WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
A couple of things might affect the results you're seeing:
clock_t
as a floating-point type, I don't think it is.1^4
) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.
If you have it, try adding a call to sleep()
between the start/stop snapshots. Note that sleep()
is POSIX though, not standard C.
For kotlin
fun unixToDate(timeStamp: Long) : String? {
val time = java.util.Date(timeStamp as Long * 1000)
val sdf = SimpleDateFormat("yyyy-MM-dd")
return sdf.format(time)
}
You can use this: document.getElementById('h1_id').innerHTML = 'the new text';
For those who have the following error:
Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
You can simply run this command to see which folder can load files from:
SHOW VARIABLES LIKE "secure_file_priv";
After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE
instead of LOAD DATA INFILE
.
What you really need is a full absolute classPath for the file. So instead of guessing it, try to find out the ROOT and then move the file to a better location base one <.war> file structures...
URL test1 = getClass().getResource("/");
URL test2 = getClass().getClassLoader().getResource("/");
URL test3 = getClass().getClassLoader().getResource("../");
logger.info(test1.getPath());
logger.info(test2.getPath());
logger.info(test3.getPath());
I've made a package for this as of 2020-12-03 available on CRAN called "this.path".
Install it using:
install.packages("this.path")
and then use it by:
this.path::this.path()
or
library(this.path)
this.path()
I still have my original answer below, though it is less functional than the version in the package. On a Unix-alike OS, strange characters (such as " ") in the 'Rscript' command-line argument 'file' are replaced (such as "~+~"). R does this so that it is easier to use that filename for other system commands, but this isn't what we want. Given that we want a path usable in R, any such strange character sequences must be replaced.
Original Answer:
My answer is an improvement upon Jerry T's answer. The issue I found is that he is guessing whether a source
call was made by checking if variable ofile
is found in the first frame on the stack. This will not work with nested source calls, nor source calls made from a non-global environment. Additionally, a source call must be looked for before checking the command-line arguments, that has also been fixed. Here is my solution:
this.path <- function (verbose = getOption("verbose"))
{
where <- function(x) if (verbose)
cat("Source: ", x, "\n", sep = "")
# loop through functions that lead here from most recent to earliest looking
# for an appropriate source call (a call to function base::source or base::sys.source)
# an appropriate source call is a source call in which
# argument 'file' has been evaluated (forced)
# this means, for example, the following is an inappropriate source call:
# source(this.path())
# the argument 'file' is stored as a promise
# containing the expression "this.path()"
# when the value of 'file' is requested, it assigns the value
# returned by evaluating "this.path()" to variable 'file'
# there are two functions on the calling stack at
# this point being 'source' and 'this.path'
# clearly, you don't want to request the 'file' argument from that source
# call because the value of 'file' is under evaluation right now!
# the trick is to ask if variable ('ofile' for base::source, 'exprs' for base::sys.source)
# exists in that function's evaluation environment. this is because that
# variable is created AFTER argument 'file' has been forced
# if that variable does exist, then argument 'file' has been forced and the
# source call is deemed appropriate. For base::source, the filename we want
# is the variable 'ofile' from that function's evaluation environment. For
# base::sys.source, the filename we want is the variable 'file' from that
# function's evaluation environment.
# if that variable does NOT exist, then argument 'file' hasn't been forced and
# the source call is deemed inappropriate. The 'for' loop moves to the next
# function up the calling stack (if available)
#
# unfortunately, there is no way to check the argument 'fileName' has been forced
# for 'debugSource' since all the work is done internally in C. Instead,
# we have to use a 'tryCatch' statement. When we ask for an object by name
# using 'get', R is capable of realizing if a variable is asking for its
# own definition (a recursive definition). The exact error is "promise already
# under evaluation" which indicates that the promise evaluation is requesting
# its own value. So we use the 'tryCatch' to get the argument 'fileName'
# from the evaluation environment of 'debugSource', and if it does not raise
# an error, then we are safe to return that value. If not, the condition
# returns false and the 'for' loop moves to the next function up the calling
# stack (if available)
if (.Platform$GUI == "RStudio")
dbs <- get("debugSource", mode = "function", "tools:rstudio",
inherits = FALSE)
for (n in seq.int(sys.nframe(), 1L)[-1L]) {
if (identical(sys.function(n), base::source) &&
exists("ofile", envir = sys.frame(n), inherits = FALSE)) {
path <- get("ofile", envir = sys.frame(n), inherits = FALSE)
if (!is.character(path))
path <- summary.connection(path)$description
where("call to function source")
return(normalizePath(path, mustWork = TRUE))
}
else if (identical(sys.function(n), base::sys.source) &&
exists("exprs", envir = sys.frame(n), inherits = FALSE)) {
path <- get("file", envir = sys.frame(n), inherits = FALSE)
where("call to function sys.source")
return(normalizePath(path, mustWork = TRUE))
}
else if (.Platform$GUI == "RStudio" && identical(sys.function(n), dbs) &&
tryCatch({
path <- get("fileName", envir = sys.frame(n), inherits = FALSE)
TRUE
}, error = function(c) {
FALSE
})) {
where("call to function debugSource in RStudio")
return(normalizePath(path, mustWork = TRUE))
}
}
# if the for loop is passed, no appropriate
# source call was found up the calling stack
# next, check if the user is running R from the command-line
# on a Windows OS, the GUI is "RTerm"
# on a Unix OS, the GUI is "X11"
if (.Platform$OS.type == "windows" && .Platform$GUI == "RTerm" || # running from Windows command-line
.Platform$OS.type == "unix" && .Platform$GUI == "X11") { # running from Unix command-line
# get all command-line arguments that start with "--file="
# check the number of command-line arguments starting with "--file="
# in case more or less than one were supplied
path <- grep("^--file=", commandArgs(), value = TRUE)
if (length(path) == 1L) {
path <- sub("^--file=", "", path)
where("Command-line argument 'file'")
return(normalizePath(path, mustWork = TRUE))
}
else if (length(path)) {
stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* R is being run from the command-line and formal argument \"--file=\" matched by multiple actual arguments\n")
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* R is being run from the command-line and argument \"--file=\" is missing\n")
}
else if (.Platform$GUI == "RStudio") { # running R from 'RStudio'
# function ".rs.api.getActiveDocumentContext" from the environment "tools:rstudio"
# returns a list of information about the document where your cursor is located
#
# function ".rs.api.getSourceEditorContext" from the environment "tools:rstudio"
# returns a list of information about the document open in the current tab
#
# element 'id' is a character string, an identification for the document
# element 'path' is a character string, the path of the document
adc <- get(".rs.api.getActiveDocumentContext",
mode = "function", "tools:rstudio", inherits = FALSE)()
if (adc$id != "#console") {
path <- adc$path
if (nzchar(path)) {
where("active document in RStudio")
return(normalizePath(path, mustWork = TRUE))
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* active document in RStudio does not exist\n")
}
sec <- get(".rs.api.getSourceEditorContext", mode = "function",
"tools:rstudio", inherits = FALSE)()
if (!is.null(sec)) {
path <- sec$path
if (nzchar(path)) {
where("source document in RStudio")
return(normalizePath(path, mustWork = TRUE))
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* source document in RStudio does not exist\n")
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* R is being run from RStudio with no documents open\n")
}
else if (.Platform$OS.type == "windows" && .Platform$GUI == "Rgui") { # running R from 'RGui' on Windows
# on a Windows OS only, the function "getWindowsHandles" from the base
# package "utils" returns a list of external pointers containing the windows
# handles. The thing of interest are the names of this list, these should
# be the names of the windows belonging to the current R process. Since
# RGui can have files besides R scripts open (such as images), a regular
# expression is used to subset only windows handles with names that exactly
# match the string "R Console" or end with " - R Editor". I highly suggest
# that you NEVER end a document's filename with " - R Editor". From there,
# similar checks are done as in the above section for 'RStudio'
wh <- names(utils::getWindowsHandles(pattern = "^R Console$| - R Editor$",
minimized = TRUE))
if (!length(wh))
stop("this error SHOULD be unreachable, as far as I know it's impossible to have an R\n",
" process running without the R Console open. If you reached this error, please\n",
" send a bug report to the package maintainer")
path <- wh[1L]
if (path != "R Console") {
path <- sub(" - R Editor$", "", path)
if (path != "Untitled") {
where("active document in RGui")
return(normalizePath(path, mustWork = TRUE))
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* active document in RGui does not exist\n")
}
path <- wh[2L]
if (!is.na(path)) {
path <- sub(" - R Editor$", "", path)
if (path != "Untitled") {
where("source document in RGui")
return(normalizePath(path, mustWork = TRUE))
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* source document in RGui does not exist\n")
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* R is being run from RGui with no documents open\n")
}
else if (.Platform$OS.type == "unix" && .Platform$GUI == "AQUA") { # running R from 'RGui' on Unix
stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* R is being run from AQUA which requires a source call on the calling stack\n")
}
else stop("'this.path' used in an inappropriate fashion\n",
"* no appropriate source call was found up the calling stack\n",
"* R is being run in an unrecognized manner\n")
}
WARNING: git clean
deletes all your untracked files/directories and can't be undone.
Sometimes just clean -f
does not help. In case you have untracked DIRECTORIES, -d option also needed:
# WARNING: this can't be undone!
git reset --hard HEAD
git clean -f -d
git pull
WARNING: git clean
deletes all your untracked files/directories and can't be undone.
Consider using -n
(--dry-run
) flag first. This will show you what will be deleted without actually deleting anything:
git clean -n -f -d
Example output:
Would remove untracked-file-1.txt
Would remove untracked-file-2.txt
Would remove untracked/folder
...
I have resolved this problem using this code
df = pd.read_csv(gdp_path, engine='python')
This should work fine..
if(val!= null)
{
alert("value is "+val.length); //-- this returns 4
}
else
{
alert("value* is null");
}
When we compare C++ with Java, we see that C++ was not designed with implicit Garbage Collection in mind, while Java was.
Having things like arbitrary pointers in C-Style is not only bad for GC-implementations, but it would also destroy backward compatibility for a large amount of C++-legacy-code.
In addition to that, C++ is a language that is intended to run as standalone executable instead of having a complex run-time environment.
All in all: Yes it might be possible to add Garbage Collection to C++, but for the sake of continuity it is better not to do so.
I'd answer this question with another question: Do you use singeltons/ Are singeltons bad?
Because (almost all) singelton usage is a glorified global variable.
I like to write a small plugin to make things cleaner:
$.fn.setClass = function(classes) {
this.attr('class', classes);
return this;
};
That way you can simply do
$('button').setClass('btn btn-primary');
For this you can use limit
select *
from scores
order by score desc
limit 10
If performance is important (when is it not ;-) look for an index on score.
Starting with version 8.4, you can also use the standard (SQL:2008) fetch first
select *
from scores
order by score desc
fetch first 10 rows only
As @Raphvanns pointed out, this will give you the first 10 rows
literally. To remove duplicate values, you have to select distinct
rows, e.g.
select distinct *
from scores
order by score desc
fetch first 10 rows only
The default (when created with the designer) is:
label.ForeColor = SystemColors.ControlText;
This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).
You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.
If you own a server or VPS upload the script and it will work fine.
Login to mysql as root and type following query
select User from mysql.user;
+------+
| User |
+------+
| amon |
| root |
| root |
+------+
For some reasons above mentioned approaches did now work for me, before I followed the advice to add .default
like this:
<div>
<img src={require('../../mySvgImage.svg').default} alt='mySvgImage' />
</div>
I know that the geoLocation API is better but for people whom can't use an SSL, you can still use some sort of services such as geopluginService.
as specified in the documentation you simply send a request with the ip to the service url http://www.geoplugin.net/php.gp?ip=xx.xx.xx.xx
the output is a serialized array so you must need to unserialize it before using it.
Remember this service is not very accurate as the geoLocation is, but it is still an easy and fast solution.
To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.
$('input[name=radioName]:checked', '#myForm').val()
OR by only
$('form input[type=radio]:checked').val();
You can assign a class
to your ASP.NET
Button and then apply the desired style to it.
<asp:Button class="mybtn" Text="Button" runat="server"></asp:Button>
CSS:
.mybtn
{
border:1px solid Red;
//some more styles
}
Use desc and multiply by -1 if necessary. Example for ascending int ordering with nulls last:
select *
from
(select null v union all select 1 v union all select 2 v) t
order by -t.v desc
create table Project (ProjectId int, Description varchar(50));
insert into Project values (1, 'Chase tail, change directions');
insert into Project values (2, 'ping-pong ball in clothes dryer');
create table ProjectResource (ProjectId int, ResourceId int, Name varchar(15));
insert into ProjectResource values (1, 1, 'Adam');
insert into ProjectResource values (1, 2, 'Kerry');
insert into ProjectResource values (1, 3, 'Tom');
insert into ProjectResource values (2, 4, 'David');
insert into ProjectResource values (2, 5, 'Jeff');
SELECT *,
(SELECT Name + ' ' AS [text()]
FROM ProjectResource pr
WHERE pr.ProjectId = p.ProjectId
FOR XML PATH (''))
AS ResourceList
FROM Project p
-- ProjectId Description ResourceList
-- 1 Chase tail, change directions Adam Kerry Tom
-- 2 ping-pong ball in clothes dryer David Jeff
I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer
and TimerTask
from the same package. See below:
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Hello World");
}
};
Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);
You can use cvResize
. Or better use c++ interface (eg cv::Mat
instead of IplImage
and cv::imread
instead of cvLoadImage
) and then use cv::resize
which handles memory allocation and deallocation itself.
As easy as
SELECT lpad(42::text, 4, '0')
References:
sqlfiddle: http://sqlfiddle.com/#!15/d41d8/3665
You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.
Example using state:
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
getInitialState() {_x000D_
return {email: ''}_x000D_
},_x000D_
handleChange(e) {_x000D_
this.setState({email: e.target.value})_x000D_
},_x000D_
render() {_x000D_
return <div>_x000D_
<input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
<button type="button" disabled={!this.state.email}>Button</button>_x000D_
</div>_x000D_
}_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
In webkit-based browsers(Safari and Chrome), -webkit-transform
is ignored on inline elements.. Set display: inline-block;
to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin
lest the text is rotated out of the visible area.
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
on your full page, you could have this
<?php
// check if the form was submitted
if ($_POST['submit_button']) {
// this means the submit button was clicked, and the form has refreshed the page
// to access the content in text area, you would do this
$a = $_POST['update'];
// now $a contains the data from the textarea, so you can do whatever with it
// this will echo the data on the page
echo $a;
}
else {
// form not submitted, so show the form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
<?php
} // end "else" loop
?>
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
# or even faster copy paste answer if you have sudo on the host
sudo su - postgres -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"
from selenium import webdriver
PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
It's really easy to create folders. Actually it's just creating keys.
You can see my below code i was creating a folder with utc_time as name.
Do remember ends the key with '/' like below, this indicates it's a key:
Key='folder1/' + utc_time + '/'
client = boto3.client('s3')
utc_timestamp = time.time()
def lambda_handler(event, context):
UTC_FORMAT = '%Y%m%d'
utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
utc_time = utc_time.strftime(UTC_FORMAT)
print 'start to create folder for => ' + utc_time
putResponse = client.put_object(Bucket='mybucketName',
Key='folder1/' + utc_time + '/')
print putResponse
Generalizing on martinedwards and others' ideas, you can glue a bunch of columns together (not just a pair) by adjusting padding of even and odd column children. Adding this definition of a class, .no-gutter
, and placing it on your .row
element
.row.no-gutter > [class*='col-']:nth-child(2n+1) {
padding-right: 0;
}
.row.no-gutter > [class*='col-']:nth-child(2n) {
padding-left: 0;
}
Or in SCSS:
.no-gutter {
> [class*='col-'] {
&:nth-child(2n+1) {
padding-right: 0;
}
&:nth-child(2n) {
padding-left: 0;
}
}
}
I think the view could have code to handle the event from the view model.
Depending on the event/scenario, it could also have an event trigger that subscribes to view model events, and one or more actions to invoke in response.
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
Less efficient, but simpler-looking:
m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
print "He loves",m0.group(1)
elif m1:
print "Er liebt",m1.group(1)
elif m2:
print "Il aime",m2.group(1)
The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.
The version with less repetition (and better efficiency) is this:
pats = [
("I love (\w+)", "He Loves {0}" ),
("Ich liebe (\w+)", "Er Liebe {0}" ),
("Je t'aime (\w+)", "Il aime {0}")
]
for p1, p3 in pats:
m= re.match( p1, statement )
if m:
print p3.format( m.group(1) )
break
A minor variation that some Perl folk prefer:
pats = {
"I love (\w+)" : "He Loves {0}",
"Ich liebe (\w+)" : "Er Liebe {0}",
"Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
m= re.match( p1, statement )
if m:
print pats[p1].format( m.group(1) )
break
This is hardly worth mentioning except it does come up sometimes from Perl programmers.
This might work for you:
cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx
Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:
rpm -qia '*release*'
Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).
It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).
But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.
A good example: here
And a good documentation from Mozilla: here
Just use the length
property of a JavaScript
array like so:
$scope.names.length
Also, I don't see a starting <script>
tag in your code.
If you want the length inside your view, do it like so:
{{ names.length }}
Using in place string concatenation by '+' is THE WORST method of concatenation in terms of stability and cross implementation as it does not support all values. PEP8 standard discourages this and encourages the use of format(), join() and append() for long term use.
As quoted from the linked "Programming Recommendations" section:
For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
Does it have to be an actual service? Can you just use the built in scheduled tasks in the windows control panel.
Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.
So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:
DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
EXECUTE dbo.myCustomProcedure @myId, @myName;
FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;
Note that @@FETCH_STATUS
is a standard variable which gets updated for you. The rest of the object names here are custom.
The jQuery DataTables plug-in is one excellent way to achieve excel-like fixed column(s) and headers.
Note the examples section of the site and the "extras".
http://datatables.net/examples/
http://datatables.net/extras/
The "Extras" section has tools for fixed columns and fixed headers.
Fixed Columns
http://datatables.net/extras/fixedcolumns/
(I believe the example on this page is the one most appropriate for your question.)
Fixed Header
http://datatables.net/extras/fixedheader/
(Includes an example with a full page spreadsheet style layout: http://datatables.net/release-datatables/extras/FixedHeader/top_bottom_left_right.html)
In case that you need to add the http redirect in many sites, you could use it as a c# console program:
class Program
{
static int Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
return 1;
}
if (args.Length == 3)
{
if (args[0].ToLower() == "-insert-redirect")
{
var path = args[1];
var value = args[2];
if (InsertRedirect(path, value))
Console.WriteLine("Redirect added.");
return 0;
}
}
Console.WriteLine("Wrong parameters.");
return 1;
}
static bool InsertRedirect(string path, string value)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
// This should find the appSettings node (should be only one):
XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");
var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
if (existNode != null)
return false;
// Create new <add> node
XmlNode nodeNewKey = doc.CreateElement("httpRedirect");
XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
XmlAttribute attributeDestination = doc.CreateAttribute("destination");
//XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");
// Assign values to both - the key and the value attributes:
attributeEnable.Value = "true";
attributeDestination.Value = value;
//attributeResponseStatus.Value = "Permanent";
// Add both attributes to the newly created node:
nodeNewKey.Attributes.Append(attributeEnable);
nodeNewKey.Attributes.Append(attributeDestination);
//nodeNewKey.Attributes.Append(attributeResponseStatus);
// Add the node under the
nodeAppSettings.AppendChild(nodeNewKey);
doc.Save(path);
return true;
}
catch (Exception e)
{
Console.WriteLine($"Exception adding redirect: {e.Message}");
return false;
}
}
}
If git config --global user.email "[email protected]"
git config --global user.name "github_username"
Dont work like in my case, you can use:
git config --replace-all user.email "[email protected]"
git config --replace-all user.name "github_username"
When I need to make the DialogFragment a bit wider I'm setting minWidth:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="320dp"
... />
Add this link:
/usr/local/lib/*.so.*
The total is:
g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*
You can create a protocol, conforming to the Swift LocalizedError
protocol, with these values:
protocol OurErrorProtocol: LocalizedError {
var title: String? { get }
var code: Int { get }
}
This then enables us to create concrete errors like so:
struct CustomError: OurErrorProtocol {
var title: String?
var code: Int
var errorDescription: String? { return _description }
var failureReason: String? { return _description }
private var _description: String
init(title: String?, description: String, code: Int) {
self.title = title ?? "Error"
self._description = description
self.code = code
}
}
I was able to resolve this using the designer.
I did not have to change my view to use the ISNULL, NULLIF, or COALESCE workarounds. If you update your model from the database, the warnings will re-appear, but will go away if you close and re-open VS. The changes you made in the designer will be preserved and not affected by the refresh.
You shouldn't. If you want to do such a thing either you need to force user to use a single instance of your application by writing URLs on the fly use a sessionID alike (not sessionid it won't work) id and pass it in every URL.
I don't know why you need it but unless you need make a totally unusable application don't do it.
You failed to specify the exact columns (data) to test for normality. Use this instead
shapiro.test(heisenberg$HWWIchg)
On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.
Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:
C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl
. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False
That should allow your app to start correctly.
If you are using cpp11 (enable with the -std=c++0x
flag if needed), then you can simply initialize the vector like this:
// static std::vector<std::string> v;
v = {"haha", "hehe"};
To use this function/method,you need an instance of the class Date .
This method is always used in conjunction with a Date object.
See the code below :
var d = new Date();
d.getTime();
Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).
Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.
Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.
Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.
Hope this helps...
It looks like you forgot the prefix on the color attribute. Try
<stroke android:width="2dp" android:color="#ff00ffff"/>
Let me share an example which I developed with BS4, thymeleaf and Spring boot.
I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").
First, the thymeleaf snippet:
<div class="form-group">
<label th:for="topicId" th:text="#{label.topic}">Topic</label>
<select class="custom-select"
th:id="topicId" th:name="topicId"
th:field="*{topicId}"
th:errorclass="is-invalid" required>
<option value="" selected
th:text="#{option.select}">Select
</option>
<optgroup th:each="topicGroup : ${topicGroups}"
th:label="${topicGroup}">
<option th:each="topicItem : ${topics}"
th:if="${topicGroup == topicItem.grp} "
th:value="${{topicItem.baseIdentity.id}}"
th:text="${topicItem.name}"
th:selected="${{topicItem.baseIdentity.id==topicId}}">
</option>
</optgroup>
<option th:each="topicIter : ${topics}"
th:if="${topicIter.grp == ''} "
th:value="${{topicIter.baseIdentity.id}}"
th:text="${topicIter.name}"
th:selected="${{topicIter.baseIdentity?.id==topicId}}">
</option>
</select>
<small id="topicHelp" class="form-text text-muted"
th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->
<div class="form-group">
<label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
<select class="custom-select"
id="subtopicsId" name="subtopicsId"
th:field="*{subtopicsId}"
th:errorclass="is-invalid" multiple="multiple">
<option value="" disabled
th:text="#{option.multiple.optional}">Select
</option>
<option th:each="subtopicsIter : ${subtopicsList}"
th:value="${{subtopicsIter.baseIdentity.id}}"
th:text="${subtopicsIter.name}">
</option>
</select>
<small id="subtopicsHelp" class="form-text text-muted"
th:unless="${#fields.hasErrors('subtopicsId')}"
th:text="#{label.subtopics.tt}">select</small>
<small id="subtopicsIdError" class="invalid-feedback"
th:if="${#fields.hasErrors('subtopicsId')}"
th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->
I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.
Now, here's the jQuery that handles changes:
$('#topicId').change(function () {
selectedOption = $(this).val();
if (selectedOption === "") {
$('#subtopicsId').prop('disabled', 'disabled').val('');
$("#subtopicsId option").slice(1).remove(); // keep first
} else {
$('#subtopicsId').prop('disabled', false)
var orig = $(location).attr('origin');
var url = orig + "/getsubtopics/" + selectedOption;
$.ajax({
url: url,
success: function (response) {
var len = response.length;
$("#subtopicsId option[value!='']").remove(); // keep first
for (var i = 0; i < len; i++) {
var id = response[i]['baseIdentity']['id'];
var name = response[i]['name'];
$("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
}).change(); // and call it once defined
The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.
BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
you can use this two simple line code :
display: block;
margin:auto;
_x000D_
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Your applets will run.
If they are still not running then you have to add that website name in exception site list of Security tab of Java in Control panel.
Check, you might have written this statement wrong.
public static void main(String Args[])
I have also just started java and was facing the same error and it was occuring as i didn't put []
after args.
so check ur statment.
In Oracle 12c, You may use OFFSET..FETCH..ROWS
option with ORDER BY
For example, to get the 3rd record from top:
SELECT *
FROM sometable
ORDER BY column_name
OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY;
The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.
http://msdn.microsoft.com/en-us/library/ms378526.aspx
sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.
I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).
Update: this was fixed in Firefox v35. See the full gist for details.
== how to hide the select arrow in Firefox ==
Just figured out how to do it. The trick is to use a mix of -prefix-appearance
, text-indent
and text-overflow
. It is pure CSS and requires no extra markup.
select {
-moz-appearance: none;
text-indent: 0.01px;
text-overflow: '';
}
Long story short, by pushing it a tiny bit to the right, the overflow gets rid of the arrow. Pretty neat, huh?
More details on this gist I just wrote. Tested on Ubuntu, Mac and Windows, all with recent Firefox versions.
I like @fubo's answer the best but I think this is much more elegant.
This method is more compatible because it doesn't manually store the length up front.
Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.
public static class ZipExtensions
{
public static string CompressToBase64(this string data)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
}
public static string DecompressFromBase64(this string data)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
}
public static byte[] Compress(this byte[] data)
{
using (var sourceStream = new MemoryStream(data))
using (var destinationStream = new MemoryStream())
{
sourceStream.CompressTo(destinationStream);
return destinationStream.ToArray();
}
}
public static byte[] Decompress(this byte[] data)
{
using (var sourceStream = new MemoryStream(data))
using (var destinationStream = new MemoryStream())
{
sourceStream.DecompressTo(destinationStream);
return destinationStream.ToArray();
}
}
public static void CompressTo(this Stream stream, Stream outputStream)
{
using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
{
stream.CopyTo(gZipStream);
gZipStream.Flush();
}
}
public static void DecompressTo(this Stream stream, Stream outputStream)
{
using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
{
gZipStream.CopyTo(outputStream);
}
}
}
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>
Add Defer to the end of your Script tag, it worked for me (;
Everything needs to be loaded in the correct order (:
My original question for this was how to both have an element of a fixed aspect, but to fit that within a specified container exactly, which makes it a little fiddly. If you simply want an individual element to maintain its aspect ratio it is a lot easier.
The best method I've come across is by giving an element zero height and then using percentage padding-bottom to give it height. Percentage padding is always proportional to the width of an element, and not its height, even if its top or bottom padding.
So utilising that you can give an element a percentage width to sit within a container, and then padding to specify the aspect ratio, or in other terms, the relationship between its width and height.
.object {
width: 80%; /* whatever width here, can be fixed no of pixels etc. */
height: 0px;
padding-bottom: 56.25%;
}
.object .content {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
padding: 40px;
}
So in the above example the object takes 80% of the container width, and then its height is 56.25% of that value. If it's width was 160px then the bottom padding, and thus the height would be 90px - a 16:9 aspect.
The slight problem here, which may not be an issue for you, is that there is no natural space inside your new object. If you need to put some text in for example and that text needs to take it's own padding values you need to add a container inside and specify the properties in there.
Also vw and vh units aren't supported on some older browsers, so the accepted answer to my question might not be possible for you and you might have to use something more lo-fi.
#include "header.h"
int estimatedPopulation (int currentPopulation, float growthRate)
{
return currentPopulation + currentPopulation * growthRate / 100;
}
Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:
echo CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT
I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.
It looks that in awk, string can be concatenated by printing variable next to each other:
echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal
This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (HttpContext.Current == null)
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
I know it's not for everyone but: why not to do a graceful Apache restart?
For e.g. in case of Centos/RedHat Linux:
sudo service httpd graceful
Ubuntu:
sudo service apache2 graceful
Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.
On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE
, can be tampered with so always use server side validation.
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize
. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE
has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.
On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES
array to find out the upload size. (Docs on the contents of $_FILES
can be found below the MAX_FILE_SIZE
docs)
upload.php
<?php
if(isset($_FILES['file'])) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}
Note.
where(:user_id => current_user.id, :notetype => p[:note_type]).
where("date > ?", p[:date]).
order('date ASC, created_at ASC')
or you can also convert everything into the SQL notation
Note.
where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
order('date ASC, created_at ASC')
If you don't have it at C:\Users\%USERNAME%\AppData\Local\Android (this is where most people have it) than it is possible you don't have it installed. Go to Tools > Android > SDK Manager and then click on "Android SDK." On the top of the SDK Manager it will list the SDK Location. Click edit. If you don't have Android SDK installed, it will give you the option to install it in certain location. Install it, and Android Studio should work!
I know I'm late, but I can't resist the temptation: anybody liking Lombok should also have a look at Scala. Many good ideas that you find in Lombok are part of the Scala language.
On your question: it's definitely easier to get your developers trying Lombok than Scala. Give it a try and if they like it, try Scala.
Just as a disclaimer: I like Java, too!
Apply DataAnnotation like:
[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]
There is a way to achieve this which is quite simple, but I wouldn't suggest it is a good approach for an app you are going to let other people see. But if you had some developer need to show the console and windows forms at the same time, it can be done quite easily.
This method also supports showing only the Console window, but does not support showing only the Windows Form - i.e. the Console will always be shown. You can only interact (i.e. receive data - Console.ReadLine()
, Console.Read()
) with the console window if you do not show the windows forms; output to Console - Console.WriteLine()
- works in both modes.
This is provided as is; no guarantees this won't do something horrible later on, but it does work.
Start from a standard Console Application.
Mark the Main
method as [STAThread]
Add a reference in your project to System.Windows.Forms
Add a Windows Form to your project.
Add the standard Windows start code to your Main
method:
You will have an application that shows the Console and optionally windows forms.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
class Program {
[STAThread]
static void Main(string[] args) {
if (args.Length > 0 && args[0] == "console") {
Console.WriteLine("Hello world!");
Console.ReadLine();
}
else {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication9 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Click(object sender, EventArgs e) {
Console.WriteLine("Clicked");
}
}
}
I had a similar problem recently and found an interesting solution. Basically I needed to deserialize following nested JSON String into my POJO:
"{\"restaurant\":{\"id\":\"abc-012\",\"name\":\"good restaurant\",\"foodType\":\"American\",\"phoneNumber\":\"123-456-7890\",\"currency\":\"USD\",\"website\":\"website.com\",\"location\":{\"address\":{\"street\":\" Good Street\",\"city\":\"Good City\",\"state\":\"CA\",\"country\":\"USA\",\"postalCode\":\"12345\"},\"coordinates\":{\"latitude\":\"00.7904692\",\"longitude\":\"-000.4047208\"}},\"restaurantUser\":{\"firstName\":\"test\",\"lastName\":\"test\",\"email\":\"[email protected]\",\"title\":\"server\",\"phone\":\"0000000000\"}}}"
I ended up using regex to remove the open quotes from beginning and the end of JSON and then used apache.commons unescapeJava() method to unescape it. Basically passed the unclean JSON into following method to get back a cleansed one:
private String removeQuotesAndUnescape(String uncleanJson) {
String noQuotes = uncleanJson.replaceAll("^\"|\"$", "");
return StringEscapeUtils.unescapeJava(noQuotes);
}
then used Google GSON to parse it into my own Object:
MyObject myObject = new.Gson().fromJson(this.removeQuotesAndUnescape(uncleanJson));
#include <stdio.h>
#include <string.h>
void repeat_char(unsigned int cnt, char ch) {
char buffer[cnt + 1];
/*assuming you want to repeat the c character 30 times*/
memset(buffer,ch,cnd); buffer[cnt]='\0';
printf("%s",buffer)
}
The documentation for the parameter spark.files.overwrite
says this: "Whether to overwrite files added through SparkContext.addFile()
when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.
You could do this before saving the file:
val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }
Aas explained here: http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html
this is the correct form:
comboBox1.Text = comboBox1.Items[0].ToString();
U r welcome
Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.
For example, you can validate the content negotiation like this.
This Accept
header prefers plain text so returns in that format:-
$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain
Whereas this one prefers JSON and so returns in that format:-
$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
"Accept": "application/json,text/*;q=0.99"
}
I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like
I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context
kubectl config get-contexts
In my case I had something like cURL Error (7): ... Operation Timed Out
. I'm using the network connection of the company I'm working for. I needed to create some environment variables. The next worked for me:
In Linux terminal:
$ export https_proxy=yourProxy:80
$ export http_proxy=yourProxy:80
In windows I created (the same) environment variables in the windows way.
I hope it helps!
Regards!
Your rows
object holds an Item
attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString()
on the row.
You should access each column from the row separately, use a for
or a foreach
to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
No need to even pass the class:
public <T> List<T> magicalListGetter() {
return new ArrayList<T>();
}
In Eclipse: right-click
on your project -> Export
-> JAR file
At last page with options (when there will be no Next
button active) you will see settings for Main class:
. You need to set here class with main
method which should be executed by default (like when JAR file will be double-clicked).
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
just type "git push" if this doesn't give you a positive replay, then check if you are connected with your repository correctly.
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1 Phone Number: output of string2
For Linux :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
For Mac :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip
For Windows:https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip
unzip it
for linux and mac users move file to /usr/local/bin
and execute ngrok http 80
command in the terminal
I don't have any idea about windows
OpenCV has region of interest functions which you may find useful. If you are using the cv::Mat
then you could use something like the following.
// You mention that you start with a CVMat* imagesource
CVMat * imagesource;
// Transform it into the C++ cv::Mat format
cv::Mat image(imagesource);
// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedImage = image(myROI);
For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}"
CanExecute="CloseWindow_CanExec"
Executed="CloseWindow_Exec" />
</Window.CommandBindings>
<!-- Binding Close Command to the button control -->
<Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>
In the Code Behind you can implement the handlers like this:
private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
The solution for multi-indexes is inside jezrael's cyclopedic answer, but it took me a while to find it so I am posting a new answer:
df.index.names
gives the names of a multi-index (as a Frozenlist).
You can do this simply like this
$('#image_id').click(function() {
$("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1');
});
where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.
This might be an alternative solution. Paste the following code into the new module:
Public Function ModDate()
ModDate =
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm")
End Function
Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.
Paste the following code into the cell where you want to display the last modification time:
=ModDate()
I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel
On Ubuntu you need to set the http_proxy for the Docker daemon, not the client process. This is done in /etc/default/docker
(see here).
Use the rename() function.
rename("user/image1.jpg", "user/del/image1.jpg");
ViewWillAppear is an override method of UIViewController class so adding a subView will not call viewWillAppear, but when you present, push , pop, show , setFront Or popToRootViewController from a viewController then viewWillAppear for presented viewController will get called.
You can use -O-
(uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null
/dev/stderr
/dev/stdout
)
wget -O- http://yourdomain.com
Or:
wget -O- http://yourdomain.com > /dev/null
Or: (same result as last command)
wget -O/dev/null http://yourdomain.com
@mani's Original answer is all you want, but if you'd also like to read it in official way, here's
https://router.vuejs.org/guide/essentials/history-mode.html#caveat
What about that?
HTML
<div class="chart" id="graph" data-percent="88"></div>
Javascript
var el = document.getElementById('graph'); // get canvas
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 220,
lineWidth: el.getAttribute('data-line') || 15,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
and CSS
div {
position:relative;
margin:80px;
width:220px; height:220px;
}
canvas {
display: block;
position:absolute;
top:0;
left:0;
}
span {
color:#555;
display:block;
line-height:220px;
text-align:center;
width:220px;
font-family:sans-serif;
font-size:40px;
font-weight:100;
margin-left:5px;
}
http://jsfiddle.net/Aapn8/3410/
Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/
Google says SHA256 is available to PHP.
You should definitely use a salt. I'd recommend using random bytes (and not restrict yourself to characters and numbers). As usually, the longer you choose, the safer, slower it gets. 64 bytes ought to be fine, i guess.
\n
is Unix, \r
is Mac, \r\n
is Windows.
Sometimes it's giving trouble especially when running code cross platform. You can bypass this by using Environment.NewLine
.
Please refer to What is the difference between \r, \n and \r\n ?! for more information. Happy reading
If you forgot to add the repository HTTPS link then put it with git push <repo HTTPS>
To update one column here are some syntax options:
Option 1
var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
}
db.SubmitChanges();
}
Update
As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status
at ones. We want to update name
and status
where the friendid
is matching. Here are some syntax options for that:
Option 1
var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
some.name=name;
}
db.SubmitChanges();
}
Update 2
In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:
db.SubmitChanges();
But for Entity Framework to commit the changes it is:
db.SaveChanges()
I have used the cmdlet and navigate to the path you want to switch your npm files to. Type in npm root -g to see what the current path your npm is installed to. Next use npm config set prefix and your npm path will be changed to whatever directory you are currently on.
Use this command for Angular 6 to build
ng build --prod --configuration=dev
Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic
.
Now, if you were to use an ExpandoObject and reference it through a dynamic
variable, you could add or remove fields on the fly.
edit
Sure you can: just cast it to IDictionary<string, object>
. Then you can use the indexer.
You use the same casting technique to iterate over the fields:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<string, object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
The above code and more can be found by clicking on that link.
you can download the pdf file using fetch, and print it with print.js
fetch("url")
.then(function (response) {
response.blob().then(function (blob) {
var reader = new FileReader();
reader.onload = function () {
//Remove the data:application/pdf;base64,
printJS({
printable: reader.result.substring(28),
type: 'pdf',
base64: true
});
};
reader.readAsDataURL(blob);
})
});
None of these answers worked for me. This answer doesn't solve OP's issue but since this post is the only one that shows up on googling this issue, I'm sharing my answer here.
I came across this issue while writing unit tests for Android. The issue was that the activity that I was testing extended AppCompatActivity
instead of Activity
. To fix this, I was able to just replace AppCompatActivity
with Activity
since I didn't really need it. This might not be a viable solution for everyone, but hopefully knowing the root cause will help someone.
If you use Windows, there some shortcuts, while devtools are opened:
Pressing Ctrl+Shift+D will dock all devtools to left, right, bottom in turn.
Press Ctrl+Shift+F if your JS console disappeared, and you want it docked back to bottom within dev tools.
A dozen pages is not a big deal when using OFFSET
. But when you have hundreds of pages, you will find that OFFSET
is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.
The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument
You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:
<context:component-scan base-package="x.y.z">
<context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>
It is possible but, before git 2.9.3 (august 2016), a git push
would print the full url used when pushing back to the cloned repo.
That would include your username and password!
But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 71076e1, 08 Aug 2016)
push
: anonymize URL in status outputCommit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.
Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.
After my previous answer disaster, I'm going to try something else.
List<Model> usrList =
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));
Assuming that the question is asking what's the minimum bits required for you to store
My approach to this question would be:
This problem can be solved this way by dividing 999 by 2 recursively. However, it's simpler to use the power of maths to help us. Essentially, we're solving n for the equation below:
2^n = 999
nlog2 = log999
n ~ 10
You'll need 10 bits to store 3 digit number.
Use similar approach to solve the other subquestions!
Hope this helps!
There are a several ways of declaring variables in SQL*Plus scripts.
The first is to use VAR, to declare a bind variable. The mechanism for assigning values to a VAR is with an EXEC call:
SQL> var name varchar2(20)
SQL> exec :name := 'SALES'
PL/SQL procedure successfully completed.
SQL> select * from dept
2 where dname = :name
3 /
DEPTNO DNAME LOC
---------- -------------- -------------
30 SALES CHICAGO
SQL>
A VAR is particularly useful when we want to call a stored procedure which has OUT parameters or a function.
Alternatively we can use substitution variables. These are good for interactive mode:
SQL> accept p_dno prompt "Please enter Department number: " default 10
Please enter Department number: 20
SQL> select ename, sal
2 from emp
3 where deptno = &p_dno
4 /
old 3: where deptno = &p_dno
new 3: where deptno = 20
ENAME SAL
---------- ----------
CLARKE 800
ROBERTSON 2975
RIGBY 3000
KULASH 1100
GASPAROTTO 3000
SQL>
When we're writing a script which calls other scripts it can be useful to DEFine the variables upfront. This snippet runs without prompting me to enter a value:
SQL> def p_dno = 40
SQL> select ename, sal
2 from emp
3 where deptno = &p_dno
4 /
old 3: where deptno = &p_dno
new 3: where deptno = 40
no rows selected
SQL>
Finally there's the anonymous PL/SQL block. As you see, we can still assign values to declared variables interactively:
SQL> set serveroutput on size unlimited
SQL> declare
2 n pls_integer;
3 l_sal number := 3500;
4 l_dno number := &dno;
5 begin
6 select count(*)
7 into n
8 from emp
9 where sal > l_sal
10 and deptno = l_dno;
11 dbms_output.put_line('top earners = '||to_char(n));
12 end;
13 /
Enter value for dno: 10
old 4: l_dno number := &dno;
new 4: l_dno number := 10;
top earners = 1
PL/SQL procedure successfully completed.
SQL>
Armin's answer is so useful, thank you. #2 is what's most important to know when trying to set up unload events that work in most browsers: you cannot alert() or confirm(), but returning a string will generate a confirm modal.
But I found that even with just returning a string, I had some cross-browser issues specific to Mootools (using version 1.4.5 in this instance). This Mootools-specific implementation worked great in Firefox, but did not result in a confirm popup in Chrome or Safari:
window.addEvent("beforeunload", function() {
return "Are you sure you want to leave this page?";
});
So in order to get my onbeforeonload event to work across browsers, I had to use the JavaScript native call:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
}
Not sure why this is the case, or if it's been fixed in later versions of Mootools.
UPDATE: using Pandas 0.22.0
Newer Pandas versions have new methods 'DataFrame.isna()' and 'DataFrame.notna()'
In [71]: df
Out[71]:
a b c
0 NaN 7.0 0
1 0.0 NaN 4
2 2.0 NaN 4
3 1.0 7.0 0
4 1.0 3.0 9
5 7.0 4.0 9
6 2.0 6.0 9
7 9.0 6.0 4
8 3.0 0.0 9
9 9.0 0.0 1
In [72]: df.isna().any()
Out[72]:
a True
b True
c False
dtype: bool
as list of columns:
In [74]: df.columns[df.isna().any()].tolist()
Out[74]: ['a', 'b']
to select those columns (containing at least one NaN
value):
In [73]: df.loc[:, df.isna().any()]
Out[73]:
a b
0 NaN 7.0
1 0.0 NaN
2 2.0 NaN
3 1.0 7.0
4 1.0 3.0
5 7.0 4.0
6 2.0 6.0
7 9.0 6.0
8 3.0 0.0
9 9.0 0.0
OLD answer:
Try to use isnull():
In [97]: df
Out[97]:
a b c
0 NaN 7.0 0
1 0.0 NaN 4
2 2.0 NaN 4
3 1.0 7.0 0
4 1.0 3.0 9
5 7.0 4.0 9
6 2.0 6.0 9
7 9.0 6.0 4
8 3.0 0.0 9
9 9.0 0.0 1
In [98]: pd.isnull(df).sum() > 0
Out[98]:
a True
b True
c False
dtype: bool
or as @root proposed clearer version:
In [5]: df.isnull().any()
Out[5]:
a True
b True
c False
dtype: bool
In [7]: df.columns[df.isnull().any()].tolist()
Out[7]: ['a', 'b']
to select a subset - all columns containing at least one NaN
value:
In [31]: df.loc[:, df.isnull().any()]
Out[31]:
a b
0 NaN 7.0
1 0.0 NaN
2 2.0 NaN
3 1.0 7.0
4 1.0 3.0
5 7.0 4.0
6 2.0 6.0
7 9.0 6.0
8 3.0 0.0
9 9.0 0.0
I've created a clearable textbox in just CSS. It requires no javascript code to make it work
below is the demo link
Before you return your model from the controller, set your ReturnDate
property to DateTime.Now()
myModel.ReturnDate = DateTime.Now()
return View(myModel)
Your view is not the right place to set values on properties so the controller is the better place for this.
You could even have it so that the getter on ReturnDate
returns the current date/time.
private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
get{
return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
}
set{_returnDate = value;}
}
You can also use it in named_scope if You want to put there others conditions
for example include some other model:
named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }
"Best" is such a subjective term :-)
I would just use the method of checking each individual variable. If your class already has a lot of these, the increase in size is not going to be that much if you do something like:
public Boolean anyUnset() {
if ( id == null) return true;
if (name == null) return true;
return false;
}
Provided you keep everything in the same order, code changes (and automated checking with a script if you're paranoid) will be relatively painless.
Alternatively (assuming they're all strings), you could basically put these values into a map of some sort (eg, HashMap
) and just keep a list of the key names for that list. That way, you could iterate through the list of keys, checking that the values are set correctly.
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
android:background="#E1E1E1"
// background add in layout
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff">
</EditText>
CORS headers should be sent from the server. If you use PHP it will be like this:
header('Access-Control-Allow-Origin: your-host');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: your-methods like POST,GET');
header('Access-Control-Allow-Headers: content-type or other');
header('Content-Type: application/json');
You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):
Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
Write-Host $_.IP1
Write-Host $_.IP2
...
}
Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:
They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
See more here.
Here's the solution:
<?php
// here's the pattern:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*(\/>|>)/';
// a string to parse:
$string = 'Hello, try clicking <a href="#paragraph">here</a>
<br/>and check out.<hr />
<h2>title</h2>
<a name ="paragraph" rel= "I\'m an anchor"></a>
Fine, <span title=\'highlight the "punch"\'>thanks<span>.
<div class = "clear"></div>
<br>';
// let's get the occurrences:
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);
// print the result:
print_r($matches[0]);
?>
To test it deeply, I entered in the string auto-closing tags like:
I also entered tags with:
Should you find something which does not work in the proof of concept above, I am available in analyzing the code to improve my skills.
<EDIT> I forgot that the question from the user was to avoid the parsing of self-closing tags. In this case the pattern is simpler, turning into this:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>/';
The user @ridgerunner noticed that the pattern does not allow unquoted attributes or attributes with no value. In this case a fine tuning brings us the following pattern:
$pattern = '/<(\w+)(\s+(\w+)(\s*\=\s*(\'|"|)(.*?)\\5\s*)?)*\s*>/';
</EDIT>
If someone is interested in learning more about the pattern, I provide some line:
Small tip: to better analyze this code it is necessary looking at the source code generated since I did not provide any HTML special characters escaping.
Get image size with jQuery
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
Get image size with JavaScript
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
Get image size with JavaScript (modern browsers, IE9+ )
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Use the above simply as: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
Method 1:
if (window.jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
Method 2:
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
} else {
// jQuery is loaded
}
If jquery.js file is not loaded, we can force load it like so:
if (!window.jQuery) {
var jq = document.createElement('script'); jq.type = 'text/javascript';
// Path to jquery.js file, eg. Google hosted version
jq.src = '/path-to-your/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
Its very simple
new AlertDialog.Builder(this).setView(input).setPositiveButton("ENTER",
new DialogInterface.OnClickListener()
{ public void onClick(DialogInterface di,int id)
{
output.setText(input.getText().toString());
}
}
)
.create().show();
In case you wish to read the full program see here: Program to take input from user using dialog and output to screen
pip install -U $(pip list --outdated | awk 'NR>2 {print $1}')
Here is the documentation of <select>
. You are using 2 attributes:
multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.
size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.
As described in the docs. <select size="1" multiple>
will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple
attribute.
Well, to give some perspective, let me compare node.js with apache.
Apache is a multi-threaded HTTP server, for each and every request that the server receives, it creates a separate thread which handles that request.
Node.js on the other hand is event driven, handling all requests asynchronously from single thread.
When A and B are received on apache, two threads are created which handle requests. Each handling the query separately, each waiting for the query results before serving the page. The page is only served until the query is finished. The query fetch is blocking because the server cannot execute the rest of thread until it receives the result.
In node, c.query is handled asynchronously, which means while c.query fetches the results for A, it jumps to handle c.query for B, and when the results arrive for A arrive it sends back the results to callback which sends the response. Node.js knows to execute callback when fetch finishes.
In my opinion, because it's a single thread model, there is no way to switch from one request to another.
Actually the node server does exactly that for you all the time. To make switches, (the asynchronous behavior) most functions that you would use will have callbacks.
The SQL query is taken from mysql library. It implements callback style as well as event emitter to queue SQL requests. It does not execute them asynchronously, that is done by the internal libuv threads that provide the abstraction of non-blocking I/O. The following steps happen for making a query :
The incoming requests to http server are handled in the similar fashion. The internal thread architecture is something like this:
The C++ threads are the libuv ones which do the asynchronous I/O (disk or network). The main event loop continues to execute after the dispatching the request to thread pool. It can accept more requests as it does not wait or sleep. SQL queries/HTTP requests/file system reads all happen this way.
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
If you get a Error 509 in Libre office you may replace ,
by ;
in the DATE() function
=(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970;1;1)
Spring framework is definitely good for web development and to be more specific for restful api services.
It is good for the above because of its dependency injection and integration with other modules like spring security, spring aop, mvc framework, microservices
With in any application, security is most probably a requirement.
If you aim to build a product that needs long maintenance, then you will need the utilize the Aop concept.
If your application has to much traffic thus increasing the load, you need to use the microservices concept.
Spring is giving all these features in one platform. Support with many modules.
Most importantly, spring is open source and an extensible framework,have a hook everywhere to integrate custom code in life cycle.
Spring Data is one project which provides integration with your project.
So spring can fit into almost every requirement.
using position:fixed
alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.
if($(window).scrollTop() > Height_of_Header){
//begin to scroll
$("#div").css("position","fixed");
$("#div").css("top",0);
}
else{
//lock it back into place
$("#div").css("position","relative");
}
1) Go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A for VS2013
2) Copy the folders Include
and Lib
(you should check where are your folders in folder windows such as v7.1
, v8
, v6
, etc.)
3) Paste them into C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
I solved my problems like:
error lnk1104: cannot open file 'kernel32.lib'.
error c1083: Cannot open Windows.h
Thanks.
In my experience, I've had to leverage the event's currentTarget:
$("#dingus").click( function (event) {
if ($(event.currentTarget).is(':checked')) {
//checkbox is checked
}
});
Good Question & Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:
SELECT col1, col2, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
That would be if the oldtable was scripted something as such:
CREATE TABLE [dbo].[oldtable]
(
[oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[col1] [nvarchar](50) NULL,
[col2] [numeric](18, 0) NULL,
)
In jQuery I mostly use:
$("#element").trigger("change");
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if
" statements to do it, either:
if (x >= 0.001 && x <= 0.009) {
// something
}
You could write yourself a "between()" function:
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Cannot comment anymore but voted it up and wanted to let folks know that "
works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src="(.*)".*"
using the escaped version instead of double-quotes.
It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:
import {Component, OnInit, NgZone} from 'angular2/core';
export class RecentDetectionComponent implements OnInit {
recentDetections: Array<RecentDetection>;
constructor(private zone:NgZone, // <== added
private recentDetectionService: RecentDetectionService) {
this.recentDetections = new Array<RecentDetection>();
}
getRecentDetections(): void {
this.recentDetectionService.getJsonFromApi()
.subscribe(recent => {
this.zone.run(() => { // <== added
this.recentDetections = recent;
console.log(this.recentDetections[0].macAddress)
});
});
}
ngOnInit() {
this.getRecentDetections();
let timer = Observable.timer(2000, 5000);
timer.subscribe(() => this.getRecentDetections());
}
}
For other ways to invoke change detection see Triggering change detection manually in Angular
Alternative ways to invoke change detection are
ChangeDetectorRef.detectChanges()
to immediately run change detection for the current component and its children
ChangeDetectorRef.markForCheck()
to include the current component the next time Angular runs change detection
ApplicationRef.tick()
to run change detection for the whole application
I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:
<code>
- tag to prevent the curly brackets from being interpreted{@code ...}
- tag to get the generics included in the output@Override
via "{@literal @}Override
" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket{@code
and {@literal
, to compensate inner spaces and keep the alignmentjavadoc code:
/** this methods adds a specific translator from one type to another type. `
* i.e.
* <pre>
* <code>new BeanTranslator.Builder()
* .translate(
* new{@code Translator<String, Integer>}(String.class, Integer.class){
* {@literal @}Override
* public Integer translate(String instance) {
* return Integer.valueOf(instance);
* }})
* .build();
* </code>
* </pre>
* @param translator
*/
gets printed as
new BeanTranslator.Builder()
.translate(
new Translator<String, Integer>(String.class, Integer.class){
@Override
public Integer translate(String instance) {
return Integer.valueOf(instance);
}})
.build();
this.WindowState = FormWindowState.Minimized;
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
This code is based on brilliant existing answer from @bukzor. I just added custom render for datetime.datetime
type into Oracle's TO_DATE()
.
Feel free to update code to suit your database:
import decimal
import datetime
def printquery(statement, bind=None):
"""
print a query, with values filled in
for debugging purposes *only*
for security, you should always separate queries from their values
please also note that this function is quite slow
"""
import sqlalchemy.orm
if isinstance(statement, sqlalchemy.orm.Query):
if bind is None:
bind = statement.session.get_bind(
statement._mapper_zero_or_none()
)
statement = statement.statement
elif bind is None:
bind = statement.bind
dialect = bind.dialect
compiler = statement._compiler(dialect)
class LiteralCompiler(compiler.__class__):
def visit_bindparam(
self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs
):
return super(LiteralCompiler, self).render_literal_bindparam(
bindparam, within_columns_clause=within_columns_clause,
literal_binds=literal_binds, **kwargs
)
def render_literal_value(self, value, type_):
"""Render the value of a bind parameter as a quoted literal.
This is used for statement sections that do not accept bind paramters
on the target driver/database.
This should be implemented by subclasses using the quoting services
of the DBAPI.
"""
if isinstance(value, basestring):
value = value.replace("'", "''")
return "'%s'" % value
elif value is None:
return "NULL"
elif isinstance(value, (float, int, long)):
return repr(value)
elif isinstance(value, decimal.Decimal):
return str(value)
elif isinstance(value, datetime.datetime):
return "TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')" % value.strftime("%Y-%m-%d %H:%M:%S")
else:
raise NotImplementedError(
"Don't know how to literal-quote value %r" % value)
compiler = LiteralCompiler(dialect, statement)
print compiler.process(statement)
In JSF 2.2 it's possible to use passthrough elements:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
...
<div jsf:id="id1" />
...
</html>
The requirement is to have at least one attribute in the element using jsf namespace.
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
You can simply do it by using:
Object.prototype.extend = function(object) {
// loop through object
for (var i in object) {
// check if the extended object has that property
if (object.hasOwnProperty(i)) {
// mow check if the child is also and object so we go through it recursively
if (typeof this[i] == "object" && this.hasOwnProperty(i) && this[i] != null) {
this[i].extend(object[i]);
} else {
this[i] = object[i];
}
}
}
return this;
};
update: I checked for
this[i] != null
sincenull
is an object
Then use it like:
var options = {
foo: 'bar',
baz: 'dar'
}
var defaults = {
foo: false,
baz: 'car',
nat: 0
}
defaults.extend(options);
This well result in:
// defaults will now be
{
foo: 'bar',
baz: 'dar',
nat: 0
}
RDP will not do that natively.
As other answers have said -- you'll need to do some scripting and make policy changes as a kludge to make it hard for RDP logins to run anything but the intended application.
However, as of 2008, Microsoft has released application virtualization technology via Terminal Services that will allow you to do this seamlessly.
Interestingly, a ComboBox with DropDownStyle=Simple has pretty much exactly the behaviour you are looking for, I think.
(If you reduce the height of the control to not show the list - and then by a couple of pixels more - there's no effective difference between the ComboBox and the TextBox.)
Wanted to add numexpr into the mix:
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)
Would only make sense for larger arrays with millions... or if you hitting a memory limits.
If you want to avoid having to use CTRL
+SHIFT
+B
and instead want this to occur any time you save a file, you can bind the command to the same short-cut as the save action:
[
{
"key": "ctrl+s",
"command": "workbench.action.tasks.build"
}
]
This goes in your keybindings.json - (head to this using File -> Preferences -> Keyboard Shortcuts).
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
If you open the directory which it is trying to delete then also you will face same error so first close the folder.
viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.
However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.
For Android Studio:
If you haven't built the APK at least once, you might not find the /Outputs/APK folder. Go to Build in Android Studio and one of the last three options is Build APK, select that. It will then create that folder and you will find your APK file there.
Create /etc/docker/daemon.json
file where you want to pull docker images and add the following content to that file
{
"insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}
Refer to my blog article for an in-depth explanation of creating a private docker registry: https://geekdosage.com/how-to-create-a-private-docker-registry-in-ubuntu-20-04/
# aptitude clean
# aptitude --download-only install <your_package_here>
# cp /var/cache/apt/archives/*.deb <your_directory_here>
Yes, orWhereIn
is a method that you can use.
I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode
to create a string and then explode it (this is a guess at your array structure):
$values = implode(',', array_map(function($value)
{
return trim($value, ',');
}, $filters));
$query->whereIn('products.value', explode(',' $values));
axios
by itself comes with two useful "methods" the interceptors
that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request
.
I made apackage that helps you out:
$ npm i axios-es6-class
Now you can use axios as class
export class UserApi extends Api {
constructor (config) {
super(config);
// this middleware is been called right before the http request is made.
this.interceptors.request.use(param => {
return {
...param,
defaults: {
headers: {
...param.headers,
"Authorization": `Bearer ${this.getToken()}`
},
}
}
});
this.login = this.login.bind(this);
this.getSome = this.getSome.bind(this);
}
login (credentials) {
return this.post("/end-point", {...credentials})
.then(response => this.setToken(response.data))
.catch(this.error);
}
getSome () {
return this.get("/end-point")
.then(this.success)
.catch(this.error);
}
}
I mean the implementation of the middleware
depends on you, or if you prefer to create your own axios-es6-class
https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a
it is the medium post where it came from
If you already have yarn 1.x
and you want to upgrade to yarn 2. You need to do something a bit different:
yarn set version berry
Where berry
is the code name for yarn version 2. See this migration guide here for more info.
**node_modules
This works for me
recursive approach to ignore all node_modules present in sub folders
I know it's very late to answer the question but with Auto-Property you can do something like that:
public static Singleton Instance { get; } = new Singleton();
Where Singleton
is you class and can be via, in this case the readonly property Instance
.
# mysqladmin -u root -p status
Output:
Enter password:
Uptime: 4 Threads: 1 Questions: 62 Slow queries: 0 Opens: 51 Flush tables: 1 Open tables: 45 Queries per second avg: 15.500
It means MySQL serer is running
If server is not running then it will dump error as follows
# mysqladmin -u root -p status
Output :
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
So Under Debian Linux you can type following command
# /etc/init.d/mysql status
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
You need to convert the date into a readable value. You may use strftime() or date().
Try this:
$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
$effectiveDate = strftime ( '%Y-%m-%d' , $effectiveDate );
echo $effectiveDate;
This should work. I like using strftime better as it can be used for localization you might want to try it.
I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.
Entity Class: implement Serializable?
Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.
Constructors: create a constructor with all required fields of the entity?
Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.
Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.
OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.
Constructors: also, package private default constructor?
Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.
Fields/Properties
Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.
As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.
Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.
Protected is better for (Hibernate) performance?
Unlikely.
Equals/HashCode?
This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.
A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.
The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!
So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.
You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.
Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized
Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.
Equals/HashCode -- never refer to related entities
"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"
Sounds like good advice.
Hope this helps!
As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)
Just for the future
we need to observe that [(ngModel)]="hero.name"
is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event"
.
So if we de-sugar code we would end up with:
<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">
or
<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">
If you inspect the above code you will notice that we end up with 2 ngModelChange
events and those need to be executed in some order.
Summing up: If you place ngModelChange
before ngModel
, you get the $event
as the new value, but your model object still holds previous value.
If you place it after ngModel
, the model will already have the new value.
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
LD_LIBRARY_PATH
is searched when the program starts, LIBRARY_PATH
is searched at link time.
caveat from comments:
ld
(instead of gcc
or g++
), the LIBRARY_PATH
or LD_LIBRARY_PATH
environment variables are not read.gcc
or g++
, the LIBRARY_PATH
environment variable is read (see documentation "gcc
uses these directories when searching for ordinary libraries").You don't even need to define a constructor
struct foo {
bool a = true;
bool b = true;
bool c;
} bar;
To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.
There are several approaches.
One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional
Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.
urlpatterns = patterns('',
url(r'^project_config/$', views.foo),
url(r'^project_config/(?P<product>\w+)/$', views.foo),
url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)
Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:
def foo(request, optional_parameter=''):
# Your code goes here
The button
element has a default type of submit
.
You can make it do nothing by setting a type of button
:
<button type="button">Cancel changes</button>
You can first find the position of the string in this case ":"
'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")
Then use Left(StringToCut, NumberOfCharacterToCut)
Result = Left(StringToSearch, position -1)
unix flavors -> ll symLinkName
OSX -> readlink symLinkName
Difference is 1st way would display the sym link path in a blinking way and 2nd way would just echo it out on the console.
Inorder to find an app's name (application label), you need to do the following:
(as shown in other answers)
aapt
command, find the app label.But devices don't ship with the aapt
binary out-of-the-box.
So you will need to install it first. You can download it from here:
https://github.com/Calsign/APDE/tree/master/APDE/src/main/assets/aapt-binaries
Check this guide for complete steps:
How to find an app name using package name through ADB Android?
(Disclaimer: I am the author of that blog post)
sometimes you just need to give the slave a kick too
try
stop slave;
reset slave;
start slave;
show slave status;
quite often, slaves, they just get stuck guys :)
First of all, the space complexity of this loop is O(1)
(the input is customarily not included when calculating how much storage is required by an algorithm).
So the question that I have is if its possible that an algorithm has different time complexity from space complexity?
Yes, it is. In general, the time and the space complexity of an algorithm are not related to each other.
Sometimes one can be increased at the expense of the other. This is called space-time tradeoff.
This solution also work for background menu: http://www.roggel.com/NGNeer/BackgroundCMD/
The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
Documentation: Deserialize JSON from a file stream
Swipe Gesture in Swift 5
override func viewDidLoad() {
super.viewDidLoad()
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeLeft.direction = .left
self.view!.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeRight.direction = .right
self.view!.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeUp.direction = .up
self.view!.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeDown.direction = .down
self.view!.addGestureRecognizer(swipeDown)
}
@objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
if gesture.direction == UISwipeGestureRecognizer.Direction.right {
print("Swipe Right")
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
print("Swipe Left")
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.up {
print("Swipe Up")
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.down {
print("Swipe Down")
}
}
The error complains about localhost
rather than permissions and the current practice in MySQL is to have a bind-address specifying localhost
only in a configuration file.
So I don't think it's a password problem - except that you say you 'unzipped' MySQL.
Is that enough installation? What did you download?
Was there any installation step which allowed you to define a root password?
And, as NawaMan said, is the server running?
in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink()
, u will encounter with a wrong Warning message that says "permission denied"
however u can make folders & files by mkdir()
but the way u delete folders (rmdir()
) is different from the way you delete files(unlink()
)
eventually as a fact:
in many programming languages, any permission related error may not directly means an actual permission issue
for example, if you want to readSync
a file that doesn't exist with node fs module
you will encounter a wrong EPERM
error
<EditText
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="DD/MM/YYYY"
android:inputType="date"
android:focusable="false"/>
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="00:00"
android:inputType="time"
android:focusable="false"/>
JAVA FILE
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText selectDate,selectTime;
private int mYear, mMonth, mDay, mHour, mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectDate=(EditText)findViewById(R.id.date);
selectTime=(EditText)findViewById(R.id.time);
selectDate.setOnClickListener(this);
selectTime.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == selectDate) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if (view == selectTime) {
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
selectTime.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
}
Try the DrawEllipse method instead.
Simple example for how to set JAVA_HOME with setx.exe
in command line:
setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"
This will set environment variable "JAVA_HOME" for current user. If you want to set a variable for all users, you have to use option "-m". Here is an example:
setx -m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"
Note: you have to execute this command as Administrator.
Note: Make sure to run the command setx from an command-line Admin window
The best approach is to create a symbolic link like @SlateEntropy very well pointed out in the answer below. To help with this, since version 5.3, Laravel includes a command which makes this incredibly easy to do:
php artisan storage:link
That creates a symlink from public/storage
to storage/app/public
for you and that's all there is to it. Now any file in /storage/app/public
can be accessed via a link like:
http://somedomain.com/storage/image.jpg
If, for any reason, your can't create symbolic links (maybe you're on shared hosting, etc.) or you want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example a simple closure route like this:
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
You can now access your files just as you would if you had a symlink:
http://somedomain.com/storage/image.jpg
If you're using the Intervention Image Library you can use its built in response
method to make things more succinct:
Route::get('storage/{filename}', function ($filename)
{
return Image::make(storage_path('public/' . $filename))->response();
});
WARNING
Keep in mind that by manually serving the files you're incurring a performance penalty, because you're going through the entire Laravel request lifecycle in order to read and send the file contents, which is considerably slower than having the HTTP server handle it.