To dynamically change a variable you can do something like this:
String value = System.getenv("MY_HOME");
Properties prop = new Properties("log4j.properties");
prop.put("MY_HOME", value); // overwrite with value from environment
PropertyConfigurator.configure(prop);
You will find de log4j.properties in solr/examples/resources.
If you don't find the file, i put it here:
# Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n
#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9
#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF
Regards
Please changes your log file location to another drive. it will work.
this happen's the permission of creating log file.
1: Add the following line into the AssemblyInfo class
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
2: Make sure you don't use .Net Framework 4 Client Profile
as Target Framework
(I think this is OK on your side because otherwise it even wouldn't compile)
3: Make sure you log very early in your program. Otherwise, in some scenarios, it will not be initialized properly (read more on log4net FAQ).
So log something during application startup in the Global.asax
public class Global : System.Web.HttpApplication
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Global));
protected void Application_Start(object sender, EventArgs e)
{
Log.Info("Startup application.");
}
}
4: Make sure you have permission to create files and folders on the given path (if the folder itself also doesn't exist)
5: The rest of your given information looks ok
You can add/remove Appender programmatically to Log4j:
ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);
FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("mylog.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa);
//repeat with all other desired appenders
I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
and start with adding your own. You need log4j in the classpath of course for this to work.
Remark:
You can take any Logger.getLogger(...)
you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).
If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:
Logger fizz = LoggerFactory.getLogger("com.fizz")
will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to
Logger.getLogger("com.fizz").addAppender(newAppender)
then logging from fizz
will be handled by alle the appenders from the root logger and the newAppender
.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.
To add to @Gevorg, if you have a similar situation running Spark locally, place the log4j.properties file in the folder named resources under the main folder.
Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.
You have a bad package name
org.apache.log4j.rolling.RollingFileAppender
The correct one is:
org.apache.log4j.RollingFileAppender
After visiting this question and noting the initial concerns of the chosen solution, I figured I'd contribute this one for those not using Java 7 which uses FileUtils instead of IOUtils from Apache Commons. The advantage here is that the readFileToString and the writeStringToFile handle the issue of closing the files for you automatically. (writeStringToFile doesn't document it but you can read the source). Hopefully this recipe simplifies things for anyone new coming to this problem.
try {
String content = FileUtils.readFileToString(new File("InputFile"), "UTF-8");
content = content.replaceAll("toReplace", "replacementString");
File tempFile = new File("OutputFile");
FileUtils.writeStringToFile(tempFile, content, "UTF-8");
} catch (IOException e) {
//Simple exception handling, replace with what's necessary for your use case!
throw new RuntimeException("Generating file failed", e);
}
Write the root logger as below for logging on both console and FILE
log4j.rootLogger=ERROR,console,FILE
And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).
I encountered the exact same problem today, Ryan.
In my src (or your root) directory, my log4j.properties file now has the following addition
# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN
Thanks for the heads up as to how to do this, Benjamin.
Loki's answer points to the Hibernate 3 docs and provides good information, but I was still not getting the results I expected.
Much thrashing, waving of arms and general dead mouse runs finally landed me my cheese.
Because Hibernate 3 is using Simple Logging Facade for Java (SLF4J) (per the docs), if you are relying on Log4j 1.2 you will also need the slf4j-log4j12-1.5.10.jar if you are wanting to fully configure Hibernate logging with a log4j configuration file. Hope this helps the next guy.
There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might only want to include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.
tree
tree is a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree
, mac: brew install tree
, windows: zip) and which can generate plain text, XML, JSON or HTML output.
Generate an HTML directory index one level deep:
tree -H '.' -L 1 --noreport --charset utf-8 > index.html
Only include specific file types that match a glob pattern, e.g. *.zip
files:
tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" > index.html
The argument to
-H
is what will be used as a base href, so you can pass either a relative path such as.
or an absolute path from the web root, such as/files
.-L 1
limits the listing to the current directory only.
I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up using this script — in addition to having customizable styling, the script can also recursively generate an index.html
file in all the nested subdirectories.
Update: an updated version (python 3) of the index generation script that uses cleaner styling (inspired by caddyserver's file-server module), includes last modified times and is more responsive in mobile viewports.
You can use a regular expression for that pretty easily…
Allowing spaces around the word (but not keeping them):
str.match(/< ?([^>]+) ?>\Z/)[1]
Or without the spaces allowed:
str.match(/<([^>]+)>\Z/)[1]
You can do this for webkit:
#text2::-webkit-input-placeholder::before {
color:#666;
content:"Line 1\A Line 2\A Line 3\A";
}
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!
Example: To be placed in AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
A Simple and an easy way
var cusid_ele = document.getElementsByClassName('custid');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
item.innerHTML = 'this is value';
}
What you see for OPTIONS request is fine. Authorisation headers are not exposed in it.
But in order for basic auth to work you need to add: withCredentials = true;
to your var config
.
From the AngularJS $http documentation:
withCredentials -
{boolean}
- whether to to set thewithCredentials
flag on the XHR object. See requests with credentials for more information.
Here is what you can do: http://jsfiddle.net/n7cyE/4/
$('#here_table').append('<table></table>');
var table = $('#here_table').children();
for(i=0;i<3;i++){
table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
Best regards!
From Google Code FAQ - Creating a Store Locator with PHP, MySQL & Google Maps:
Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) )
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance
FROM markers
HAVING distance < 25
ORDER BY distance
LIMIT 0 , 20;
Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):
using System.Web.Mvc;
public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
var jsonResult = context.Result as JsonResult;
if (jsonResult == null) return;
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var jsonResult = filterContext.Result as JsonResult;
if (jsonResult == null) return;
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
base.OnResultExecuting(filterContext);
}
}
@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it to create a package without an __init__.py
file. This is called a namespace package in contrast to a regular package which does have an __init__.py
file (empty or not empty).
However, creating a namespace package should ONLY be done if there is a need for it. For most use cases and developers out there, this doesn't apply so you should stick with EMPTY __init__.py
files regardless.
To demonstrate the difference between the two types of python packages, lets look at the following example:
google_pubsub/ <- Package 1
google/ <- Namespace package (there is no __init__.py)
cloud/ <- Namespace package (there is no __init__.py)
pubsub/ <- Regular package (with __init__.py)
__init__.py <- Required to make the package a regular package
foo.py
google_storage/ <- Package 2
google/ <- Namespace package (there is no __init__.py)
cloud/ <- Namespace package (there is no __init__.py)
storage/ <- Regular package (with __init__.py)
__init__.py <- Required to make the package a regular package
bar.py
google_pubsub
and google_storage
are separate packages but they share the same namespace google/cloud
. In order to share the same namespace, it is required to make each directory of the common path a namespace package, i.e. google/
and cloud/
. This should be the only use case for creating namespace packages, otherwise, there is no need for it.
It's crucial that there are no __init__py
files in the google
and google/cloud
directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.path
with a name that matches the package name being looked for will be recognized as contributing modules and subpackages to that package. As a result, when you import both from google_pubsub
and google_storage
, the Python interpreter will be able to find them.
This is different from regular packages which are self-contained meaning all parts live in the same directory hierarchy. When importing a package and the Python interpreter encounters a subdirectory on the sys.path
with an __init__.py
file, then it will create a single directory package containing only modules from that directory, rather than finding all appropriately named subdirectories outside that directory. This is perfectly fine for packages that don't want to share a namespace. I highly recommend taking a look at Traps for the Unwary in Python’s Import System to get a better understanding of how Python importing behaves with regular and namespace package and what __init__.py
traps to watch out for.
__init__.py
files if you want to create namespace packages. Only create namespace packages if you have different libraries that reside in different locations and you want them each to contribute a subpackage to the parent package, i.e. the namespace package.__init__py
to your directories because 99% of the time you just want to create regular packages. Also, Python tools out there such as mypy
and pytest
require empty __init__.py
files to interpret the code structure accordingly. This can lead to weird errors if not done with care.My answer only touches the surface of how regular packages and namespace packages work so take a look at the following resources for further information:
Just for completion the data.table solution:
library(data.table)
mydf <- structure(list(ID = c(110L, 111L, 121L, 131L, 141L),
MONTH.YEAR = c("JAN. 2012", "JAN. 2012",
"FEB. 2012", "FEB. 2012",
"MAR. 2012"),
VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)),
.Names = c("ID", "MONTH.YEAR", "VALUE"),
class = "data.frame", row.names = c(NA, -5L))
setDT(mydf)
mydf[, .(`Number of rows` = .N), by = MONTH.YEAR]
MONTH.YEAR Number of rows
1: JAN. 2012 2
2: FEB. 2012 2
3: MAR. 2012 1
In my case, my script has parameters, so I set:
Arguments: -Command "& C:\scripts\myscript.ps1 myParam1 myParam2"
html, body{
width:100%;
}
This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.
You may want to set a min width instead.
html, body{
min-width:100%;
}
So it will be 100% as a minimum, bot more if needed.
This expression 12-4-2005
is a calculated int and the value is -1997
. You should do like this instead '2005-04-12'
with the '
before and after.
Add this line above you Query
SET IDENTITY_INSERT tbl_content ON
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
I want to compare UTC timestamps from a log file with local timestamps
If this is your intent, then I wouldn't worry about specifying specific tzinfo parameters or any additional external libraries. Since Python 3.5, the built in datetime module is all you need to create a UTC and a local timestamp automatically.
import datetime
f = "%a %b %d %H:%M:%S %Z %Y" # Full format with timezone
# tzinfo=None
cdatetime = datetime.datetime(2010, 4, 27, 12, 0, 0, 0) # 1. Your example from log
cdatetime = datetime.datetime.now() # 2. Basic date creation (default: local time)
print(cdatetime.strftime(f)) # no timezone printed
# Tue Apr 27 12:00:00 2010
utctimestamp = cdatetime.astimezone(tz=datetime.timezone.utc) # 1. convert to UTC
utctimestamp = datetime.datetime.now(tz=datetime.timezone.utc) # 2. create in UTC
print(utctimestamp.strftime(f))
# Tue Apr 27 17:00:00 UTC 2010
localtimestamp = cdatetime.astimezone() # 1. convert to local [default]
localtimestamp = datetime.datetime.now().astimezone() # 2. create with local timezone
print(localtimestamp.strftime(f))
# Tue Apr 27 12:00:00 CDT 2010
The '%Z' parameter of datetime.strftime() prints the timezone acronym into the timestamp for humans to read.
I know this an old thread, but I found out using the Subtotal method in VBA also accurately renders a count of the rows. The formula I found is in this article, and looks like this:
Application.WorksheetFunction.Subtotal(2, .Range("A2:A" & .Rows(.Rows.Count).End(xlUp).Row))
I tested it and it came out accurately every time, rendering the correct number of visible rows in column A.
Hopefully this will help some other wayfarer of the 'Net like me.
How do I invoke a maven task without leaving vi?
Maven is no different than any other shell command:
:!mvn
You can :set makeprg=mvn
if you already have a favourite key mapping for :make
.
Can I get code completion?
Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.
<C-n>
and <C-p>
are not-so-great, but amazingly helpful.
How's the syntax highlighting?
More than good enough for a regex-based highligher.
You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh
).
In v 5.8.38, I set the env file as the following:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=difficultCombination
MAIL_ENCRYPTION=ssl
MAIL_FROM_NAME=myWebappName
After doing php artisan config:clear
, it worked well on a shard server.
According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Doing either
mystring == yourstring
or
mystring.eql? yourstring
Are equivalent.
Start session from terminal:
openssl s_client -connect smtp.gmail.com:25 -starttls smtp
The last line of the response should be "250 SMTPUTF8"
Initiate login
auth login
This should return "334 VXNlcm5hbWU6".
Type username
Type your username in base64 encoding (eg. echo -n 'your-username' | base64
)
This should return "334 UGFzc3dvcmQ6"
Type password
Type your password in base64 encoding (eg. echo -n 'your-password' | base64
)
Success
You should see "235 2.7.0 Accepted" and you're are successfully logged in
@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:
(true) ? 1 : 0
Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \
line-continuation symbol at the end of a line and Ruby will be happy:
(true) \
? 1 \
: 0
This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.
It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:
(true) ?
1 :
0
I think that leads to really hard to read code as the conditional test and/or results get longer.
I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..
' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.
Why have you put brackets around
true
?
Consider the OP's example:
<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
Wrapping the conditional test helps make it more readable because it visually separates the test:
<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>
Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:
<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
: question.question
%>
Or, more written more idiomatically:
<% question = if (question.size > 20)
question.question.slice(0, 20) + "..."
else
question.question
end
%>
It'd be easy to argument that readability suffers badly from question.question
too.
This will help
wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir
use the arguments -Xms<memory>
-Xmx<memory>
. Use M
or G
after the numbers for indicating Megs and Gigs of bytes respectively. -Xms
indicates the minimum and -Xmx
the maximum.
You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:
# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful
On Ubuntu/Debian you can configure headers in the file
/etc/apache2/conf-enabled/security.conf
#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"
#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"
Note: This is the bottom part of the file. Only the last three entries are CSP settings.
The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.
Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.
While you're at it you could take a look at the other header settings and install mod_security
Further reading:
https://developers.google.com/web/fundamentals/security/csp/
If variable1
is a string, and you are searching for a substring in it, this should work:
when: '"value" in variable1'
if variable1
is an array or dict instead, in
will search for the exact string as one of its items.
If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.
Ex.
Filename: csvsample.php
class csvsample {
}
I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser
Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that
sudo apt install php libapache2-mod-php sudo apt install php7.0-mbstring sudo a2dismod mpm_event sudo a2enmod mpm_prefork service apache2 restart
And then to:
gksu gedit /etc/apache2/apache2.conf
In the last line I do add Include /etc/phpmyadmin/apache.conf
That make a deal with all problems
Maciej
If it solves your problem, up vote this solution in the original post.
I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.
I faced this same error while because I was using parameters in my php file path like this:
/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234
But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:
/usr/bin/php -q /home/**/public_html/cron/job.php id=1234
Just replace the "?"
with a space " "
.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
The only one i have found for Cross-site, is this function:
<script type="text/javascript">
var your_url = 'http://www.example.com';
</script>
<script type="text/javascript" src="jquery.min.js" ></script>
<script type="text/javascript">
// jquery.xdomainajax.js ------ from padolsey
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0]
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: your_url,
type: 'GET',
success: function(res) {
var text = res.responseText;
// then you can manipulate your text as you wish
alert(text);
}
});
</script>
you can use flex box for it.. this will solve your problem
.image-parent
{
height:33px;
display:flex;
}
You must declare the reportfile as variable for console.
Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....
Example: for batch/console
cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile
Exemple Javascript:
var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;
You can change the dir and filename how ever you want.
Frank from Berlin
It means that you compiled your classes under a specific JDK, but then try to run them under older version of JDK.
The comma got eaten by the quotes!
This part:
("username," visitorName);
Should be this:
("username", visitorName);
Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)
In case if you are using node js, then this could be the possible solution
const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;
You could use addEventListener to add as many listeners as you want.
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
Also add script
tag after the element to make sure Save
element is loaded at the time when script runs
Rather than moving script tag you could call it when dom is loaded. Then you should place your code inside the
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
});
Consider that we need to create the following XML document:
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
we can write the following code to generate the above XML
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
If any text need to be written between a tag we can use innerHTML property to achieve it.
Example
elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)
For more details please follow the below link. The above example has been explained there in more details.
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
If you are running out of connections like this, chances are excellent that you are not closing the connections that you have open.
Review code that opens connections and ensure the connections are closed as soon as practical. Typically you want to make use of the using keyword around anything that implements IDisposable (including database connections) to ensure that such objects are disposed as soon as they leave the scope where they are needed.
You can check the current number of active connections with this query:
show processlist
I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.
I didn't have high hopes, as that plugin was last updated in 2011
Parse that string into a Date
object:
var myDate = new Date('10/11/1955 10:40:50 AM');
Then use the usual methods to get the date's day of month (getDate
) / month (getMonth
) / year (getFullYear
).
var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());
In addition to perfect Riceball LEE's example of adding a new element-directive
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
Adding a new attribute-directive to existed element could be done using this way:
Let's say you wish to add on-the-fly my-directive
to the span
element.
template: '<div>Hello <span>World</span></div>'
link: ($scope, $element, $attrs) ->
span = $element.find('span').clone()
span.attr('my-directive', 'my-directive')
span = $compile(span)($scope)
$element.find('span').replaceWith span
Hope that helps.
If you want to copy the DataTable
to another DataTable
of different Schema Structure
then you can do this:
DataType
so that you can only get the structure.DataTable
. So:
Dim dt1 As New DataTable
dt1 = dtExcelData.Clone()
dt1.Columns(17).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(26).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(30).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(35).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(38).DataType = System.Type.GetType("System.Decimal")
dt1 = dtprevious.Copy()
Hence you get the same DataTable
but revised structure
Installing psqlODBC on 64bit Windows
Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.
How to configure 32 bit ODBC drivers on Win x64
Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe
%SystemRoot%\syswow64\odbcad32.exe
You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.
I recently started using Qt as a GUI framework for a Ruby application. There is a binding called QtRuby. For a quickstart tutorial (covers only windows) see this post
Above methods will remove your output file data whenever you run above nohup command.
To Append output in user defined file you can use >>
in nohup command.
nohup your_command >> filename.out &
This command will append all output in your file without removing old data.
from django.http import JsonResponse
def SomeFunction(): dict1 = {}
obj = list( Mymodel.objects.values() )
dict1['data']=obj
return JsonResponse(dict1)
Try this code for Django
This should be working too using JPA 2.0 @MapsId annotation instead of Hibernate's GenericGenerator:
@Entity
public class Person {
@Id
@GeneratedValue
public int id;
@OneToOne
@PrimaryKeyJoinColumn
public OtherInfo otherInfo;
rest of attributes ...
}
@Entity
public class OtherInfo {
@Id
public int id;
@MapsId
@OneToOne
@JoinColumn(name="id")
public Person person;
rest of attributes ...
}
More details on this in Hibernate 4.1 documentation under section 5.1.2.2.7.
Do not forget to verify if your text editor encodes properly your code in UTF-8.
Otherwise, you may have invisible characters that are not interpreted as UTF-8.
When nginx returns 400(bad request) it will log the reason into error log, at "info" level and take a look into error log when testing.
This will work for the MacOS for Firefox and Chrome:
// opens the default browser tab with the first webpage
driver.get("the url 1");
thread.sleep(2000);
// opens the second tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver.get("the url 2");
Thread.sleep(2000);
// comes back to the first tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");
Let's not forget the most important thing to learn out of a question like this: SQL Injection.
Use PDO and prepared statements.
Click here for a tutorial on PDO.
you can use ltrim or rtrim to clean whitespaces for the right or left or a string.
yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
I struggled to get this working. That's why I'll add a complete solution here:
My objective is to add this header to the SOAP envelope:
<soapenv:Header>
<urn:OTAuthentication>
<urn:AuthenticationToken>TOKEN</urn:AuthenticationToken>
</urn:OTAuthentication>
</soapenv:Header>
First create a SOAPHeaderHandler
class.
import java.util.Set;
import java.util.TreeSet;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
private final String authenticatedToken;
public SOAPHeaderHandler(String authenticatedToken) {
this.authenticatedToken = authenticatedToken;
}
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty =
(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
try {
SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
SOAPFactory factory = SOAPFactory.newInstance();
String prefix = "urn";
String uri = "urn:api.ecm.opentext.com";
SOAPElement securityElem =
factory.createElement("OTAuthentication", prefix, uri);
SOAPElement tokenElem =
factory.createElement("AuthenticationToken", prefix, uri);
tokenElem.addTextNode(authenticatedToken);
securityElem.addChildElement(tokenElem);
SOAPHeader header = envelope.addHeader();
header.addChildElement(securityElem);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// inbound
}
return true;
}
public Set<QName> getHeaders() {
return new TreeSet();
}
public boolean handleFault(SOAPMessageContext context) {
return false;
}
public void close(MessageContext context) {
//
}
}
setHandlerChain
is required to configure the binding instance with the new chain."Authentication_Service authentication_Service = new Authentication_Service();
Authentication basicHttpBindingAuthentication = authentication_Service.getBasicHttpBindingAuthentication();
String authenticatedToken = "TOKEN";
List<Handler> handlerChain = ((BindingProvider)basicHttpBindingAuthentication).getBinding().getHandlerChain();
handlerChain.add(new SOAPHeaderHandler(authenticatedToken));
((BindingProvider)basicHttpBindingAuthentication).getBinding().setHandlerChain(handlerChain);
webbot
even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.
Here's a snippet :)
from webbot import Browser
web = Browser()
web.go_to('google.com')
web.click('Sign in')
web.type('[email protected]' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^
The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io
You can use fill().
let arr = new Array(5).fill('lol');
let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));
Will create an array of 5 items. Then you can use forEach for example.
arr.forEach(str => console.log(str));
Note that when doing new Array(5)
it's just an object with length 5 and the array is empty. When you use fill()
you fill each individual spot with whatever you want.
Here is some good overview of .NET impersonation concepts.
Basically you will be leveraging these classes that are out of the box in the .NET framework:
The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.
First, Identify the user you are logged in as:
select user();
select current_user();
The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost
in mysql.
Grant_priv
to root@localhost
. Here is how you can check.
mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host | user | password | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root | ***************************************** | N | Y |
| localhost | debian-sys-maint | ***************************************** | Y | Y |
| localhost | staging | ***************************************** | N | N |
+-----------+------------------+-------------------------------------------+------------+------------+
You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';
I logged back in, it was fine.
I have created a very simple library https://github.com/ravinderpayal/FooterJS
It is very simple in use. After including library, just call this line of code.
footer.init(document.getElementById("ID_OF_ELEMENT_CONTAINING_FOOTER"));
Footers can be dynamically changed by recalling above function with different parameter/id.
footer.init(document.getElementById("ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER"));
Note:- You haven't to alter or add any CSS. Library is dynamic which implies that even if screen is resized after loading page it will reset the position of footer. I have created this library, because CSS solves the problem for a while but when size of display changes significantly,from desktop to tablet or vice versa, they either overlap the content or they no longer remains sticky.
Another solution is CSS Media Queries, but you have to manually write different CSS styles for different size of screens while this library does its work automatically and is supported by all basic JavaScript supporting browser.
Edit CSS solution:
@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/
/* For mobile phones: */
#footer {
width: 100%;
position:fixed;
bottom:0;
}
}
Now, if the height of display is more than your content length, we will make footer fixed to bottom and if not, it will automatically appear in very end of display as you need to scroll to view this.
And, it seems a better solution than JavaScript/library one.
I tried JSON. It worked. But I hate having to create the struct of the exact fields and types I might be setting. To me that was a pain. I noticed it was the method used by all the configuration options I could find. Maybe my background in dynamic languages makes me blind to the benefits of such verboseness. I made a new simple config file format, and a more dynamic-ish lib for reading it out.
https://github.com/chrisftw/ezconf
I am pretty new to the Go world, so it might not be the Go way. But it works, it is pretty quick, and super simple to use.
hi try the following ...
function pageLoad (sender, args) {
alert (args._isPartialLoad);
}
the result is a Boolean
users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1
for i in ${users[@]}; do
t=$(( t + 1 ))
if [ $t -eq 0 ]; then
for j in ${!users[@]}; do
index[$j]=$j
done
fi
echo "${index[$t]} is $i"
done
Which operating system?
For windows machines, if you're writing a server to scale well, and therefore using I/O Completion Ports and async I/O, then the main limitation is the amount of non-paged pool that you're using for each active connection. This translates directly into a limit based on the amount of memory that your machine has installed (non-paged pool is a finite, fixed size amount that is based on the total memory installed).
For connections that don't see much traffic you can reduce make them more efficient by posting 'zero byte reads' which don't use non-paged pool and don't affect the locked pages limit (another potentially limited resource that may prevent you having lots of socket connections open).
Apart from that, well, you will need to profile but I've managed to get more than 70,000 concurrent connections on a modestly specified (760MB memory) server; see here http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html for more details.
Obviously if you're using a less efficient architecture such as 'thread per connection' or 'select' then you should expect to achieve less impressive figures; but, IMHO, there's simply no reason to select such architectures for windows socket servers.
Edit: see here http://blogs.technet.com/markrussinovich/archive/2009/03/26/3211216.aspx; the way that the amount of non-paged pool is calculated has changed in Vista and Server 2008 and there's now much more available.
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
In either case, I'd expect file.getParent()
(or file.getParentFile()
) to give you what you want.
Additionally, if you want to find out whether the original File
does exist and is a directory, then exists()
and isDirectory()
are what you're after.
Create specific .yml files in the resources directory for each and every environment(Eg: dev,qa,stg etc.) that you need to run the application. image of .yml files in resources directory
If you are using spring-boot-maven-plugin 2.0.5.RELEASE in your pom.xml file you can add the profiles within the dependency tag as follows. image of pom.xml spring-boot-maven-plugin (you can configure multiple profiles using multiple profile tags)
Then you can use the following commands to build and run the project.
1) mvn clean install
2) mvn spring-boot:run -Dspring-boot.run.default==qa
Then you will see that the default profile is set as qa while running the project. displaying the default profile when running the application
Because this pops-up in Google when trying to find an answer to: "Error: Argument '' is not a function, got undefined".
It's possible that you are trying to create the same module twice.
The angular.module is a global place for creating, registering and retrieving AngularJS modules.
Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module
Source: https://docs.angularjs.org/api/ng/function/angular.module#overview
Example:
angular.module('myApp', [])
Is used to create a module without injecting any dependencies.
angular.module('myApp')
(Without argument) is used to get an existing module.
There are two ways to add new properties to an object:
var obj = {
key1: value1,
key2: value2
};
obj.key3 = "value3";
obj["key3"] = "value3";
The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:
var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key1");
getProperty("key2");
getProperty("key3");
A real JavaScript array can be constructed using either:
var arr = [];
var arr = new Array();
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return (!isset($str) || trim($str) === '');
}
A lot of these answers sound like trial and error. In my case though, it was simple: the referenced dll was not found in that particular location.
If you see the build errors, typically in this case, the build complains about many dlls. The key is to find the right dll that is missing. In my case, one of the projects in my solution had a direct dll reference instead of a project reference. So, I needed to build the project that outputs that dll before building the failing solution to make sure the failing solution finds the missing dll in that particular location.
Wow.. that was simple, but quite difficult to put it into words.
You can use the MultilineLabel component in the Jide Open Source Components.
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
public abstract class ExternalScript extends Script {
private String source;
public void setSource(String file) {
source = file;
}
public String getSource() {
return source;
}
}
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
Javascript in a browser only really has a couple of effective scopes: function scope and global scope.
If a variable isn't in function scope, it's in global scope. And global variables are generally bad, so this is a construct to keep a library's variables to itself.
Somewhere around r59 this gets easier (rotate around x):
bb.GraphicsEngine.prototype.calcRotation = function ( obj, rotationX)
{
var euler = new THREE.Euler( rotationX, 0, 0, 'XYZ' );
obj.position.applyEuler(euler);
}
You have various possibilies. The most simple and the most ugly is:
XAML
<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/>
Code Behind
private void Button_Clicked(object sender, RoutedEventArgs e) {
FrameworkElement fe=sender as FrameworkElement;
((YourClass)fe.DataContext).DoYourCommand();
}
Another solution (better) is to provide a ICommand-property on your YourClass
. This command will have already a reference to your YourClass
-object and therefore can execute an action on this class.
XAML
<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>
Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.
It happened that I needed to link a data model of a person with a form, what I did was a direct mapping of the data with the form.
For example if the model had something like:
$scope.model.people.name
The control input of the form:
<input type="text" name="namePeople" model="model.people.name">
That way if you modify the value of the object controller, this will be reflected automatically in the view.
An example where I passed the model is updated from server data is when you ask for a zip code and zip code based on written loads a list of colonies and cities associated with that view, and by default set the first value with the user. And this I worked very well, what does happen, is that angularJS
sometimes takes a few seconds to refresh the model, to do this you can put a spinner while displaying the data.
About the same as sanchothefat's answer, but from a different aspect. I always ask myself: if I would completely remove the stylesheets from the website, do the remaining elements only belong to the content? If so, I did my job well.
The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.
Good Example :-
switch(5) {
case 1:
echo "1";
break;
case 2:
default:
echo "2, default";
break;
case 3;
echo "3";
break;
}
Outputs '2,default'
very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default
This Technical Note TN2328 from Apple Developer Library helped me a lot about Changes To Embedding Python Using Xcode 5.0.
Modern Jenkins versions (since 2.26, October 2016) solved this: it's just an advanced option for the Execute shell build step!
You can just choose and set an arbitrary exit value; if it matches, the build will be unstable. Just pick a value which is unlikely to be launched by a real process in your build.
Its so simple just use this
header("location:javascript://history.go(-1)");
Its working fine for me
Even More straightforward:
axios.post('/addUser',{
userName: 'Fred',
userEmail: '[email protected]'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Seems like last_accessed_on, is a date time, and you are converting '23-07-2014 09:37:00' to a varchar. This would not work, and give you conversion errors. Try
last_accessed_on= convert(datetime,'23-07-2014 09:37:00', 103)
I think you can avoid the cast though, and update with '23-07-2014 09:37:00'. It should work given that the format is correct.
Your query is not going to work because in last_accessed_on (which is DateTime2 type), you are trying to pass a Varchar value.
You query would be
UPDATE student_queues SET Deleted=0 , last_accessed_by='raja', last_accessed_on=convert(datetime,'23-07-2014 09:37:00', 103)
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Everything you need to know about underscore template is here. Only 3 things to keep in mind:
<% %>
- to execute some code<%= %>
- to print some value in template<%- %>
- to print some values HTML escapedThat's all about it.
Simple example:
var tpl = _.template("<h1>Some text: <%= foo %></h1>");
then tpl({foo: "blahblah"})
would be rendered to the string <h1>Some text: blahblah</h1>
For those who were having trouble parsing other answers:
eval "for _,k in ipairs(redis.call('keys','key:*:pattern')) do redis.call('del',k) end" 0
Replace key:*:pattern
with your own pattern and enter this into redis-cli
and you are good to go.
Credit lisco from: http://redis.io/commands/del
The other answers are just fine but this one highlights a few fairly important gotchas of animating constraints using a recent example. I went through a lot of variations before I realized the following:
Make the constraints you want to target into Class variables to hold a strong reference. In Swift I used lazy variables:
lazy var centerYInflection:NSLayoutConstraint = {
let temp = self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
return temp!
}()
After some experimentation I noted that one MUST obtain the constraint from the view ABOVE (aka the superview) the two views where the constraint is defined. In the example below (both MNGStarRating and UIWebView are the two types of items I am creating a constraint between, and they are subviews within self.view).
Filter Chaining
I take advantage of Swift's filter method to separate the desired constraint that will serve as the inflection point. One could also get much more complicated but filter does a nice job here.
Animating Constraints Using Swift
Nota Bene - This example is the storyboard/code solution and assumes one has made default constraints in the storyboard. One can then animate the changes using code.
Assuming you create a property to filter with accurate criteria and get to a specific inflection point for your animation (of course you could also filter for an array and loop through if you need multiple constraints):
lazy var centerYInflection:NSLayoutConstraint = {
let temp = self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
return temp!
}()
....
Sometime later...
@IBAction func toggleRatingView (sender:AnyObject){
let aPointAboveScene = -(max(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height) * 2.0)
self.view.layoutIfNeeded()
//Use any animation you want, I like the bounce in springVelocity...
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.75, options: [.CurveEaseOut], animations: { () -> Void in
//I use the frames to determine if the view is on-screen
if CGRectContainsRect(self.view.frame, self.ratingView.frame) {
//in frame ~ animate away
//I play a sound to give the animation some life
self.centerYInflection.constant = aPointAboveScene
self.centerYInflection.priority = UILayoutPriority(950)
} else {
//I play a different sound just to keep the user engaged
//out of frame ~ animate into scene
self.centerYInflection.constant = 0
self.centerYInflection.priority = UILayoutPriority(950)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}) { (success) -> Void in
//do something else
}
}
}
These notes are really a set of tips that I wrote for myself. I did all the don'ts personally and painfully. Hopefully this guide can spare others.
Watch out for zPositioning. Sometimes when nothing is apparently happening, you should hide some of the other views or use the view debugger to locate your animated view. I've even found cases where a User Defined Runtime Attribute was lost in a storyboard's xml and led to the animated view being covered (while working).
Always take a minute to read the documentation (new and old), Quick Help, and headers. Apple keeps making a lot of changes to better manage AutoLayout constraints (see stack views). Or at least the AutoLayout Cookbook. Keep in mind that sometimes the best solutions are in the older documentation/videos.
Play around with the values in the animation and consider using other animateWithDuration variants.
Don't hardcode specific layout values as criteria for determining
changes to other constants, instead use values that allow you to
determine the location of the view. CGRectContainsRect
is one
example
let viewMargins = self.webview.layoutMarginsGuide
: is on exampleQuick Sample Of Solutions to AVOID when using Storyboards
private var _nc:[NSLayoutConstraint] = []
lazy var newConstraints:[NSLayoutConstraint] = {
if !(self._nc.isEmpty) {
return self._nc
}
let viewMargins = self.webview.layoutMarginsGuide
let minimumScreenWidth = min(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height)
let centerY = self.ratingView.centerYAnchor.constraintEqualToAnchor(self.webview.centerYAnchor)
centerY.constant = -1000.0
centerY.priority = (950)
let centerX = self.ratingView.centerXAnchor.constraintEqualToAnchor(self.webview.centerXAnchor)
centerX.priority = (950)
if let buttonConstraints = self.originalRatingViewConstraints?.filter({
($0.firstItem is UIButton || $0.secondItem is UIButton )
}) {
self._nc.appendContentsOf(buttonConstraints)
}
self._nc.append( centerY)
self._nc.append( centerX)
self._nc.append (self.ratingView.leadingAnchor.constraintEqualToAnchor(viewMargins.leadingAnchor, constant: 10.0))
self._nc.append (self.ratingView.trailingAnchor.constraintEqualToAnchor(viewMargins.trailingAnchor, constant: 10.0))
self._nc.append (self.ratingView.widthAnchor.constraintEqualToConstant((minimumScreenWidth - 20.0)))
self._nc.append (self.ratingView.heightAnchor.constraintEqualToConstant(200.0))
return self._nc
}()
If you forget one of these tips or the more simple ones such as where to add the layoutIfNeeded, most likely nothing will happen: In which case you may have a half baked solution like this:
NB - Take a moment to read the AutoLayout Section Below and the original guide. There is a way to use these techniques to supplement your Dynamic Animators.
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1.0, options: [.CurveEaseOut], animations: { () -> Void in
//
if self.starTopInflectionPoint.constant < 0 {
//-3000
//offscreen
self.starTopInflectionPoint.constant = self.navigationController?.navigationBar.bounds.height ?? 0
self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)
} else {
self.starTopInflectionPoint.constant = -3000
self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)
}
}) { (success) -> Void in
//do something else
}
}
Snippet from the AutoLayout Guide (note the second snippet is for using OS X). BTW - This is no longer in the current guide as far as I can see. The preferred techniques continue to evolve.
Animating Changes Made by Auto Layout
If you need full control over animating changes made by Auto Layout, you must make your constraint changes programmatically. The basic concept is the same for both iOS and OS X, but there are a few minor differences.
In an iOS app, your code would look something like the following:
[containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
[UIView animateWithDuration:1.0 animations:^{
// Make all constraint changes here
[containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
}];
In OS X, use the following code when using layer-backed animations:
[containterView layoutSubtreeIfNeeded];
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
[context setAllowsImplicitAnimation: YES];
// Make all constraint changes here
[containerView layoutSubtreeIfNeeded];
}];
When you aren’t using layer-backed animations, you must animate the constant using the constraint’s animator:
[[constraint animator] setConstant:42];
For those who learn better visually check out this early video from Apple.
Often in documentation there are small notes or pieces of code that lead to bigger ideas. For example attaching auto layout constraints to dynamic animators is a big idea.
Good Luck and May the Force be with you.
this is it:
@echo off
:: del_ext
call :del_ext "*.txt"
call :del_ext "*.png"
call :del_ext "*.jpg"
:: funcion del_ext
@echo off
pause
goto:eof
:del_ext
set del_ext=%1
del /f /q "folder_path\%del_ext%"
goto:eof
pd: replace folder_path with your folder
For the relative path (i.e. the direct equivalent of Windows' %~dp0
):
MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"
For the absolute, normalized path:
MY_PATH="`dirname \"$0\"`" # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`" # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
# error; for some reason, the path is not accessible
# to the script (e.g. permissions re-evaled after suid)
exit 1 # fail
fi
echo "$MY_PATH"
Did have identical problem with on XP machine when installing javacv
and opencv
in combination with Eclipse. It turned out that I was missing the following files:
Once these were installed, the project compiled and ran OK.
My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.
You could do this easily by creating a CreateRoles
method in your startup
class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//Here you could create a super user who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration["AppSettings:UserName"],
Email = Configuration["AppSettings:UserEmail"],
};
//Ensure you have these values in your appsettings.json file
string userPWD = Configuration["AppSettings:UserPassword"];
var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);
if(_user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
and then you could call the CreateRoles(serviceProvider).Wait();
method from the Configure
method in the Startup class.
ensure you have IServiceProvider
as a parameter in the Configure
class.
Using role-based authorization in a controller to filter user access: Question 2
You can do this easily, like so.
[Authorize(Roles="Manager")]
public class ManageController : Controller
{
//....
}
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
.....
*/
}
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here
Update for RxJS 6 (April 2018)
It is now perfectly fine to import directly from rxjs
. (As can be seen in Angular 6+). Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). Thanks to this treeshaking can now be used as well.
Sample code from rxjs repo:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
Backwards compatibility for rxjs < 6?
rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x
code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.
To update this for Python-3 you can do this
"{} {}".format(True, False)
However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.
>>> "{:<8} {}".format(True, False)
'1 False'
To get around this you can cast True
as a string, e.g.
>>> "{:<8} {}".format(str(True), False)
'True False'
As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.
i tried using the same ng-click for two elements with same name showDetail2('abc')
it is working for me . can you check rest of the code which may be breaking you to move further.
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
On an AWS Ubuntu 16.04 Server I put the Docker images on a separate EBS, mounted on /home/ubuntu/kaggle/, under the docker dir
This snippet of my initialization script worked correctly
# where are the images initially stored?
sudo docker info | grep "Root Dir"
# ... not where I want them
# modify the configuration files to change to image location
# NOTE this generates an error
# WARNING: Usage of loopback devices is strongly discouraged for production use.
# Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
# see https://stackoverflow.com/questions/31620825/
# warning-of-usage-of-loopback-devices-is-strongly-discouraged-for-production-use
sudo sed -i ' s@#DOCKER_OPTS=.*@DOCKER_OPTS="-g /home/ubuntu/kaggle/docker"@ ' /etc/default/docker
sudo chmod -R ugo+rw /lib/systemd/system/docker.service
sudo cp /lib/systemd/system/docker.service /etc/systemd/system/
sudo chmod -R ugo+rw /etc/systemd/system/
sudo sed -i ' s@ExecStart.*@ExecStart=/usr/bin/dockerd $DOCKER_OPTS -H fd://@ ' /etc/systemd/system/docker.service
sudo sed -i '/ExecStart/a EnvironmentFile=-/etc/default/docker' /etc/systemd/system/docker.service
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo docker info | grep "Root Dir"
# now they're where I want them
Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"
Explanation : [How it works]
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
Hope it work
Other warning
objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int
Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"
[caution: It may void other warning of 64 Bits architecture conversion].
The value disappears since the read command is run in a separate subshell: Bash FAQ 24
I got this problem somewhere on the logs and I saw that my java version was not 1.8 somehow. Upgrading it again to 1.8 solved my problem.
You can have this if you are trying to manifest your application that it has a dependancy on the Microsoft.Windows.Common-Controls assembly. You do this when you want to load Version 6 of the common controls library - so that visual styles are applied to common controls.
You probably followed Microsoft's original documentation way back from Windows XP days, and added the following to your application's manifest:
<!-- Dependancy on Common Controls version 6 -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Windows XP is no longer the OS, and you're no longer a 32-bit application. In the intervening 17 years Microsoft updated their documentation; now it's time for you to update your manifest:
<!-- Dependancy on Common Controls version 6 -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Raymond Chen has a lovely history of the Common Controls:
You will get this warning if you are using npm v6 or before. After npm v7.0, npm development team has stated that they will automatically install peer dependencies, all together. Therefore, now you don't want to install your peer dependencies manually.
You can install npm v7.0 using this command,
npm install -g npm@7
Learn more about npm v7.0 from this blog post, published by the Github Blog.
In the page source I see the following:
<div class="holder">
<div id="s7" style="position: relative; width: 1366px; height: 474px; overflow: hidden;">
If you put the height value in the tag, it will use this instead of the height defined in the css file.
Use the power of Python and lean on one of the best libraries around: requests
import requests
r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
print(r.text)
Variable r (requests response) has a lot more parameters that you can use. Best thing is to pop into the interactive interpreter and play around with it, and/or read requests docs.
ubuntu@hostname:/home/ubuntu$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass'))
>>> dir(r)
['__attrs__', '__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__nonzero__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_content_consumed', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'iter_content', 'iter_lines', 'json', 'links', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url']
>>> r.content
b'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.text
'{"battery_status":0,"margin_status":0,"timestamp_status":null,"req_status":0}'
>>> r.status_code
200
>>> r.headers
CaseInsensitiveDict({'x-powered-by': 'Express', 'content-length': '77', 'date': 'Fri, 20 May 2016 02:06:18 GMT', 'server': 'nginx/1.6.3', 'connection': 'keep-alive', 'content-type': 'application/json; charset=utf-8'})
If your UML modeling tool has support for specifying an Enumeration, you should use that. It will likely be easier to do and it will give your model stronger semantics. Visually the result will be very similar to a Class with an <<enumeration>>
Stereotype, but in the UML metamodel, an Enumeration is actually a separate (meta)type.
+---------------------+
| <<enumeration>> |
| DayOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
+---------------------+
Once it is defined, you can use it as the type of an Attribute just like you would a Datatype or the name one of your own Classes.
+---------------------+
| Event |
|_____________________|
| day : DayOfTheWeek |
| ... |
+---------------------+
If you're using ArgoEclipse or ArgoUML, there's a pulldown menu on the toolbar which selects among Datatype, Enumeration, Signal, etc that will allow you to create your own Enumerations. The compartment that normally contains Attributes can then be populated with EnumerationLiterals for the values of your enumeration.
Here's a picture of a slightly different example in ArgoUML:
Two simple solutions:
Execute your code once before the while loop
actions() {
check_if_file_present
# Do other stuff
}
actions #1st execution
while [ current_time <= $cutoff ]; do
actions # Loop execution
done
Or:
while : ; do
actions
[[ current_time <= $cutoff ]] || break
done
@Patrick I would improve your solution a bit
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectNode objectNode = jp.readValueAsTree();
JsonNode wrapped = objectNode.get(wrapperKey);
JsonParser parser = node.traverse();
parser.setCodec(jp.getCodec());
Vendor mapped = parser.readValueAs(Vendor.class);
return mapped;
}
It works faster :)
Recursively count files in directories in PowerShell 2.0
ls -rec | ? {$_.mode -match 'd'} | select FullName, @{N='Count';E={(ls $_.FullName | measure).Count}}
In my case, I needed to specify a viahost
and viauser
. Worth trying if you're in a complex system. :)
Just as a addition. You can find the Catalina Paths in
->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS
In the VM Arguments the Paths are listed and changeable
I finally solved the problem!!! You should first set the jre path to system variables by navigating to::
control panel > System and Security > System > Advanced system settings
Under System variables click on new
Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin
Where Variable value should be the path to your JDK's bin folder.
Then open command prompt and Change directory to the same JDK's bin folder like this
C:\Program Files (x86)\Java\jre1.8.0_171\bin
then paste,
keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
NOTE: People are confusing jre and jdk. All I did applied strictly to jre
long
can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float
the value before calling the long
. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int
to provide the key as well.
So, the answer is long(float('234.89'))
or it could just be int(float('234.89'))
if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int
aca definis los anchos
float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};
aca se los insertas a la tabla que tiene las columnas
table.setWidths(anchoDeColumnas);
I have an answer for you Yes, It is possible.
Go to
SQL Server Management Studio > select Database > click on attach
Then select and add .mdf and .ldf file. Click on OK.
Boost Preprocessor actually has this as of Boost 1.49, as BOOST_PP_VARIADIC_SIZE(...)
. It works up to size 64.
Under the hood, it's basically the same as Kornel Kisielewicz's answer.
The parameter(s) to isset()
must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:
if (isset($_POST['search_term'], $_POST['postcode'])) {
}
This will return true
only if all arguments to isset()
are set and do not contain null
.
Note that isset($var)
and isset($var) == true
have the same effect, so the latter is somewhat redundant.
Update
The second part of your expression uses empty()
like this:
empty ($_POST['search_term'] . $_POST['postcode']) == false
This is wrong for the same reasons as above. In fact, you don't need empty()
here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:
isset($_POST['search_term'], $_POST['postcode']) &&
$_POST['search_term'] &&
$_POST['postcode']
Or using an equivalent expression:
!empty($_POST['search_term']) && !empty($_POST['postcode'])
Final thoughts
You should consider using filter
functions to manage the inputs:
$data = filter_input_array(INPUT_POST, array(
'search_term' => array(
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_NULL_ON_FAILURE,
),
'postcode' => array(
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_NULL_ON_FAILURE,
),
));
if ($data === null || in_array(null, $data, true)) {
// some fields are missing or their values didn't pass the filter
die("You did something naughty");
}
// $data['search_term'] and $data['postcode'] contains the fields you want
Btw, you can customize your filters to check for various parts of the submitted values.
In C++ you are supposed to declare functions before you can use them. In your code integrate
is not declared before the point of the first call to integrate
. The same applies to sum
. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.
Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable
, getSkewNormal
, integrate
etc. have no business being in header file.
Also SkewNormalEvalutatable e();
declaration in C++ declares a function e
, not an object e
as you seem to assume. The simple SkewNormalEvalutatable e;
will declare an object initialized by default constructor.
Also, you receive the last parameter of integrate
(and of sum
) by value as an object of Evaluatable
type. That means that attempting to pass SkewNormalEvalutatable
as last argument of integrate
will result in SkewNormalEvalutatable
getting sliced to Evaluatable
. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.
The accepted answer is too long, other answers didn't work for me. I'm gonna leave this for future purpose.
Dim sKey, bFound
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\SecurityHealth"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
on error goto 0 ' restore error trapping
end with
If bFound Then
MsgBox = "Registry Key Exist."
Else
MsgBox = "Nope, it doesn't exist."
End If
Here's the list of the Registry Tree, choose your own base on your current task.
HKCR = HKEY_CLASSES_ROOT
HKCU = HKEY_CURRENT_USER
HKLM = HKEY_LOCAL_MACHINE
HKUS = HKEY_USERS
HKCC = HKEY_CURRENT_CONFIG
Given the use of List
, there's no way to "lookup" a value without iterating through it...
For example...
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.add(new Party("FirstParty")); // all anonymously added
cave.parties.add(new Party("SecondParty"));
cave.parties.add(new Party("ThirdParty"));
for (Party p : cave.parties) {
if (p.name.equals("SecondParty") {
p.index = ...;
break;
}
}
Now, this will take time. If the element you are looking for is at the end of the list, you will have to iterate to the end of the list before you find a match.
It might be better to use a Map
of some kind...
So, if we update Cave
to look like...
class Cave {
Map<String, Party> parties = new HashMap<String, Party>(25);
}
We could do something like...
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.put("FirstParty", new Party("FirstParty")); // all anonymously added
cave.parties.put("SecondParty", new Party("SecondParty"));
cave.parties.put("ThirdParty", new Party("ThirdParty"));
if (cave.parties.containsKey("SecondParty")) {
cave.parties.get("SecondParty").index = ...
}
Instead...
Ultimately, this will all depend on what it is you want to achieve...
When you use addEventListener
, this
will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this
from within your function:
productLineSelect.addEventListener('change',getSelection,false);
function getSelection(){
var value = sel.options[this.selectedIndex].value;
alert(value);
}
If you want to pass in some other argument from the context where you call addEventListener
, you can use a closure, like this:
productLineSelect.addEventListener('change', function(){
// pass in `this` (the element), and someOtherVar
getSelection(this, someOtherVar);
},false);
function getSelection(sel, someOtherVar){
var value = sel.options[sel.selectedIndex].value;
alert(value);
alert(someOtherVar);
}
The code returns the nth occurrence positions substring aka field width. Example. if string "Stack overflow in low melow" is the string to search 2nd occurance of token "low", you will agree with me that it 2nd occurance is at subtring "18 and 21". indexOfOccurance("Stack overflow in low melow", low, 2) returns 18 and 21 in a string.
class Example{
public Example(){
}
public String indexOfOccurance(String string, String token, int nthOccurance) {
int lengthOfToken = token.length();
int nthCount = 0;
for (int shift = 0,count = 0; count < string.length() - token.length() + 2; count++, shift++, lengthOfToken++)
if (string.substring(shift, lengthOfToken).equalsIgnoreCase(token)) {
// keeps count of nthOccurance
nthCount++;
if (nthCount == nthOccurance){
//checks if nthCount == nthOccurance. If true, then breaks
return String.valueOf(shift)+ " " +String.valueOf(lengthOfToken);
}
}
return "-1";
}
public static void main(String args[]){
Example example = new Example();
String string = "the man, the woman and the child";
int nthPositionOfThe = 3;
System.out.println("3rd Occurance of the is at " + example.indexOfOccurance(string, "the", nthPositionOfThe));
}
}
host or hostname would be the i.p address of the remote server, or if you can access it over the network by computer name, that should work to.
All answers are quite old. Since the beginning of 2013 Mongoose started to support promises gradually for all queries, so that would be the recommended way of structuring several async calls in the required order going forward I guess.
You will find a folder named "Oracle" on ProgramData folder in your windows installed drive. Remove the folder. Hope it will work. In my case my install drive is C and my path is C:\ProgramData\Oracle
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
Presumably you're passing the arguments in on the command line as follows:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
... and then accessing them in the script thusly:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:
Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2
... and access:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
Another option - to convert to C++ besides Shed Skin - is Pythran.
To quote High Performance Python by Micha Gorelick and Ian Ozsvald:
Pythran is a Python-to-C++ compiler for a subset of Python that includes partial
numpy
support. It acts a little like Numba and Cython—you annotate a function’s arguments, and then it takes over with further type annotation and code specialization. It takes advantage of vectorization possibilities and of OpenMP-based parallelization possibilities. It runs using Python 2.7 only.One very interesting feature of Pythran is that it will attempt to automatically spot parallelization opportunities (e.g., if you’re using a
map
), and turn this into parallel code without requiring extra effort from you. You can also specify parallel sections usingpragma omp
> directives; in this respect, it feels very similar to Cython’s OpenMP support.Behind the scenes, Pythran will take both normal Python and numpy code and attempt to aggressively compile them into very fast C++—even faster than the results of Cython.
You should note that this project is young, and you may encounter bugs; you should also note that the development team are very friendly and tend to fix bugs in a matter of hours.
To add:
$arr["key"] = "value";
Then simply return $arr
Can't return directly like this way return $arr["key"] = "value";
I got a does not exist error
Here is how I make it works
adb shell pm list packages -f | findstr zalo
package:/data/app/com.zing.zalo-1/base.apk=com.zing.zalo
adb shell
mido:/ $ cp /data/app/com.zing.zalo-1/base.apk /sdcard/zalo.apk
mido:/ $ exit
adb pull /sdcard/zalo.apk Desktop
/sdcard/zalo.apk: 1 file pulled. 7.7 MB/s (41895394 bytes in 5.200s)
I can offer only an example of the layout solution already pointed out.
layout(matrix(c(1,2), nrow = 1), widths = c(0.7, 0.3))
par(mar = c(5, 4, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
par(mar = c(5, 0, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, ylim=c(-2,2), type = "n", axes = FALSE, ann = FALSE)
legend(1, 1, c("group A", "group B"), pch = c(1,2), lty = c(1,2))
Most answers here suggest to use the req.headers.host header.
The Host header is required by HTTP 1.1, but it is actually optional since the header might not be actually sent by a HTTP client, and node/express will accept this request.
You might ask: which HTTP client (e.g: browser) can send a request missing that header? The HTTP protocol is very trivial. You can craft a HTTP request in few lines of code, to not send a host header, and if each time you receive a malformed request you throw an exception, and depending on how you handle such exceptions, this can take your server down.
So always validate all input. This is not paranoia, I have received requests lacking the host header in my service.
Also, never treat URLs as strings. Use the node url module to modify specific parts of a string. Treating URLs as strings can be exploited in many many many ways. Don't do it.
I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)
private void populateInCurrentScreen()
{
(this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
this.Bindings.Update();
}
Try doing SHIFT + G
and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G
I was playing around with C# code an I accidentally found the solution to your problem haha
This is the code for the Principal view:
`@model dynamic
@Html.Partial("_Partial", Model as IDictionary<string, object>)`
Then in the Partial view:
`@model dynamic
@if (Model != null) {
foreach (var item in Model)
{
<div>@item.text</div>
}
}`
It worked for me, I hope this will help you too!!
None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01
Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.
then rounding to ensure we do not have more than 2 d.p.
Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
6.665m.ToString() -> "6.67"
6.6m.ToString() -> "6.60"
Circle Time! :) Easy way of making a circle with a hollow center : use border-radius, give the element a border and no background so you can see through it :
div {_x000D_
display: inline-block;_x000D_
margin-left: 5px;_x000D_
height: 100px;_x000D_
border-radius: 100%;_x000D_
width:100px;_x000D_
border:solid black 2px;_x000D_
}_x000D_
_x000D_
body{_x000D_
background:url('http://lorempixel.com/output/people-q-c-640-480-1.jpg');_x000D_
background-size:cover;_x000D_
}
_x000D_
<div></div>
_x000D_
Alright, here's the best solution I've found that meets all the requirements:
No need for mouse interaction whatsoever.
GC.Collect()
from MDSN,
Use this method to try to reclaim all memory that is inaccessible.
All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.
Try This
<EditText
android:id="@+id/EditText1"
android:text=""
android:inputType="text|textNoSuggestions"
android:textSize="18sp"
android:layout_width="80dp"
android:layout_height="43dp">
</EditText>
Other inputType can be found Here ..
Starting from the above answer I modified a little bit the code to make the helper work with CSS files too and add a version every time when you do some change in the files and not only when you do the build
public static class HtmlHelperExtensions
{
public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename)
{
string version = GetVersion(helper, filename);
return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");
}
public static MvcHtmlString IncludeVersionedCss(this HtmlHelper helper, string filename)
{
string version = GetVersion(helper, filename);
return MvcHtmlString.Create("<link href='" + filename + version + "' type ='text/css' rel='stylesheet'/>");
}
private static string GetVersion(this HtmlHelper helper, string filename)
{
var context = helper.ViewContext.RequestContext.HttpContext;
var physicalPath = context.Server.MapPath(filename);
var version = "?v=" +
new System.IO.FileInfo(physicalPath).LastWriteTime
.ToString("yyyyMMddHHmmss");
context.Cache.Add(physicalPath, version, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero,
CacheItemPriority.Normal, null);
if (context.Cache[filename] == null)
{
context.Cache[filename] = version;
return version;
}
else
{
if (version != context.Cache[filename].ToString())
{
context.Cache[filename] = version;
return version;
}
return context.Cache[filename] as string;
}
}
}
If you want to just untrack a file and not delete from local and remote repo then use this command:
git update-index --assume-unchanged file_name_with_path
Alternatively there's the application called LiveReload...
Illegal State Exception is an Unchecked exception.
It indicate that method has been invoked at wrong time.
example:
Thread t = new Thread();
t.start();
//
//
t.start();
output:
Runtime Excpetion: IllegalThreadStateException
We cant start the Thread again, it will throw IllegalStateException.
Java 8 introduces the Instant.ofEpochSecond
utility method for creating an Instant
from a Unix timestamp, this can then be converted into a ZonedDateTime
and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
The "IIS APPPOOL\AppPoolName" will work, but as mentioned previously, it does not appear to be a valid AD name so when you search for it in the "Select User or Group" dialog box, it won't show up (actually, it will find it, but it will think its an actual system account, and it will try to treat it as such...which won't work, and will give you the error message about it not being found).
How I've gotten it to work is:
As long as the AppPool name actually exists, the login should now be created.
Scenario X:
Table:Spitter (One) ,Table: Spittles (Many) (Spittles is Owner of the relationship with a FK:spitter_id)
This scenario results in saving : The Spitter and both Spittles as if owned by Same Spitter.
Spitter spitter=new Spitter();
Spittle spittle3=new Spittle();
spitter.setUsername("George");
spitter.setPassword("test1234");
spittle3.setSpittle("I love java 2");
spittle3.setSpitter(spitter);
dao.addSpittle(spittle3); // <--persist
Spittle spittle=new Spittle();
spittle.setSpittle("I love java");
spittle.setSpitter(spitter);
dao.saveSpittle(spittle); //<-- merge!!
Scenario Y:
This will save the Spitter, will save the 2 Spittles But they will not reference the same Spitter!
Spitter spitter=new Spitter();
Spittle spittle3=new Spittle();
spitter.setUsername("George");
spitter.setPassword("test1234");
spittle3.setSpittle("I love java 2");
spittle3.setSpitter(spitter);
dao.save(spittle3); // <--merge!!
Spittle spittle=new Spittle();
spittle.setSpittle("I love java");
spittle.setSpitter(spitter);
dao.saveSpittle(spittle); //<-- merge!!
Reference taken from this blog:
Below is a list of hashing algorithm along with its require bit size:
Created one sample table with require CHAR(n):
CREATE TABLE tbl_PasswordDataType
(
ID INTEGER
,MD5_128_bit CHAR(32)
,SHA_160_bit CHAR(40)
,SHA_224_bit CHAR(56)
,SHA_256_bit CHAR(64)
,SHA_384_bit CHAR(96)
,SHA_512_bit CHAR(128)
);
INSERT INTO tbl_PasswordDataType
VALUES
(
1
,MD5('SamplePass_WithAddedSalt')
,SHA1('SamplePass_WithAddedSalt')
,SHA2('SamplePass_WithAddedSalt',224)
,SHA2('SamplePass_WithAddedSalt',256)
,SHA2('SamplePass_WithAddedSalt',384)
,SHA2('SamplePass_WithAddedSalt',512)
);
You can get the projection from the MapView object which is passed into the draw() method: mapv.getProjection().toPixels(gP1, p1);
If you use androidx.appcompat:appcompat and want a custom drawable (of type selector
with android:state_checked
) to work on old platform versions in addition to new platform versions, you need to use
<CheckBox
app:buttonCompat="@drawable/..."
instead of
<CheckBox
android:button="@drawable/..."
In my case, the server list was empty for Apache in "Run Configurations" when I opened
I fixed this by creating a server in the Servers Panel as in other answers:
This worked for me: :)
<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
alert('PlanId:' + planId + ' ParticipantId:' + participantId);
}
My alternative solution with subtraction :)
void convert( unsigned int addr )
{
unsigned int num[OCTET],
next_addr[OCTET];
int bits = 8;
unsigned int shift_bits;
int i;
next_addr[0] = addr;
shift_bits -= bits;
num[0] = next_addr[0] >> shift_bits;
for ( i = 0; i < OCTET-1; i ++ )
{
next_addr[i + 1] = next_addr[i] - ( num[i] << shift_bits ); // next subaddr
shift_bits -= bits; // next shift
num[i + 1] = next_addr[i + 1] >> shift_bits; // octet
}
printf( "%d.%d.%d.%d\n", num[0], num[1], num[2], num[3] );
}
No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.
If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.
A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.
Store the lines in some type of list. When it comes time to paint them, iterate the list and draw each one. Like this:
Screenshot
DrawLines
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.geom.Line2D;
import javax.swing.JOptionPane;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import java.util.ArrayList;
import java.util.Random;
class DrawLines {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
LineComponent lineComponent = new LineComponent(400,400);
for (int ii=0; ii<30; ii++) {
lineComponent.addLine();
}
JOptionPane.showMessageDialog(null, lineComponent);
}
};
SwingUtilities.invokeLater(r);
}
}
class LineComponent extends JComponent {
ArrayList<Line2D.Double> lines;
Random random;
LineComponent(int width, int height) {
super();
setPreferredSize(new Dimension(width,height));
lines = new ArrayList<Line2D.Double>();
random = new Random();
}
public void addLine() {
int width = (int)getPreferredSize().getWidth();
int height = (int)getPreferredSize().getHeight();
Line2D.Double line = new Line2D.Double(
random.nextInt(width),
random.nextInt(height),
random.nextInt(width),
random.nextInt(height)
);
lines.add(line);
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
Dimension d = getPreferredSize();
g.setColor(Color.black);
for (Line2D.Double line : lines) {
g.drawLine(
(int)line.getX1(),
(int)line.getY1(),
(int)line.getX2(),
(int)line.getY2()
);
}
}
}
getCurrentActivity() is also in ReactContextBaseJavaModule.
(Since the this question was initially asked, many Android app also has ReactNative component - hybrid app.)
class ReactContext in ReactNative has the whole set of logic to maintain mCurrentActivity which is returned in getCurrentActivity().
Note: I wish getCurrentActivity() is implemented in Android Application class.
Old thread, but i wanted to update since i worked on this problem today, i didnt have jquery in my project so i did it the plain old javascript way, i also needed to block the content on the screen so in my xhtml
<img id="loading" src="#{request.contextPath}/images/spinner.gif" style="display: none;"/>
in my javascript
document.getElementsByClassName('myclass').style.opacity = '0.7'
document.getElementById('loading').style.display = "block";
I suppose https://get-ytt.io/ would be an acceptable solution to your problem
This is old, but someone else may stumble on it as I did. When you connect to the DataCast, you are talking to a daemon that can access the database. It was intended that a customer would write some code to access the database and store the results somewhere. It just happens that telnet works to access data manually. netcat should also work. ssh obviously will not.
It actually requires inclusion of Twitter Bootstrap's dropdown.js
PLease make sure to backup your changes before running these commmand in a separate folder
git checkout branch_name
Checkout on your branch
git merge --abort
Abort the merge
git status
Check status of the code after aborting the merge
git reset --hard origin/branch_name
these command will reset your changes and align your code with the branch_name (branch) code.
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
I prefer option two because it clearly shows the list item as the possessor of that nested list. I would always lean towards semantically sound HTML.
Better solution for your Stack implementation
import java.util.List;
import java.util.ArrayList;
public class IntegerStack
{
private List<Integer> stack;
public IntegerStack(int SIZE)
{
stack = new ArrayList<Integer>(SIZE);
}
public void push(int i)
{
stack.add(0,i);
}
public int pop()
{
if(!stack.isEmpty()){
int i= stack.get(0);
stack.remove(0);
return i;
} else{
return -1;// Or any invalid value
}
}
public int peek()
{
if(!stack.isEmpty()){
return stack.get(0);
} else{
return -1;// Or any invalid value
}
}
public boolean isEmpty()
{
stack.isEmpty();
}
}
If you have to use Array... Here are problems in your code and possible solutions
import java.util.Arrays;
public class IntegerStack
{
private int stack [];
private int top;
public IntegerStack(int SIZE)
{
stack = new int [SIZE];
top = -1; // top should be 0. If you keep it as -1, problems will arise when SIZE is passed as 0.
// In your push method -1==0 will be false and your code will try to add the invalid element to Stack ..
/**Solution top=0; */
}
public void push(int i)
{
if (top == stack.length)
{
extendStack();
}
stack[top]= i;
top++;
}
public int pop()
{
top --; // here you are reducing the top before giving the Object back
/*Solution
if(!isEmpty()){
int value = stack[top];
top --;
return value;
} else{
return -1;// OR invalid value
}
*/
return stack[top];
}
public int peek()
{
return stack[top]; // Problem when stack is empty or size is 0
/*Solution
if(!isEmpty()){
return stack[top];
}else{
return -1;// Or any invalid value
}
*/
}
public boolean isEmpty()
{
if ( top == -1); // problem... we changed top to 0 above so here it need to check if its 0 and there should be no semicolon after the if statement
/* Solution if(top==0) */
{
return true;
}
}
private void extendStack()
{
int [] copy = Arrays.copyOf(stack, stack.length); // The second parameter in Arrays.copyOf has no changes, so there will be no change in array length.
/*Solution
stack=Arrays.copyOf(stack, stack.length+1);
*/
}
}
<span style="text-align:center; display:block;">
<a href="http://news.awaissoft.com">Awaissoft</a>
</span>
<style>
#aspectRatio
{
position:fixed;
left:0px;
top:0px;
width:60vw;
height:40vw;
border:1px solid;
font-size:10vw;
}
</style>
<body>
<div id="aspectRatio">Aspect Ratio?</div>
</body>
The key thing to note here is vw
= viewport width, and vh
= viewport height
Darian Moody has a nice solution to this challenge in his blog post:
a = 1
b = 2
c = True
rules = [a == 1,
b == 2,
c == True]
if all(rules):
print("Success!")
The all() method returns True
when all elements in the given iterable are true. If not, it returns False
.
You can read a little more about it in the python docs here and more information and examples here.
(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)
HashMap is a class used to store the element in key and value format.it is not thread safe. because it is not synchronized .where as Hashtable is synchronized.Hashmap permits null but hastable doesn't permit null.
The background color property is ignored on a UINavigationBar
, so if you want to adjust the look and feel you either have to use the tintColor
or call some of the other methods listed under "Customizing the Bar Appearance" of the UINavigationBar class reference (like setBackgroundImage:forBarMetrics:
).
Be aware that the tintColor
property works differently in iOS 7, so if you want a consistent look between iOS 7 and prior version using a background image might be your best bet. It's also worth mentioning that you can't configure the background image in the Storyboard, you'll have to create an IBOutlet
to your UINavigationBar
and change it in viewDidLoad
or some other appropriate place.
I had the same issue even when hardware acceleration installed. My solutions was uninstalling and reinstalling it using SDK Manager. Make sure you restart the Android studio after then.
To understand those phrases let's look at the couple of things:
typedef double Foo;
void fooFunc(Foo &_bar){ ... }
So that's passing a double by reference.
typedef double* Foo;
void fooFunc(Foo &_bar){ ... }
now it's passing a pointer to a double by reference.
typedef double** Foo;
void fooFunc(Foo &_bar){ ... }
Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.
If git gc --prune=now
dosen't help you. (bad luck like me)
What I did is remove the project in local, and re clone the whole project again.
$( "#dialogueForm" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
my: "center",
at: "center",
of: window,
close : function(){
// functionality goes here
}
});
"close" property of dialog gives the close event for the same.
0
and 7
both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.
Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON
, THU
, etc:
0 - Sun Sunday
1 - Mon Monday
2 - Tue Tuesday
3 - Wed Wednesday
4 - Thu Thursday
5 - Fri Friday
6 - Sat Saturday
7 - Sun Sunday
Graphically:
+---------- minute (0 - 59)
¦ +-------- hour (0 - 23)
¦ ¦ +------ day of month (1 - 31)
¦ ¦ ¦ +---- month (1 - 12)
¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
¦ ¦ ¦ ¦ ¦ 1 - 7 => Monday - Sunday)
? ? ? ? ?
* * * * * command to be executed
Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU
will exectute the command only on sundays, mondays on thursdays.
You can read further details in Wikipedia's article about Cron.
Call myTextInputLayout.setError()
instead of myEditText.setError()
.
These container and containment have double functionality on setting errors. Functionality you need is container's one. But you could require minimal version of 23 for that.
Just make regular link look like button :)
<a href="#" role="button" class="btn btn-success btn-large">Click here!</a>
"role" inside a href code makes it look like button, ofc you can add more variables such as class.
Using color function to print text with colors
Code:
enum Color {
RED("\033[0;31m"), // RED
GREEN("\033[0;32m"), // GREEN
YELLOW("\033[0;33m"), // YELLOW
BLUE("\033[0;34m"), // BLUE
MAGENTA("\033[0;35m"), // MAGENTA
CYAN("\033[0;36m"), // CYAN
private final String code
Color(String code) {
this.code = code;
}
@Override
String toString() {
return code
}
}
def color = { color, txt ->
def RESET_COLOR = "\033[0m"
return "${color}${txt}${RESET_COLOR}"
}
Usage:
test {
println color(Color.CYAN, 'testing')
}
I noticed that this error happens when I send an IQueriable to the view and use it in a double foreach, where the inner foreach also needs to use the connection. Simple example (ViewBag.parents can be IQueriable or DbSet):
foreach (var parent in ViewBag.parents)
{
foreach (var child in parent.childs)
{
}
}
The simple solution is to use .ToList()
on the collection before using it. Also note that MARS does not work with MySQL.
Generate QR Code Image in ASP.NET Using Google Chart API
Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.
var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
WebResponse response = default(WebResponse);
Stream remoteStream = default(Stream);
StreamReader readStream = default(StreamReader);
WebRequest request = WebRequest.Create(url);
response = request.GetResponse();
remoteStream = response.GetResponseStream();
readStream = new StreamReader(remoteStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
img.Save("D:/QRCode/" + txtCode.Text + ".png");
response.Close();
remoteStream.Close();
readStream.Close();
txtCode.Text = string.Empty;
txtWidth.Text = string.Empty;
txtHeight.Text = string.Empty;
lblMsg.Text = "The QR Code generated successfully";
Click here for complete source code to download
Demo of application for free QR Code generator using C#
echo %Date:~7,2% gets current day
7 is starting position 2 number of digits to display
echo %Date:~7,2% gets current day
echo %Date:~4,2% gets current month
echo %Date:~10,4% gets current year
I found that "phpseclib" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/
To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);
This might be your script-free solution: http://davidwalsh.name/css-transform-rotate
It's supported in all browsers prefixed and, in IE10-11 and all still-used Firefox versions, unprefixed.
That means that if you don't care for old IEs (the bane of web designers) you can skip the -ms-
and -moz-
prefixes to economize space.
However, the Webkit browsers (Chrome, Safari, most mobile navigators) still need -webkit-
, and there's a still-big cult following of pre-Next Opera and using -o-
is sensate.
If you have something that's O(f(n)) that means there's are k, g(n) such that f(n) ≤ k g(n).
If you have something that's Ω(f(n)) that means there's are k, g(n) such that f(n) ≥ k g(n).
And if you have a something with O(f(n)) and Ω(f(n)), then it's Θ(f(n).
The Wikipedia article is decent, if a little dense.
Yes you need to use a System.out.println
. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.
Try:
for (int i = 0 ; i < array.length; i++ ) {
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
int length = i;
// get biggest number
int large = getMaxValue(array, length);
// get smallest number
int small = getMinValue(array, length);
// actually print
System.out.println( "Max: " + large + " Min: " + small );
Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.
I use android studio in Windows 7 and i have AVG for antivirus. The first time you launch adb, AVG prompts you to add avg.exe in antivirus vault. If you accept, then you android studio dont have access to run adb.exe. So open avg >> options >> Virus Vault >> Restore (select the adb file)
Swift 4:
// add 5 minutes to date
let date = startDate.addingTimeInterval(TimeInterval(5.0 * 60.0))
// subtract 5 minutes from date
let date = startDate.addingTimeInterval(TimeInterval(-5.0 * 60.0))
Swift 5.1:
// subtract 5 minutes from date
transportationFromDate.addTimeInterval(TimeInterval(-5.0 * 60.0))
Here's a DateTime extender that adds the age calculation to the DateTime object.
public static class AgeExtender
{
public static int GetAge(this DateTime dt)
{
int d = int.Parse(dt.ToString("yyyyMMdd"));
int t = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
return (t-d)/10000;
}
}
A solution is to add captures for the preceding and following text:
str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")
Simply
$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
echo "BB is not found";
}
Bluetooth devices can operate in both classic and LE mode at the same time. Sometimes they use a different MAC address depending on which way you are connecting. Calling socket.connect()
is using Bluetooth Classic, so you have to make sure the device you got when you scanned was really a classic device.
It's easy to filter for only Classic devices, however:
if(BluetoothDevice.DEVICE_TYPE_LE == device.getType()){
//socket.connect()
}
Without this check, it's a race condition as to whether a hybrid scan will give you the Classic device or the BLE device first. It may appear as intermittent inability to connect, or as certain devices being able to connect reliably while others seemingly never can.
public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;
public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}
public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}
Persistance
public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_CreateEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);
try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
Repository
Task<ResponseStatusViewModel> Create(EmployeeModel Employee);
public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}
private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}
I have similar problem. In my case requests to localhost was working and suddenly stopped. It turn out that the problem was that I was turn off my wifi on my android phone.
This query will return details about foreign keys in a table, it supports multiple column keys.
SELECT *
FROM
(
SELECT
T1.constraint_name ConstraintName,
T2.COLUMN_NAME ColumnName,
T3.TABLE_NAME RefTableName,
T3.COLUMN_NAME RefColumnName,
T1.MATCH_OPTION MatchOption,
T1.UPDATE_RULE UpdateRule,
T1.DELETE_RULE DeleteRule
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS T1
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2
ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T3
ON T1.UNIQUE_CONSTRAINT_NAME = T3.CONSTRAINT_NAME
AND T2.ORDINAL_POSITION = T3.ORDINAL_POSITION) A
WHERE A.ConstraintName = 'table_name'
I tested as below. Hope it helps.
Integer[] integers1 = new Integer[10];
System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
for (Integer integer : integers1) {
System.out.println(integer); //prints all 0s
}
//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
// integers1[2] = 0;
for (Integer integer : integers1) {
System.out.println(integer); //Still it prints all 0s but it is not empty
//but that manually added 0 is different
}
//Even we manually add 0, still we need to treat it as null. This is semantic logic.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:
INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'
In the above query, there are 2 extra columns named email & current_time.
I created a module to make dealing with trusted hosts slightly easier, psTrustedHosts. You can find the repo here on GitHub. It provides four functions that make working with trusted hosts easy: Add-TrustedHost
, Clear-TrustedHost
, Get-TrustedHost
, and Remove-TrustedHost
. You can install the module from PowerShell Gallery with the following command:
Install-Module psTrustedHosts -Force
In your example, if you wanted to append hosts 'machineC' and 'machineD' you would simply use the following command:
Add-TrustedHost 'machineC','machineD'
To be clear, this adds hosts 'machineC' and 'machineD' to any hosts that already exist, it does not overwrite existing hosts.
The Add-TrustedHost
command supports pipeline processing as well (so does the Remove-TrustedHost
command) so you could also do the following:
'machineC','machineD' | Add-TrustedHost
Considering, you have epoch_time
available,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format