Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
The SQL in your SP is wrong. You probably want
Select @code = RecItemCode from Receipt where RecTransaction = @id
In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException
when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.
The other issue is that your SQL statement if rewritten as
Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id
It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements
Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.
If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery();
and then read the output parameter value.
Another issue with your SP and code. In your SP, you have declared @code as varchar
. In your code, you specify the parameter type as Int
. Either change your SP or your code to make the types consistent.
Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write
Select RecItemCode from Receipt where RecTransaction = @id
And then use object obj = cmd.ExecuteScalar();
to get the result, no need for an output parameter in the SP or in your code.
From what I understand of the scikit-image docs (http://scikit-image.org/docs/dev/index.html), imshow() takes a ndarray as an argument, and not a dictionary:
http://scikit-image.org/docs/dev/api/skimage.io.html?highlight=imshow#skimage.io.imshow
Maybe if you post the whole stack trace, we could see that the TypeError comes somewhere deep from imshow().
Try this'
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<!-- table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<!-- end table -->
<script>
$(function() {
$('#example').DataTable();
$("#from_date").datepicker({
dateFormat: "mm/d/yy",
maxDate: 0,
onSelect: function () {
var minDate = $(this).datepicker('getDate');
$('#to_date').datepicker('setDate', minDate);
$('#to_date').datepicker('option', 'maxDate', 0);
$('#to_date').datepicker('option', 'minDate', minDate);
}
});
$('#to_date').datepicker({
dateFormat: "mm/d/yy"
});
});
</script>
A variable is declared if accessing the variable name will not produce a ReferenceError
. The expression typeof variableName !== 'undefined'
will be false
in only one of two cases:
var variableName
in scope), orundefined
(i.e., the variable's value is not defined)Otherwise, the comparison evaluates to true
.
If you really want to test if a variable is declared or not, you'll need to catch
any ReferenceError
produced by attempts to reference it:
var barIsDeclared = true;
try{ bar; }
catch(e) {
if(e.name == "ReferenceError") {
barIsDeclared = false;
}
}
If you merely want to test if a declared variable's value is neither undefined
nor null
, you can simply test for it:
if (variableName !== undefined && variableName !== null) { ... }
Or equivalently, with a non-strict equality check against null
:
if (variableName != null) { ... }
Both your second example and your right-hand expression in the &&
operation tests if the value is "falsey", i.e., if it coerces to false
in a boolean context. Such values include null
, false
, 0
, and the empty string, not all of which you may want to discard.
This is a simple solution:
Example 1
my $var1 = "123abc";
print $var1 + 0;
Result
123
Example 2
my $var2 = "abc123";
print $var2 + 0;
Result
0
Just use wpdb->insert(tablename, coloumn, format)
and wp will prepare that's query
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"name" => $name,
"email" => $email,
"phone" => $phone,
"country" => $country,
"course" => $course,
"message" => $message,
"datesent" => $now ,
));
?>
These do the same thing:
window.location.assign(url);
window.location = url;
window.location.href = url;
They simply navigate to the new URL. The replace
method on the other hand navigates to the URL without adding a new record to the history.
So, what you have read in those many forums is not correct. The assign
method does add a new record to the history.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/location
Activator.CreateInstance()
returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load
, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null);
should do it.
Put this code in a file called MY_Exceptions.php in application/core folder:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/**
* Class dealing with errors as exceptions
*/
class MY_Exceptions extends CI_Exceptions
{
/**
* Force exception throwing on erros
*/
public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = implode(" / ", (!is_array($message)) ? array($message) : $message);
throw new CiError($message);
}
}
/**
* Captured error from Code Igniter
*/
class CiError extends Exception
{
}
It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:
$db['default']['db_debug'] = true;
It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change
event.
You can handle the blur
event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.
You can use jquery attr method
$("#delete").attr("hidden",true);
why?
because there is a great chance that your database contains serialized data (especially wp_options table), so using just "replace" might break data.
Use recommended serialization: https://puvox.software/tools/wordpress-migrator
I found that calling of stored procedures in code-first approach is not convenient.
I prefer to use Dapper
instead.
The following code was written with Entity Framework:
var clientIdParameter = new SqlParameter("@ClientId", 4);
var result = context.Database
.SqlQuery<ResultForCampaign>("GetResultsForCampaign @ClientId", clientIdParameter)
.ToList();
The following code was written with Dapper
:
return Database.Connection.Query<ResultForCampaign>(
"GetResultsForCampaign ",
new
{
ClientId = 4
},
commandType: CommandType.StoredProcedure);
I believe the second piece of code is simpler to understand.
There is no separate chromedriver binary for Windows 64 bit. Chromedriver 32 bit binary works for both 32 as well as 64 bit versions of Windows. As of today, you can find the latest version of chromedriver Windows binary at https://chromedriver.storage.googleapis.com/2.25/chromedriver_win32.zip
You can ssh
directly from the Terminal on Mac, but you need to use a .PEM
key rather than the putty
.PPK
key. You can use PuttyGen on Windows to convert from .PEM
to .PPK
, I'm not sure about the other way around though.
You can also convert the key using putty
for Mac via port
or brew
:
sudo port install putty
or
brew install putty
This will also install puttygen
. To get puttygen
to output a .PEM
file:
puttygen privatekey.ppk -O private-openssh -o privatekey.pem
Once you have the key, open a terminal window and:
ssh -i privatekey.pem [email protected]
The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.
chmod go-rw privatekey.pem
Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.
This
SELECT CONVERT(NVARCHAR(30), GETDATE(), 126)
will produce this
2009-05-01T14:18:12.430
And some more detail on this can be found at MSDN.
If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.
This option comes in curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg
I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.
The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.
I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.
I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.
?foldername
?foldername
?foldername
Try spannableStringbuilder. Using this we can create string with multiple font sizes.
When you $ pip install jupyter
several dependencies are installed. The best way to uninstall it completely is by running:
$ pip install pip-autoremove
$ pip-autoremove jupyter -y
Kindly refer to this related question.
pip-autoremove
removes a package and its unused dependencies. Here are the docs.
Sorry, not enough rep to add a comment, but from zmbq's answer:
Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.
is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:
bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;
If one or both of your dates are in the future, then I'm afraid you're SOL if you want to-the-second accuracy. UTC time has leap seconds that aren't known until about 6 months before they happen, so any dates further out than that can be inaccurate by some number of seconds (and in practice, since people don't update their machines that often, you may find that any time in the future is off by some number of seconds).
This gives a good explanation of the theory of designing date/time libraries and why this is so: http://www.boost.org/doc/libs/1_41_0/doc/html/date_time/details.html#date_time.tradeoffs
var json1=["Chennai","Bangalore"];
var json2=["TamilNadu","Karanataka"];
finaljson=json1.concat(json2);
console.error(message); //gives you the red errormessage
console.log(message); //gives the default message
console.warn(message); //gives the warn message with the exclamation mark in front of it
console.info(message); //gives an info message with an 'i' in front of the message
You also can add CSS to your logging messages:
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
You have two options; either handle the exception or test the length:
if len(dlist) > 1:
newlist.append(dlist[1])
continue
or
try:
newlist.append(dlist[1])
except IndexError:
pass
continue
Use the first if there often is no second item, the second if there sometimes is no second item.
As long as you have the firewall set to allow the port that your SQL Server instance is using, all you need to do is change Data Source from =Server name
to =IP,Port
ie, in the connection string use something like this.
Data Source=190.190.1.100,1433;
You should not have to change anything on the client side.
Sample code testing div() and combined division & mod. I compiled these with gcc -O3, I had to add the call to doNothing to stop the compiler from optimising everything out (output would be 0 for the division + mod solution).
Take it with a grain of salt:
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
extern doNothing(int,int); // Empty function in another compilation unit
int main() {
int i;
struct timeval timeval;
struct timeval timeval2;
div_t result;
gettimeofday(&timeval,NULL);
for (i = 0; i < 1000; ++i) {
result = div(i,3);
doNothing(result.quot,result.rem);
}
gettimeofday(&timeval2,NULL);
printf("%d",timeval2.tv_usec - timeval.tv_usec);
}
Outputs: 150
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
extern doNothing(int,int); // Empty function in another compilation unit
int main() {
int i;
struct timeval timeval;
struct timeval timeval2;
int dividend;
int rem;
gettimeofday(&timeval,NULL);
for (i = 0; i < 1000; ++i) {
dividend = i / 3;
rem = i % 3;
doNothing(dividend,rem);
}
gettimeofday(&timeval2,NULL);
printf("%d",timeval2.tv_usec - timeval.tv_usec);
}
Outputs: 25
You can put an image into ::before pseudoelement and set the same dimensions for as is the image + add overflow:hidden, like:
li a::before{
content:url('img');
width:20px;
height:10px
}
a {
overflow:hidden;
width:20px;
height:10px
}
I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:
var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));
Example:
var answer = value === 'foo' ? 1 :
(value === 'bar' ? 2 :
(value === 'foobar' ? 3 : 0));
Minimal runnable example
If a concept is not clear, there is a simpler example that you haven't seen that explains it.
In this case, that example is the Linux x86_64 assembly freestanding (no libc) hello world:
hello.S
.text
.global _start
_start:
/* write */
mov $1, %rax /* syscall number */
mov $1, %rdi /* stdout */
mov $msg, %rsi /* buffer */
mov $len, %rdx /* buffer len */
syscall
/* exit */
mov $60, %rax /* exit status */
mov $0, %rdi /* syscall number */
syscall
msg:
.ascii "hello\n"
len = . - msg
Assemble and run:
as -o hello.o hello.S
ld -o hello.out hello.o
./hello.out
Outputs the expected:
hello
Now let's use strace on that example:
env -i ASDF=qwer strace -o strace.log -s999 -v ./hello.out arg0 arg1
cat strace.log
We use:
env -i ASDF=qwer
to control the environment variables: https://unix.stackexchange.com/questions/48994/how-to-run-a-program-in-a-clean-environment-in-bash-s999 -v
to show fuller information on the logsstrace.log
now contains:
execve("./hello.out", ["./hello.out", "arg0", "arg1"], ["ASDF=qwer"]) = 0
write(1, "hello\n", 6) = 6
exit(0) = ?
+++ exited with 0 +++
With such a minimal example, every single character of the output is self evident:
execve
line: shows how strace
executed hello.out
, including CLI arguments and environment as documented at man execve
write
line: shows the write system call that we made. 6
is the length of the string "hello\n"
.
= 6
is the return value of the system call, which as documented in man 2 write
is the number of bytes written.
exit
line: shows the exit system call that we've made. There is no return value, since the program quit!
More complex examples
The application of strace is of course to see which system calls complex programs are actually doing to help debug / optimize your program.
Notably, most system calls that you are likely to encounter in Linux have glibc wrappers, many of them from POSIX.
Internally, the glibc wrappers use inline assembly more or less like this: How to invoke a system call via sysenter in inline assembly?
The next example you should study is a POSIX write
hello world:
main.c
#define _XOPEN_SOURCE 700
#include <unistd.h>
int main(void) {
char *msg = "hello\n";
write(1, msg, 6);
return 0;
}
Compile and run:
gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
This time, you will see that a bunch of system calls are being made by glibc before main
to setup a nice environment for main.
This is because we are now not using a freestanding program, but rather a more common glibc program, which allows for libc functionality.
Then, at the every end, strace.log
contains:
write(1, "hello\n", 6) = 6
exit_group(0) = ?
+++ exited with 0 +++
So we conclude that the write
POSIX function uses, surprise!, the Linux write
system call.
We also observe that return 0
leads to an exit_group
call instead of exit
. Ha, I didn't know about this one! This is why strace
is so cool. man exit_group
then explains:
This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.
And here is another example where I studied which system call dlopen
uses: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710
Tested in Ubuntu 16.04, GCC 6.4.0, Linux kernel 4.4.0.
$()
means: "first evaluate this, and then evaluate the rest of the line".
Ex :
echo $(pwd)/myFile.txt
will be interpreted as
echo /my/path/myFile.txt
On the other hand ${}
expands a variable.
Ex:
MY_VAR=toto
echo ${MY_VAR}/myFile.txt
will be interpreted as
echo toto/myFile.txt
Why can't I use it as
bash$ while ((i=0;i<10;i++)); do echo $i; done
I'm afraid the answer is just that the bash syntax for while
just isn't the same as the syntax for for
.
To answer my own question, the trick is to turn auto scaling off...
p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
I like a few usages of Java enum:
enum with value parameters:
enum StateEnum {
UNDEFINED_POLL ( 1 * 1000L, 4 * 1000L),
SUPPORT_POLL ( 1 * 1000L, 5 * 1000L),
FAST_POLL ( 2 * 1000L, 4 * 60 * 1000L),
NO_POLL ( 1 * 1000L, 6 * 1000L);
...
}
switch example:
private void queuePoll(StateEnum se) {
// debug print se.name() if needed
switch (se) {
case UNDEFINED_POLL:
...
break;
case SUPPORT_POLL:
...
break;
I was successful using tidy
command line utility. On linux I installed it quickly with apt-get install tidy
. Then the command:
tidy -q -asxml --numeric-entities yes source.html >file.xml
gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.
This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)
No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?
First Activity Code :
Intent mIntent = new Intent(ActivityA.this, ActivityB.class);
mIntent.putExtra("easyPuzzle", easyPuzzle);
Second Activity Code :
String easyPuzzle = getIntent().getStringExtra("easyPuzzle");
Try this.
ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
If you used a raw socket (SOCK_RAW
) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port)
tuples (~2^64 per local address).
It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.
The way to do this in bash is
zsh <<< '> test <<< "Hello World!"'
This is one of the interesting differences between zsh and bash: given an unchained >
or >>
, zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful - if it were only standard.
I tried to use this to send & append my ssh key over ssh to a remote authorized_keys
file, but the remote host was bash, of course, and quietly did nothing.
And that's why you should just use cat
.
java
packages are base, and javax
packages are extensions.
Swing was an extension because AWT was the original UI API. Swing came afterwards, in version 1.1.
I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs
.
So I solved my problem like this:
# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`
test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH
Et voilà !
Unless you have sudo permissions to change it or its in your own usergroup/account you will not be able to get into it.
Check out man chmod
in the terminal for more information about changing permissions of a directory.
Use the std::vector
class from the standard library.
You can avoid refactoring your code by including the following JavaScript code
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
return this;
}
});
You'll have to use an HttpServletRequestWrapper:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getHeader(String name) {
final String value = request.getParameter(name);
if (value != null) {
return value;
}
return super.getHeader(name);
}
};
chain.doFilter(wrapper, response);
}
Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames
for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.
Here is a complete example for navigating valid URL on a new tab with focused.
HTML:
<div class="panel">
<p>
Enter Url:
<input type="text" id="txturl" name="txturl" size="30" class="weburl" />
<input type="button" id="btnopen" value="Open Url in New Tab" onclick="openURL();"/>
</p>
</div>
CSS:
.panel{
font-size:14px;
}
.panel input{
border:1px solid #333;
}
JAVASCRIPT:
function isValidURL(url) {
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (RegExp.test(url)) {
return true;
} else {
return false;
}
}
function openURL() {
var url = document.getElementById("txturl").value.trim();
if (isValidURL(url)) {
var myWindow = window.open(url, '_blank');
myWindow.focus();
document.getElementById("txturl").value = '';
} else {
alert("Please enter valid URL..!");
return false;
}
}
I have also created a bin with the solution on http://codebins.com/codes/home/4ldqpbw
I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.
In parent window use:
<head>
<style>
.disableWin{
pointer-events: none;
}
</style>
<script type="text/javascript">
function openPopUp(url) {
disableParentWin();
var win = window.open(url);
win.focus();
checkPopUpClosed(win);
}
/*Function to detect pop up is closed and take action to enable parent window*/
function checkPopUpClosed(win) {
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
enableParentWin();
}
}, 1000);
}
/*Function to enable parent window*/
function enableParentWin() {
window.document.getElementById('mainDiv').class="";
}
/*Function to enable parent window*/
function disableParentWin() {
window.document.getElementById('mainDiv').class="disableWin";
}
</script>
</head>
<body>
<div id="mainDiv class="">
</div>
</body>
package com.example.sandeep.googlemapsample;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener,
View.OnClickListener {
private static final String TAG = "MapsActivity";
private GoogleMap mMap;
private double longitude;
private double latitude;
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
// .compassEnabled(true);
// Add a marker in Sydney and move the camera
LatLng india = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
private void moveMap() {
/**
* Creating the latlng object to store lat, long coordinates
* adding marker to map
* move the camera with animation
*/
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onClick(View view) {
Log.v(TAG,"view click event");
}
@Override
public void onConnected(@Nullable Bundle bundle) {
getCurrentLocation();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onMapLongClick(LatLng latLng) {
// mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
}
@Override
public void onMarkerDragStart(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDrag(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDragEnd(Marker marker) {
// getting the Co-ordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//move to current position
moveMap();
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
@Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
return true;
}
}
I thought by setting the first element to a null would clear the entire contents of a char array.
That is not correct as you discovered
However, this only sets the first element to null.
Exactly!
You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.
However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
Kendo grid is good as well as Wijmo. I know Kendo comes with Angular bindings for their datasource and I think Wijmo has an Angular plugin. Neither are free though.
xxdiff if you're in Linux land.
Building on tkerwin's answer, if you happen to have nested parentheses like in
st = "sum((a+b)/(c+d))"
his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d)
, because find searches from the left of the string, and would stop at the first closing parenthesis.
To fix that, you need to use rfind
for the second part of the operation, so it would become
st[st.find("(")+1:st.rfind(")")]
You can't do it in a (This isn't quite true, as Sean points out in the comments. See note at the end.)switch
unless you're doing full string matching; that's doing substring matching.
If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:
switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
...but again, that only works if that's the complete string you're matching. It would fail if base_url_string
were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.
Update: Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):
function test(str) {
switch (true) {
case /xyz/.test(str):
display("• Matched 'xyz' test");
break;
case /test/.test(str):
display("• Matched 'test' test");
break;
case /ing/.test(str):
display("• Matched 'ing' test");
break;
default:
display("• Didn't match any test");
break;
}
}
That works because of the way JavaScript switch
statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case
) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.
Please find code for respected region.
Controller
ViewBag.hdnFlag= Session["hdnFlag"];
View
<input type="hidden" value="@ViewBag.hdnFlag" id="hdnFlag" />
JavaScript
var hdnFlagVal = $("#hdnFlag").val();
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
<body onload="initialize()">
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding
I found a website that will do this for you: http://tmpvar.com/markdown.html. Paste in your Markdown, and it'll display it for you. It seems to work just fine!
However, it doesn't seem to handle the syntax highlighting option for code; that is, the ~~~ruby
feature doesn't work. It just prints 'ruby'.
Fix:
I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".
After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.
C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
Volume in drive C is Windows
Volume Serial Number is 8EE6-5DD0
Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319
03/18/2010 08:23 PM 19,296 aspnet_regbrowsers.exe
03/18/2010 08:23 PM 36,696 aspnet_regiis.exe
03/18/2010 08:23 PM 102,232 aspnet_regsql.exe
3 File(s) 158,224 bytes
0 Dir(s) 34,836,508,672 bytes free
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>
However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.
HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.
Instead of
$("form").submit()
try this
$("<input type='submit' id='btn_tmpSubmit'/>").css('display','none').appendTo('form');
$("#btn_tmpSubmit").click();
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");
base but probably slow:
n <- 1
for(i in strsplit(as.character(before$type),'_and_')){
before[n, 'type_1'] <- i[[1]]
before[n, 'type_2'] <- i[[2]]
n <- n + 1
}
## attr type type_1 type_2
## 1 1 foo_and_bar foo bar
## 2 30 foo_and_bar_2 foo bar_2
## 3 4 foo_and_bar foo bar
## 4 6 foo_and_bar_2 foo bar_2
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
To use the Bash builtin time
rather than /bin/time
you can set this variable:
TIMEFORMAT='%3R'
which will output the real time that looks like this:
5.009
or
65.233
The number specifies the precision and can range from 0 to 3 (the default).
You can use:
TIMEFORMAT='%3lR'
to get output that looks like:
3m10.022s
The l
(ell) gives a long format.
to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link
The basic answer to the question in the title is eval(as.symbol(variable_name_as_string))
as Josh O'Brien uses. e.g.
var.name = "x"
assign(var.name, 5)
eval(as.symbol(var.name)) # outputs 5
Or more simply:
get(var.name) # 5
showInLegend
is a series-specific option that can hide the series from the legend. If the requirement is to hide the legends completely then it is better to use enabled: false
property as shown below:
legend: {
enabled: false
}
More information about legend
is here
Let's say this is your dataframe.
You can rename the columns using two methods.
Using dataframe.columns=[#list]
df.columns=['a','b','c','d','e']
The limitation of this method is that if one column has to be changed, full column list has to be passed. Also, this method is not applicable on index labels. For example, if you passed this:
df.columns = ['a','b','c','d']
This will throw an error. Length mismatch: Expected axis has 5 elements, new values have 4 elements.
Another method is the Pandas rename()
method which is used to rename any index, column or row
df = df.rename(columns={'$a':'a'})
Similarly, you can change any rows or columns.
Domain Driven Design is a methodology and process prescription for the development of complex systems whose focus is mapping activities, tasks, events, and data within a problem domain into the technology artifacts of a solution domain.
The emphasis of Domain Driven Design is to understand the problem domain in order to create an abstract model of the problem domain which can then be implemented in a particular set of technologies. Domain Driven Design as a methodology provides guidelines for how this model development and technology development can result in a system that meets the needs of the people using it while also being robust in the face of change in the problem domain.
The process side of Domain Driven Design involves the collaboration between domain experts, people who know the problem domain, and the design/architecture experts, people who know the solution domain. The idea is to have a shared model with shared language so that as people from these two different domains with their two different perspectives discuss the solution they are actually discussing a shared knowledge base with shared concepts.
The lack of a shared problem domain understanding between the people who need a particular system and the people who are designing and implementing the system seems to be a core impediment to successful projects. Domain Driven Design is a methodology to address this impediment.
It is more than having an object model. The focus is really about the shared communication and improving collaboration so that the actual needs within the problem domain can be discovered and an appropriate solution created to meet those needs.
Domain-Driven Design: The Good and The Challenging provides a brief overview with this comment:
DDD helps discover the top-level architecture and inform about the mechanics and dynamics of the domain that the software needs to replicate. Concretely, it means that a well done DDD analysis minimizes misunderstandings between domain experts and software architects, and it reduces the subsequent number of expensive requests for change. By splitting the domain complexity in smaller contexts, DDD avoids forcing project architects to design a bloated object model, which is where a lot of time is lost in working out implementation details — in part because the number of entities to deal with often grows beyond the size of conference-room white boards.
Also see this article Domain Driven Design for Services Architecture which provides a short example. The article provides the following thumbnail description of Domain Driven Design.
Domain Driven Design advocates modeling based on the reality of business as relevant to our use cases. As it is now getting older and hype level decreasing, many of us forget that the DDD approach really helps in understanding the problem at hand and design software towards the common understanding of the solution. When building applications, DDD talks about problems as domains and subdomains. It describes independent steps/areas of problems as bounded contexts, emphasizes a common language to talk about these problems, and adds many technical concepts, like entities, value objects and aggregate root rules to support the implementation.
Martin Fowler has written a number of articles in which Domain Driven Design as a methodology is mentioned. For instance this article, BoundedContext, provides an overview of the bounded context concept from Domain Driven Development.
In those younger days we were advised to build a unified model of the entire business, but DDD recognizes that we've learned that "total unification of the domain model for a large system will not be feasible or cost-effective" 1. So instead DDD divides up a large system into Bounded Contexts, each of which can have a unified model - essentially a way of structuring MultipleCanonicalModels.
Below SCP format works for me
scp -i /path/my-key-pair.pem [email protected]:~/SampleFile.txt ~/SampleFile2.txt
SampleFile.txt: It will be the path from your root directory(In my case, /home/ubuntu). in my case the file which I wanted to download was at /var/www
SampleFile2.txt: It will be path of your machine's root path(In my case, /home/MyPCUserName)
So, I have to write below command
scp -i /path/my-key-pair.pem [email protected]:~/../../var/www/Filename.zip ~/Downloads
There are many plugins for doing that. I normally use datatables it works great. http://datatables.net/
Use Tkinter there are a ton of tutorials online for this. basically, you can create events. Here is a link to a great site! This makes it easy to capture clicks. Also, if you are trying to make a game, Tkinter also has a GUI. Although, I wouldn't recommend Python for games at all, it could be a fun experiment. Good Luck!
If you want to make interactive console:
#!/usr/bin/env ruby
require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
addends << addend_string.to_i
puts "#{addends.join(' + ')} = #{addends.sum}"
end
Usage (assuming you put above snippet into summator
file in current directory):
chmod +x summator
./summator
> 1
1 = 1
> 2
1 + 2 = 3
Use Ctrl + D
to exit
If you're looking for a Facebook like scroll bar, then I'd highly recommend you take a look at this one:
similar to R0byn's experience, i was experimenting with a Powerpoint slide presentation and dumped out the main body of text on the slide, finding that all the places where one would typically find carriage return (ASCII 13/0x0d/^M) or line feed/new line (ASCII 10/0x0a/^J) characters, it uses vertical tab (ASCII 11/0x0b/^K) instead, presumably for the exact reason that dan04 described above for Word: to serve as a "newline" while staying within the same paragraph. good question though as i totally thought this character would be as useless as a teletype terminal today.
I needed to get the number of occurrences of each distinct value. The column contained Region info. The simple SQL query I ended up with was:
SELECT Region, count(*)
FROM item
WHERE Region is not null
GROUP BY Region
Which would give me a list like, say:
Region, count
Denmark, 4
Sweden, 1
USA, 10
How about something like this.
Test the live example: http://jsfiddle.net/6hBZU/1/
It assumes that the string will always end with the extension:
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif':
alert('was jpg png gif'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
alert('was zip rar');
break;
case 'pdf':
alert('was pdf');
break;
default:
alert('who knows');
}
};
openFile("somestring.png");
EDIT: I mistakenly deleted part of the string in openFile("somestring.png");
. Corrected. Had it in the Live Example, though.
You'll need to use UNION
to combine the results of two queries. In your case:
SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum
Note - If you use UNION ALL
as in above, it's no slower than running the two queries separately as it does no duplicate-checking.
DPLYR makes this really easy.
x<-santa%>%
count(Believe)
If you wanted to count by a group; for instance, how many males v females believe, just add a group_by
:
x<-santa%>%
group_by(Gender)%>%
count(Believe)
The plain and simple answer is yes, VanillaJS === JavaScript, as prescribed by Dr B. Eich.
For something really basic use this:
<a href="#middle">Go To Middle</a>
Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.
You are referring to the type rather than the instance. Make 'Model' lowercase in the example in your second and fourth code samples.
Model.GetHtmlAttributes
should be
model.GetHtmlAttributes
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar
or toCalendar
(as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat
is used to convert Strings to Dates (parse()
) or Dates to Strings (format()
). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
The rsa.pub (i.e. public key generated), needs to be added on the github>> settings>>ssh keys page. Check that, you have not added this public key in the repository-settings >> deployment keys. If so, remove the entry from here and add to the first place mentioned.
Setup of the pub-private keys in detail.
It will work hence!
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
This one saves KEYS & VALUES
function array2string($data){
$log_a = "";
foreach ($data as $key => $value) {
if(is_array($value)) $log_a .= "[".$key."] => (". array2string($value). ") \n";
else $log_a .= "[".$key."] => ".$value."\n";
}
return $log_a;
}
Hope it helps someone.
In Python 3, the reduce
has been removed: Release notes. Nevertheless you can use the functools module
import operator, functools
def product(xs):
return functools.reduce(operator.mul, xs, 1)
On the other hand, the documentation expresses preference towards for
-loop instead of reduce
, hence:
def product(xs):
result = 1
for i in xs:
result *= i
return result
In this case, one of the easiest and best approach is to first cast it to list
and then use where
or select
.
result = result.ToList().where(p => date >= p.DOB);
If you set unique parameters, then the cache does not work, for example:
$.ajax({
url : "my_url",
data : {
'uniq_param' : (new Date()).getTime(),
//other data
}});
km=[]
for i in range(num_data.shape[1]):
kmeans = KMeans(n_clusters=ncluster[i])#we take number of cluster bandwidth theory
ndata=num_data[[i]].dropna()
ndata['labels']=kmeans.fit_predict(ndata.values)
cluster=ndata
co=cluster.groupby(['labels'])[cluster.columns[0]].count()#count for frequency
me=cluster.groupby(['labels'])[cluster.columns[0]].median()#median
ma=cluster.groupby(['labels'])[cluster.columns[0]].max()#Maximum
mi=cluster.groupby(['labels'])[cluster.columns[0]].min()#Minimum
stat=pd.concat([mi,ma,me,co],axis=1)#Add all column
stat['variable']=stat.columns[1]#Column name change
stat.columns=['Minimum','Maximum','Median','count','variable']
l=[]
for j in range(ncluster[i]):
n=[mi.loc[j],ma.loc[j]]
l.append(n)
stat['Class']=l
stat=stat.sort(['Minimum'])
stat=stat[['variable','Class','Minimum','Maximum','Median','count']]
if missing_num.iloc[i]>0:
stat.loc[ncluster[i]]=0
if stat.iloc[ncluster[i],5]==0:
stat.iloc[ncluster[i],5]=missing_num.iloc[i]
stat.iloc[ncluster[i],0]=stat.iloc[0,0]
stat['Percentage']=(stat[[5]])*100/count_row#Freq PERCENTAGE
stat['Cumulative Percentage']=stat['Percentage'].cumsum()
km.append(stat)
cluster=pd.concat(km,axis=0)## see documentation for more info
cluster=cluster.round({'Minimum': 2, 'Maximum': 2,'Median':2,'Percentage':2,'Cumulative Percentage':2})
There's a relatively new way of doing transparency, it's called HEXA (HEX + Alpha). It takes in 8 digits instead of 6. The last pair is Alpha. So the pattern of pairs is #RRGGBBAA. Having 4 digits also works: #RGBA
I am not sure about its browser support for now but, you can check the DRAFT Docs for more information.
§ 4.2. The RGB hexadecimal notations: #RRGGBB
The syntax of a
<hex-color>
is a<hash-token>
token whose value consists of 3, 4, 6, or 8 hexadecimal digits. In other words, a hex color is written as a hash character, "#", followed by some number of digits0-9
or lettersa-f
(the case of the letters doesn’t matter -#00ff00
is identical to#00FF00
).8 digits
The first 6 digits are interpreted identically to the 6-digit notation. The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where
00
represents a fully transparent color andff
represent a fully opaque color.Example 3
In other words,#0000ffcc
represents the same color asrgba(0, 0, 100%, 80%)
(a slightly-transparent blue).4 digits
This is a shorter variant of the 8-digit notation, "expanded" in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where
0
represents the minimum value andf
represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.
For the most part, Chrome and Firefox have started supporting this:
Connect to postgres via existing superuser.
Create a Database by the name of user you are connecting through to postgres.
create database username;
Now try to connect via username
Just subscribe to the control's ToolTipTextNeeded event, and return e.TooltipText, much simpler.
First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:
var options = [
set0 = ['Option 1','Option 2'],
set1 = ['First Option','Second Option','Third Option']
];
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));
Here's a demo. You might also want to note that set0
and set1
are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:
var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};
And access them like so:
makeUL(options.set0);
If you really need a "Backup" then you also need database schema, like table definitions, view definitions, store procedures and so on. A backup of a database isn't just the data.
The value of the mysqldump format for backup is specifically that it is very EASY to use it to restore mysql databases. A backup that isn't easily restored is far less useful. If you are looking for a method to reliably backup mysql data to so you can restore to a mysql server then I think you should stick with the mysqldump tool.
Mysql is free and runs on many different platforms. Setting up a new mysql server that I can restore to is simple. I am not at all worried about not being able to setup mysql so I can do a restore.
I would be far more worried about a custom backup/restore based on a fragile format like csv/tsv failing. Are you sure that all your quotes, commas, or tabs that are in your data would get escaped correctly and then parsed correctly by your restore tool?
If you are looking for a method to extract the data then see several in the other answers.
It is a public final
field for the array type. You can refer to the document below:
http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7
You could do something like this:
> +(Math.floor(y/x)*x).toFixed(15);
1.2
If you want to read a CSV File with encoding utf-8, a minimalistic approach that I recommend you is to use something like this:
with open(file_name, encoding="utf8") as csv_file:
With that statement, you can use later a CSV reader to work with.
It´s out of the scope of the question, but I think it might be also interesting to know how to link to a route. The query would look like this:
https://www.google.es/maps/dir/'52.51758801683297,13.397978515625027'/'52.49083837044266,13.369826049804715'
just click on image and will change:
<div>_x000D_
<img src="https://i.imgur.com/jgyJ7Oj.png" id="imgLoad">_x000D_
</div>_x000D_
_x000D_
<script type='text/javascript'>_x000D_
var img = document.getElementById('imgLoad'); _x000D_
img.onclick = function() { img.src = "https://i.imgur.com/PqpOLwp.png"; }_x000D_
</script>
_x000D_
In case someone want's to do this with a cronjob, please keep in mind that this:
find .session/ -atime +7 -exec rm {} \;
is really slow, when having a lot of files.
Consider using this instead:
find .session/ -atime +7 | xargs -r rm
In Case you have spaces in you file names use this:
find .session/ -atime +7 -print0 | xargs -0 -r rm
xargs
will fill up the commandline with files to be deleted, then run the rm
command a lot lesser than -exec rm {} \;
, which will call the rm
command for each file.
Just my two cents
A nifty non-caching async one liner for node 15 modules:
import { readFile } from 'fs/promises';
const data = await readFile('{{ path }}').then(json => JSON.parse(json)).catch(() => null);
Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:
numpy.linalg.svd numpy.linalg.qr
It's also possible to do something like this with ng-style
:
ng-style="image_path != '' && {'background-image':'url('+image_path+')'}"
which would not attempt to fetch a non-existing image.
I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:
var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;
The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.
On the Official SQL Server 2012 ISO that's for download, just navigate to \x64\Setup\ (or \x86\Setup) and you will find "sql_ssms.msi". It's only about 60 MB, and since it's an .MSI you can probably provision it to be installed automatically (say for a large lab or classroom environment).
if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
// strings are equal except for possibly case
}
The documentation is located at Search and Comparison Methods
You need a bit more information so that the browser knows what you want. For instance, the children of the container need to be told "how" to flex.
I've added #wrapper > * { flex: 1; margin: auto; }
to your CSS and changed inline-flex
to flex
, and you can see how the elements now space themselves out evenly on the page.
You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.
The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.
With an appropriate predicate in hand, problem 1 simplifies to:
low_primes = {x for x in range(1, 100) if is_prime(x)}
And problem 2 simplifies to:
low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}
Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."
P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.
@SC_Chupacabra has correct answer for modifying behavior.
I generally prefer CTRL + PAGE UP / DOWN for my navigation, rather than using the TAB key.
{
"key": "ctrl+pageUp",
"command": "workbench.action.nextEditor"
},
{
"key": "ctrl+pageDown",
"command": "workbench.action.previousEditor"
}
&& it's operation return true only if both operand it's true which implies
bool and(bool b1, bool b2)]
{
if(b1==true)
{
if(b2==true)
return true;
}
return false;
}
|| it's operation return true if one or both operand it's true which implies
bool or(bool b1,bool b2)
{
if(b1==true)
return true;
if(b2==true)
return true;
return false;
}
if You write
y=45&&34//45 binary 101101, 35 binary 100010
in result you have
y=32// in binary 100000
Therefore, the which I wrote above is used with respect to every pair of bits
Random character:
String.fromCharCode(i); //where is an int
Random int:
Math.floor(Math.random()*100);
Put it all together:
function randomNum(hi){
return Math.floor(Math.random()*hi);
}
function randomChar(){
return String.fromCharCode(randomNum(100));
}
function randomString(length){
var str = "";
for(var i = 0; i < length; ++i){
str += randomChar();
}
return str;
}
var RandomString = randomString(32); //32 length string
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
You can get that error if you have an object with the same name as the schema. For example:
create sequence s2;
begin
s2.a;
end;
/
ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored
When you refer to S2.MY_FUNC2
the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2
there is no confusion, so it works.
The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.
It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.
select owner, object_type, object_name
from all_objects
where object_name = 'S2';
I have just faced this problem, and the solution is that the property "mail.smtp.user" should be your email (not username).
The example for gmail user:
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
HTML4 specification states that:
Inline elements may contain only data and other inline elements
Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.
HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.
try this method
$("your id or class name").css({ 'margin-top': '18px' });
just close the eclipse and avd emulator and restart it. It works fine
// Use this version to capture the full extended desktop (i.e. multiple screens)
Bitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width,
SystemInformation.VirtualScreen.Height,
PixelFormat.Format32bppArgb);
Graphics screenGraph = Graphics.FromImage(screenshot);
screenGraph.CopyFromScreen(SystemInformation.VirtualScreen.X,
SystemInformation.VirtualScreen.Y,
0,
0,
SystemInformation.VirtualScreen.Size,
CopyPixelOperation.SourceCopy);
screenshot.Save("Screenshot.png", System.Drawing.Imaging.ImageFormat.Png);
I resolved this by clearing App Data.
Cypress documentation admits that App Data can get corrupted:
Cypress maintains some local application data in order to save user preferences and more quickly start up. Sometimes this data can become corrupted. You may fix an issue you have by clearing this app data.
cypress open
File
-> View App Data
cy
whose content should look something
like this: production
all.log
browsers
bundles
cache
projects
proxy
state.json
cy
folderSource: https://docs.cypress.io/guides/references/troubleshooting.html#To-clear-App-Data
Double check if you have set and initial value for int and decimal values to be printed.
This sample is printing an empty line
declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)
And this sample is printing -> The number is : 1
declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)
you can use between too:
SELECT Table.date
FROM Table
WHERE date between current_date and current_date - interval '10 day';
SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
batchfiles perform simple string substitution with variables. so, a simple
goto :language%language%
echo notfound
...
does this without any need for if.
The following works fine for me in Excel 2007. It is simple, and performs a full copy (retains all formatting, etc.):
Sheets("Sheet1").Columns(1).Copy Destination:=Sheets("Sheet2").Columns(2)
"Columns" returns a Range object, and so this is utilizing the "Range.Copy" method. "Destination" is an option to this method - if not provided the default is to copy to the paste buffer. But when provided, it is an easy way to copy.
As when manually copying items in Excel, the size and geometry of the destination must support the range being copied.
The following sequence of commands does remove every name from the current module:
>>> import sys
>>> sys.modules[__name__].__dict__.clear()
I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).
Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:
>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
... if n[0]!='_': delattr(this, n)
...
>>>
This sequence leaves alone names that are private or magical, including the __builtins__
special name which houses all built-in names. So, built-ins still work -- for example:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>>
As you see, name n
(the control variable in that for
) also happens to stick around (as it's re-bound in the for
clause every time through), so it might be better to name that control variable _
, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _
is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).
Anyway, once you have determined exactly what it is you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).
You can get this exception at many different places in the MVC framework (e.g. it can't create the controller, or it can't create a model to give that controller).
The only easy way I've found to diagnose this problem is to override MVC as close to the exception as possible with your own code. Then your code will break inside Visual Studio when this exception occurs, and you can read the Type causing the problem from the stack trace.
This seems like a horrible way to approach this problem, but it's very fast, and very consistent.
For example, if this error is occurring inside the MVC DefaultModelBinder (which you will know by checking the stack trace), then replace the DefaultModelBinder with this code:
public class MyDefaultModelBinder : System.Web.Mvc.DefaultModelBinder
{
protected override object CreateModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, Type modelType)
{
return base.CreateModel(controllerContext, bindingContext, modelType);
}
}
And update your Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
...
protected void Application_Start(object sender, EventArgs e)
{
ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder();
}
}
Now the next time you get that exception, Visual Studio will stop inside your MyDefaultModelBinder class, and you can check the "modelType" property to see what type caused the problem.
The example above works for when you get the "No parameterless constructor defined for this object" exception during model binding, only. But similar code can be written for other extension points in MVC (e.g. controller construction).
Other answers already on Stackoverflow:
From perlfaq8:
When you build modules, tell Perl where to install the modules.
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:
% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit
For Build.PL-based distributions, use the --install_base option:
perl Build.PL --install_base /mydir/perl
You can configure CPAN.pm to automatically use this option too:
% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit
If you look at the documentation for str.split
:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
In other words, if you're trying to figure out what to pass to split
to get '\n\tName: Jane Smith'
to ['Name:', 'Jane', 'Smith']
, just pass nothing (or None).
This almost solves your whole problem. There are two parts left.
First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:
s.split(None, 1)
Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:
key, value = s.split(None, 1)
key = key[:-1]
There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.
Laravel Framework 5.6.26
return more than one array then we use compact('array1', 'array2', 'array3', ...)
to return view.
viewblade
is the frontend (view) blade.
return view('viewblade', compact('view1','view2','view3','view4'));
From the MDN documentation:
[The margin property] applies to all elements except elements with table display types other than table-caption, table and inline-table
In other words, the margin
property is not applicable to display:table-cell
elements.
Consider using the border-spacing
property instead.
Note it should be applied to a parent element with a display:table
layout and border-collapse:separate
.
For example:
HTML
<div class="table">
<div class="row">
<div class="cell">123</div>
<div class="cell">456</div>
<div class="cell">879</div>
</div>
</div>
CSS
.table {display:table;border-collapse:separate;border-spacing:5px;}
.row {display:table-row;}
.cell {display:table-cell;padding:5px;border:1px solid black;}
Different margin horizontally and vertically
As mentioned by Diego Quirós, the border-spacing
property also accepts two values to set a different margin for the horizontal and vertical axes.
For example
.table {/*...*/border-spacing:3px 5px;} /* 3px horizontally, 5px vertically */
I needed to append substrings to create an ssh command, I solved with sprintf
(Visual Studio 2013)
char gStrSshCommand[SSH_COMMAND_MAX_LEN]; // declare ssh command string
strcpy(gStrSshCommand, ""); // empty string
void appendSshCommand(const char *substring) // append substring
{
sprintf(gStrSshCommand, "%s %s", gStrSshCommand, substring);
}
We apply StandardScalar()
on a row basis.
So, for each row in a column (I am assuming that you are working with a Pandas DataFrame):
x_new = (x_original - mean_of_distribution) / std_of_distribution
Few points -
It is called Standard Scalar as we are dividing it by the standard deviation of the distribution (distr. of the feature). Similarly, you can guess for MinMaxScalar()
.
The original distribution remains the same after applying StandardScalar()
. It is a common misconception that the distribution gets changed to a Normal Distribution. We are just squashing the range into [0, 1].
Maybe try this? It seems the problem is solved after remove all the handlers in my case.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename='output.log', level=logging.INFO)
find . -name '*.ear' -exec ls -lh {} \;
just the h extra from jer.drab.org's reply. saves time converting to MB mentally ;)
this worked for me..
$sql = "desc MyTableName";
$result = @mysql_query($sql);
while($row = @mysql_fetch_array($result)){
echo $row[0]."<br>";
}
Add -lrt
to the end of g++ command line. This links in the librt.so "Real Time" shared library.
How about netstat?
http://support.microsoft.com/kb/907980
The command is netstat -anob
.
(Make sure you run command as admin)
I get:
C:\Windows\system32>netstat -anob
Active Connections
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 692
RpcSs
[svchost.exe]
TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 7540
[Skype.exe]
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:623 0.0.0.0:0 LISTENING 564
[LMS.exe]
TCP 0.0.0.0:912 0.0.0.0:0 LISTENING 4480
[vmware-authd.exe]
And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path
From jQuery.ajax()
async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
So in your request, you must do async: false
instead of async: "false"
.
Update:
The return value of ajaxSubmit
is not the return value of the success: function(){...}
. ajaxSubmit
returns no value at all, which is equivalent to undefined
, which in turn evaluates to true.
And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.
If you want to submit the form only, when the response is "Successful"
, you must return false
from ajaxSubmit
and then submit the form in the success
function, as @halilb already suggested.
Something along these lines should work
function ajaxSubmit() {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
url: "checkpass.php",
data: "password="+password,
success: function(response) {
if(response == "Successful")
{
$('form').removeAttr('onsubmit'); // prevent endless loop
$('form').submit();
}
}
});
return false;
}
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
For python 3.6
class SomeClass:
def attr_list(self, should_print=False):
items = self.__dict__.items()
if should_print:
[print(f"attribute: {k} value: {v}") for k, v in items]
return items
I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.
ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>
As you can see, it's all about the -map 0
, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.
You can create a simple batch mkv2mp4.bat
, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.
@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"
Now you can simply run
mkv2mp4 "Video with subtitles etc.mkv"
And it will create "Video with subtitles etc.mp4" with the maximum of information included.
So here is a solution for both your requests in the manner you originally asked for. It will give human readability filesize without the filesize limits everyone is experiencing. Compatible with Win Vista or newer. XP only available if Robocopy is installed. Just drop a folder on this batch file or use the better method mentioned below.
@echo off
setlocal enabledelayedexpansion
set "vSearch=Files :"
For %%i in (%*) do (
set "vSearch=Files :"
For /l %%M in (1,1,2) do (
for /f "usebackq tokens=3,4 delims= " %%A in (`Robocopy "%%i" "%%i" /E /L /NP /NDL /NFL ^| find "!vSearch!"`) do (
if /i "%%M"=="1" (
set "filecount=%%A"
set "vSearch=Bytes :"
) else (
set "foldersize=%%A%%B"
)
)
)
echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!
REM remove the word "REM" from line below to output to txt file
REM echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!>>Folder_FileCountandSize.txt
)
pause
To be able to use this batch file conveniently put it in your SendTo folder. This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.
To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.
explorer C:\Users\%username%\AppData\Roaming\Microsoft\Windows\SendTo
In Entity Framework Core.
Remove all files from migrations folder.
Type in console
dotnet ef database drop -f -v
dotnet ef migrations add Initial
dotnet ef database update
UPD: Do that only if you don't care about your current persisted data. If you do, use Greg Gum's answer
I'm not a fan of the accepted answer as it converts anything which evaluates to false to "false"
no just boolean and vis-versa.
Anyway here's my O.T.T answer, it uses the var_export
function.
var_export
works with all variable types except resource
, I have created a function which will perform a regular cast to string ((string)
), a strict cast (var_export
) and a type check, depending on the arguments provided..
if(!function_exists('to_string')){
function to_string($var, $strict = false, $expectedtype = null){
if(!func_num_args()){
return trigger_error(__FUNCTION__ . '() expects at least 1 parameter, 0 given', E_USER_WARNING);
}
if($expectedtype !== null && gettype($var) !== $expectedtype){
return trigger_error(__FUNCTION__ . '() expects parameter 1 to be ' . $expectedtype .', ' . gettype($var) . ' given', E_USER_WARNING);
}
if(is_string($var)){
return $var;
}
if($strict && !is_resource($var)){
return var_export($var, true);
}
return (string) $var;
}
}
if(!function_exists('bool_to_string')){
function bool_to_string($var){
return func_num_args() ? to_string($var, true, 'boolean') : to_string();
}
}
if(!function_exists('object_to_string')){
function object_to_string($var){
return func_num_args() ? to_string($var, true, 'object') : to_string();
}
}
if(!function_exists('array_to_string')){
function array_to_string($var){
return func_num_args() ? to_string($var, true, 'array') : to_string();
}
}
Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country
, X-AppEngine-Region
, X-AppEngine-City
and X-AppEngine-CityLatLong
headers.
An example looks like this:
X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733
Just return your existing check from a function.
function _isCurl(){
return function_exists('curl_version');
}
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.
There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.
Here's a Python 3 example:
class C(abc.ABC):
@abc.abstractmethod
def my_abstract_method(self, ...):
...
When instantiating C
, you'll get an error because my_abstract_method
is abstract. You need to implement it in a child class.
TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method
Subclass C
and implement my_abstract_method
.
class D(C):
def my_abstract_method(self, ...):
...
Now you can instantiate D
.
C.my_abstract_method
does not have to be empty. It can be called from D
using super()
.
An advantage of this over NotImplementedError
is that you get an explicit Exception
at instantiation time, not at method call time.
The stdout of the process started by the docker container is available through the docker logs $containerid
command (use -f
to keep it going forever). Another option would be to stream the logs directly through the docker remote API.
For accessing log files (only if you must, consider logging to stdout or other standard solution like syslogd) your only real-time option is to configure a volume (like Marcus Hughes suggests) so the logs are stored outside the container and available for processing from the host or another container.
If you do not need real-time access to the logs, you can export the files (in tar format) with docker export
Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:
$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
if ($cbx_group.is(":checked")) {
// checkboxes become unrequired as long as one is checked
$cbx_group.prop("required", false).each(function() {
this.setCustomValidity("");
});
} else {
// require checkboxes and set custom validation error message
$cbx_group.prop("required", true).each(function() {
this.setCustomValidity("Please select at least one checkbox.");
});
}
});
Note that my form has some checkboxes checked by default.
Maybe some of you JavaScript/JQuery wizards could tighten that up even more?
From the Command Prompt (Start \ All Programs \ Accessories \ Command Prompt):
DEL /S SqlStudio.bin
Maybe explaining the whole workflow can help.
Everything starts with the Dockerfile. The Dockerfile is the source code of the image.
Once the Dockerfile is created, you build it to create the image of the container. The image is just the "compiled version" of the "source code" which is the Dockerfile.
Once you have the image of the container, you should redistribute it using the registry. The registry is like a Git repository -- you can push and pull images.
Next, you can use the image to run containers. A running container is very similar, in many aspects, to a virtual machine (but without the hypervisor).
They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.
The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.
They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.
In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.
Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.
Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.
Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.
http://handbrake.fr is a nice high level tool with a lot of useful presets for mp4 for iPod, PS3, ... with both GUI and CLI interfaces for Linux, Windows and Mac OS X.
It comes with its own dependencies as a single statically linked fat binary so you have all the x264 / aac codecs included.
$ HandBrakeCLI -Z Universal -i myinputfile.mov -o myoutputfile.mp4
To list all the available presets:
$ HandBrakeCLI -z
The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.
However, if the only way to disable Show References is to disable CodeLens altogether.
Then, I guess I could do just that.
Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'
If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.
In short, uncheck Codelens...
Addressing Steven's comment to Sam Dufel's answer
Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?
This should do the trick:
/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/
See this page for all the different variations of 'cats' that this matches.
You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
There is an implementation available at the msinttypes project page - "This project fills the absence of stdint.h and inttypes.h in Microsoft Visual Studio".
I don't have experience with this implementation, but I've seen it recommended by others on SO.
I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.
png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
x = rnorm(500, mean = rep(1:5, 100)),
y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))
ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
Here it is the first figure:
and the second figure:
As we can see the colors do not stay fixed, for example E switches from magenta to blu.
As suggested by malcook in his comment and by hadley in his comment the code which uses limits
works properly:
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +
geom_point() +
scale_colour_discrete(drop=TRUE,
limits = levels(dataset$fCategory))
gives the following figure, which is correct:
This is the output from sessionInfo()
:
R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] methods stats graphics grDevices utils datasets base
other attached packages:
[1] ggplot2_0.9.3.1
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 dichromat_2.0-0 digest_0.6.4 grid_3.0.2
[5] gtable_0.1.2 labeling_0.2 MASS_7.3-29 munsell_0.4.2
[9] plyr_1.8 proto_0.3-10 RColorBrewer_1.0-5 reshape2_1.2.2
[13] scales_0.2.3 stringr_0.6.2
Well, the basic premise here is: no, it is not secure yet.
Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.
The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.
As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.
Either that, or if you need that sort of security, and you need local storage, create a custom application...
I know it's pretty late, but for future people stumbling upon this issue, if you want to have access to the webpack config of CRA, there's no other way except you have to run:
$ npm run eject
However, with ejection, you'll strip away yourself from CRA pipeline of updates, therefore from the point of ejection, you have to maintain it yourself.
I have come across this issue many times, and therefore I've created a template for react apps which have most of the same config as CRA, but also additional perks (like styled-components, jest unit test, Travis ci for deployments, prettier, ESLint, etc...) to make the maintenance easier. Check out the repo.
Using http://mvnrepository.com/artifact/commons-lang/commons-lang
Date date1 = new Date();
Date date2 = new Date();
if (DateUtils.truncatedCompareTo(date1, date2, Calendar.DAY_OF_MONTH) == 0)
// TRUE
else
// FALSE
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
I think that the most elegant way to do it is to implement custom Flash Scope in Spring MVC.
the main idea for the flash scope is to store data from one controller till next redirect in second controller
Please refer to my answer on the custom scope question:
The only thing that is missing in this code is the following xml configuration:
<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list><ref bean="flashScopeInterceptor"/></list>
</property>
</bean>
DWORD ReplaceString(__inout PCHAR source, __in DWORD dwSourceLen, __in const char* pszTextToReplace, __in const char* pszReplaceWith)
{
DWORD dwRC = NO_ERROR;
PCHAR foundSeq = NULL;
PCHAR restOfString = NULL;
PCHAR searchStart = source;
size_t szReplStrcLen = strlen(pszReplaceWith), szRestOfStringLen = 0, sztextToReplaceLen = strlen(pszTextToReplace), remainingSpace = 0, dwSpaceRequired = 0;
if (strcmp(pszTextToReplace, "") == 0)
dwRC = ERROR_INVALID_PARAMETER;
else if (strcmp(pszTextToReplace, pszReplaceWith) != 0)
{
do
{
foundSeq = strstr(searchStart, pszTextToReplace);
if (foundSeq)
{
szRestOfStringLen = (strlen(foundSeq) - sztextToReplaceLen) + 1;
remainingSpace = dwSourceLen - (foundSeq - source);
dwSpaceRequired = szReplStrcLen + (szRestOfStringLen);
if (dwSpaceRequired > remainingSpace)
{
dwRC = ERROR_MORE_DATA;
}
else
{
restOfString = CMNUTIL_calloc(szRestOfStringLen, sizeof(CHAR));
strcpy_s(restOfString, szRestOfStringLen, foundSeq + sztextToReplaceLen);
strcpy_s(foundSeq, remainingSpace, pszReplaceWith);
strcat_s(foundSeq, remainingSpace, restOfString);
}
CMNUTIL_free(restOfString);
searchStart = foundSeq + szReplStrcLen; //search in the remaining str. (avoid loops when replWith contains textToRepl
}
} while (foundSeq && dwRC == NO_ERROR);
}
return dwRC;
}
.... char ch; ... ch=scan.next().charAt(0); . . It's the easy way to get character.
Just check: where value > '' -- not null and not empty
-- COLUMN CONTAINS A VALUE (ie string not null and not empty) :
-- (note: "<>" gives a different result than ">")
select iif(null > '', 'true', 'false'); -- false (null)
select iif('' > '', 'true', 'false'); -- false (empty string)
select iif(' ' > '', 'true', 'false'); -- false (space)
select iif(' ' > '', 'true', 'false'); -- false (tab)
select iif('
' > '', 'true', 'false'); -- false (newline)
select iif('xxx' > '', 'true', 'false'); -- true
--
--
-- NOTE - test that tab and newline is processed as expected:
select 'x x' -- tab
select 'x
x' -- newline
You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.
$(items).each(function(i, item){
setTimeout(function(){
geoLocate("my address", function(myLatlng){
...
});
}, 200 * i);
}
We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.
CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
BEGIN
IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;
...your code here...
END
This worked for me
viewPager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (viewPager.getCurrentItem() == 0) {
viewPager.setCurrentItem(-1, false);
return true;
}
else if (viewPager.getCurrentItem() == 1) {
viewPager.setCurrentItem(1, false);
return true;
}
else if (viewPager.getCurrentItem() == 2) {
viewPager.setCurrentItem(2, false);
return true;
}
return true;
}
});
If you're targeting iOS 4.0+, you can do the following:
[executing first operation];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[executing second operation];
});
Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).
Instead, I used this method:
Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:
Or you could just add some content to the div and use inline-table
What is the problem here is that you somehow installed into virtualenv using sudo
. Probably by accident. This means root
user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.
You can fix the issue by changing UNIX file permissions pack to your user. Try:
$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip
then pip
should be able to write those files again.
Here's a method and some reasoning behind using it this way. It isn't as pretty to edit the stored proc but there are pros and cons...
UPDATE: You can also wrap this entire call in a TRANSACTION. Including many stored procedures in a single transaction which can all commit or all rollback. Another advantage of wrapping in a transaction is the stored procedure always exists for other SQL connections as long as they do not use the READ UNCOMMITTED transaction isolation level!
1) To avoid alters just as a process decision. Our processes are to always IF EXISTS DROP THEN CREATE. If you do the same pattern of assuming the new PROC is the desired proc, catering for alters is a bit harder because you would have an IF EXISTS ALTER ELSE CREATE.
2) You have to put CREATE/ALTER as the first call in a batch so you can't wrap a sequence of procedure updates in a transaction outside dynamic SQL. Basically if you want to run a whole stack of procedure updates or roll them all back without restoring a DB backup, this is a way to do everything in a single batch.
IF NOT EXISTS (select ss.name as SchemaName, sp.name as StoredProc
from sys.procedures sp
join sys.schemas ss on sp.schema_id = ss.schema_id
where ss.name = 'dbo' and sp.name = 'MyStoredProc')
BEGIN
DECLARE @sql NVARCHAR(MAX)
-- Not so aesthetically pleasing part. The actual proc definition is stored
-- in our variable and then executed.
SELECT @sql = 'CREATE PROCEDURE [dbo].[MyStoredProc]
(
@MyParam int
)
AS
SELECT @MyParam'
EXEC sp_executesql @sql
END
Some more answers from the interwebs: "fix" the sensor (glue screen back on more, or clean it with alcohol, or blow it off with air sent through the headphone jack, tap on it, clean the screen, etc.).
Adjust (after some finding) setting in the "phone" app to disable proximity sensor use. No such setting in mine, that I could find. Proximity Screen Off Lite
also didn't work, nor macrodroid
.
Another option: root your phone and remove some files:
From root explorer or similar program delete these folders and file
/data/system/sensors
/data/misc/sensors
/persist/sensors/sns.reg
Or if you're truly desperate I suppose a totally different dialer system like TextNow or google hangouts dialer :|
In telegram desktop, use this hotkey:
ctrl+K
In android:
Create Link
from its optionsError in file(file, "rt") :
I just faced the same error and resolved by removing spacing in address using paste0 instead of paste
filepath=paste0(directory,"/",filename[1],sep="")
Depending on your editor, this should be a fairly easy macro to write.
Another macro to reverse these steps, and you are done.
Edit: this simplistic approach does not handle nested comment tags, but should make the commenting/uncommenting easier in the general case.
Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.
I forgot to add the "Password=xxx;" in the connection string in my case.
A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:
#include <assert.h>
int main() {
int a[] = {1, 2, 3, 4, 5};
int* pArr = a;
int* pFirstElem = &(a[0]);
assert(a == pArr);
assert(a == pFirstElem);
return 0;
}
This also means that passing an array to a function should be done via pointer (and not via int in[5]
), and possibly along with the length of the array:
int* test(int* in, int len) {
int* out = in;
return out;
}
That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:
#include <iostream>
using namespace std;
int main() {
int* pArr = 0;
{
int a[] = {1, 2, 3, 4, 5};
pArr = a; // or test(a) if you wish
}
// a[] went out of scope here, but pArr holds a pointer to it
// all bets are off, this can output "1", output 1st chapter
// of "Romeo and Juliet", crash the program or destroy the
// universe
cout << pArr[0] << endl; // WRONG!
return 0;
}
So if you don't feel competent enough, just use std::vector
.
[answer to the updated question]
The correct way to write your test
function is either this:
void test(int* a, int* b, int* c, int len) {
for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
}
...
int main() {
int a[5] = {...}, b[5] = {...}, c[5] = {};
test(a, b, c, 5);
// c now holds the result
}
Or this (using std::vector
):
#include <vector>
vector<int> test(const vector<int>& a, const vector<int>& b) {
vector<int> result(a.size());
for (int i = 0; i < a.size(); ++i) {
result[i] = a[i] + b[i];
}
return result; // copy will be elided
}
<style type="text/css">
#userprofile{
display: inline-block;
padding: 15px 25px;
font-size: 24px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #FFF;
background-color: #4CAF50; // #C32836
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
width: 200px;
margin-bottom: 15px;
}
#userprofile:hover {
background-color: #3E8E41
}
#userprofile:active {
background-color: #3E8E41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#array {
border-radius: 15px 50px;
background: #4A21AD;
padding: 20px;
width: 200px;
height: 900px;
overflow-y: auto;
}
</style>
if (data[i].socketid != "") {
$("#array").append("<button type='button' id='userprofile' class='green_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username + "</button></br>");
}
else {
console.log('null socketid >>', $("#userprofile").css('background-color'));
//$("#userprofile").css('background-color', '#C32836 ! important');
$("#array").append("<button type='button' id='userprofile' class='red_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username+"</button></br>");
$(".red_button").css('background-color','#C32836');
}
Assuming the rectangle is represented by three points A,B,C, with AB and BC perpendicular, you only need to check the projections of the query point M on AB and BC:
0 <= dot(AB,AM) <= dot(AB,AB) &&
0 <= dot(BC,BM) <= dot(BC,BC)
AB
is vector AB, with coordinates (Bx-Ax,By-Ay), and dot(U,V)
is the dot product of vectors U and V: Ux*Vx+Uy*Vy
.
Update. Let's take an example to illustrate this: A(5,0) B(0,2) C(1,5) and D(6,3). From the point coordinates, we get AB=(-5,2), BC=(1,3), dot(AB,AB)=29, dot(BC,BC)=10.
For query point M(4,2), we have AM=(-1,2), BM=(4,0), dot(AB,AM)=9, dot(BC,BM)=4. M is inside the rectangle.
For query point P(6,1), we have AP=(1,1), BP=(6,-1), dot(AB,AP)=-3, dot(BC,BP)=3. P is not inside the rectangle, because its projection on side AB is not inside segment AB.
$datediff = floor(strtotime($date1)/(60*60*24)) - floor(strtotime($date2)/(60*60*24));
and, if needed:
$datediff=abs($datediff);
You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:
bArray = addByteToArray(bArray, newByte);
code:
public byte[] addByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
You need to add a reference to the .NET assembly System.Data.Linq
4 possible ways, use one you need.
val ll = findViewById<LinearLayout>(R.id.your_layout_id)
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
<LinearLayout
android:background="@{@color/white}"
OR more useful statement-
<LinearLayout
android:background="@{model.colorResId}"
<LinearLayout
android:background="#FFFFFF"
<LinearLayout
android:background="@color/white"
LinearLayout ll = (LinearLayout) findViewById(R.id.your_layout_id);
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white));