You should try very usefull procedure sp_whoIsActive
which can be found here: http://whoisactive.com and it is free.
re.escape
doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.
When using the repl, try using print
to see what is really in the string.
$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\\w\$arr=1")
'\\\\\\^stack\\\\\\.\\\\\\*\\/overflo\\\\w\\\\\\$arr\\=1'
>>> print re.escape("\^stack\.\*/overflo\\w\$arr=1")
\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1
>>>
Try this
$('#add_here').text('new-dynamic-text');
After all alternatives, I found:
sudo -S <cmd>
The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device.
Above command still needs password to be entered. To remove entering password manually, in cases like jenkins, this command works:
echo <password> | sudo -S <cmd>
You could use the Enterprise Security API (ESAPI) library, which provides methods like encodeForXML
and encodeForXMLAttribute
. Take a look at the documentation of the Encoder interface; it also contains examples of how to create an instance of DefaultEncoder.
html, body {
height: 100%;
width: 100%;
}
html {
display: table;
margin: auto;
}
body {
padding-top: 50px;
display: table-cell;
}
div {
margin: auto;
}
This will center align objects and then also center align the items within them to center align multiple objects with different widths.
Do this in jQuery. The below code works well even if you columns generated automatically or not sure about the column number.
var table = $('#tbl').DataTable({
"columnDefs": [{ targets: 'no-sort', orderable: false }]});
and add a class 'no-sort' to whatever headers you want to disable sort like this..
<th class="no-sort">Header n</th>
Open standard terminal ctrl+p and paste this command
npm i script-runner
Need to see this logs npm should be run outside of the node repl, in your normal shell. (Press Control-D to exit.)
(To exit, press ^C again or type .exit)
C:\DW\Examples\Ang.Crud>npm i script-runner npm WARN saveError ENOENT: no such file or directory, open 'C:\DW\Examples\Ang.Crud\package.json' npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN enoent ENOENT: no such file or directory, open 'C:\DW\Examples\Ang.Crud\package.json' npm WARN Ang.Crud No description npm WARN Ang.Crud No repository field. npm WARN Ang.Crud No README data npm WARN Ang.Crud No license field.
- [email protected] added 7 packages from 5 contributors and audited 7 packages in 2.955s found 0 vulnerabilities
Usage: npm
where is one of: access, adduser, audit, bin, bugs, c, cache, ci, cit, completion, config, create, ddp, dedupe, deprecate, dist-tag, docs, doctor, edit, explore, get, help, help-search, hook, i, init, install, install-test, it, link, list, ln, login, logout, ls, outdated, owner, pack, ping, prefix, profile, prune, publish, rb, rebuild, repo, restart, root, run, run-script, s, se, search, set, shrinkwrap, star, stars, start, stop, t, team, test, token, tst, un, uninstall, unpublish, unstar, up, update, v, version, view, whoami
npm -h quick help on npm -l display full usage info npm help search for help on npm help npm involved overview
Specify configs in the ini-formatted file: C:\Users\fdc.npmrc or on the command line via: npm --key value Config info can be viewed via: npm help config
[email protected] C:\Program Files\nodejs\node_modules\npm
In Notepad++
View --->Show Symbols --->Show White Spaces and Tabs(select)
replace all tabs with spaces.
I love jQuery's method chaining. Simply do...
var value = $("#text").val().replace('.',':');
//Or if you want to return the value:
return $("#text").val().replace('.',':');
This should work if current file is located in same directory where initcontrols is:
<?php
$ds = DIRECTORY_SEPARATOR;
$base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds;
require_once("{$base_dir}initcontrols{$ds}config.php");
?>
<div>
<?php
$file = "{$base_dir}initcontrols{$ds}header_myworks.php";
include_once($file);
echo $plHeader;?>
</div>
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
If you actually want to send data to a php script for example you can do this:
The php:
<?php
$a = $_REQUEST['a'];
$b = $_REQUEST['b']; //totally sanitized
echo $a + $b;
?>
Js (using jquery):
$.post("/path/to/above.php", {a: something, b: something}, function(data){
$('#somediv').html(data);
});
You can load both json strings into Python Dictionaries and then combine. This will only work if there are unique keys in each json string.
import json
a = json.loads(jsonStringA)
b = json.loads(jsonStringB)
c = dict(a.items() + b.items())
# or c = dict(a, **b)
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
use further as
rs.getString(1);
rs.getInt(2);
1, 2 is the column number of table and set int or string as per data-type of coloumn
An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.
Use this code it works perfectly for odd or even list sizes. Hope it help somebody .
int listSize = listOfArtist.size();
int mid = 0;
if (listSize % 2 == 0) {
mid = listSize / 2;
Log.e("Parting", "You entered an even number. mid " + mid
+ " size is " + listSize);
} else {
mid = (listSize + 1) / 2;
Log.e("Parting", "You entered an odd number. mid " + mid
+ " size is " + listSize);
}
//sublist returns List convert it into arraylist * very important
leftArray = new ArrayList<ArtistModel>(listOfArtist.subList(0, mid));
rightArray = new ArrayList<ArtistModel>(listOfArtist.subList(mid,
listSize));
Add this to the scope - https://www.googleapis.com/auth/userinfo.profile
And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json
It has loads of stuff - including name, public profile url, gender, photo etc.
In case anyone still looking for a solution. This worked for me.
Python adds the folder containing the script you launch to the PYTHONPATH, so if you run
python application/app2/some_folder/some_file.py
Only the folder application/app2/some_folder is added to the path (not the base dir that you're executing the command in). Instead, run your file as a module and add a __init__.py in your some_folder directory.
python -m application.app2.some_folder.some_file
This will add the base dir to the python path, and then classes will be accessible via a non-relative import.
If you have R, you can use:
> ... | Rscript -e 'print(sum(scan("stdin")));'
Read 4 items
[1] 2232320
Since I'm comfortable with R, I actually have several aliases for things like this so I can use them in bash
without having to remember this syntax. For instance:
alias Rsum=$'Rscript -e \'print(sum(scan("stdin")));\''
which let's me do
> ... | Rsum
Read 4 items
[1] 2232320
Inspiration: Is there a way to get the min, max, median, and average of a list of numbers in a single command?
Your error indicates that the operation is being cancelled for some reason. I'd need more details to understand why. But I think the bigger issue may be that since your endpoint https://host.com/a/path
is bogus, there is no real server response to report, and hence you're seeing nil
.
If you hit up a valid endpoint that serves up a proper response, you should see a non-nil value for res
(using the techniques Sam mentions) in the form of a NSURLHTTPResponse
object with properties like statusCode
, etc.
Also, just to be clear, error
is of type NSError
. It tells you why the network request failed. The status code of the failure on the server side is actually a part of the response.
Hope that helps answer your main question.
This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.
Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011
. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.
When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY
, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.
Whether that is the problem or not, you should always specify the date model:
UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');
Since you aren't specifying a time component - all Oracle DATE
columns include a time, even if it's midnight - you could also use a date literal:
UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';
You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.
You can achieve this by using ArgumentCaptor
Imagine you have bean function like so.
public interface Application {
public String myFunction(String abc);
}
Then in your test class:
//Use ArgumentCaptor to capture the value
ArgumentCaptor<String> param = ArgumentCaptor.forClass(String.class);
when(mock.myFunction(param.capture())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return param.getValue();//return the captured value.
}
});
OR if you fan of lambda simply do:
//Use ArgumentCaptor to capture the value
ArgumentCaptor<String> param = ArgumentCaptor.forClass(String.class);
when(mock.myFunction(param.capture()))
.thenAnswer((invocation) -> param.getValue());
Summary: Use argumentcaptor, to capture the parameter passed. Later in answer return the value captured using getValue.
You can't style a pseudo-class on a particular element alone, in the same way that you can't have a pseudo-class in an inline style="..." attribute (as there is no selector).
You can do it by altering the stylesheet, for example by adding the rule:
#elid:hover { background: red; }
assuming each element you want to affect has a unique ID to allow it to be selected.
In theory the document you want is http://www.w3.org/TR/DOM-Level-2-Style/Overview.html which means you can (given a pre-existing embedded or linked stylesheet) using syntax like:
document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';
IE, of course, requires its own syntax:
document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
document.styleSheets[0].rules[0].style.backgroundColor= 'red';
Older and minor browsers are likely not to support either syntax. Dynamic stylesheet-fiddling is rarely done because it's quite annoying to get right, rarely needed, and historically troublesome.
way 1 :
Let we have java file test.java which contains main class testa now first we compile our java file simply as javac test.java we create file manifest.txt in same directory and we write Main-Class: mainclassname . e.g :
Main-Class: testa
then we create jar file by this command :
jar cvfm anyname.jar manifest.txt testa.class
then we run jar file by this command : java -jar anyname.jar
way 2 :
Let we have one package named one and every class are inside it. then we create jar file by this command :
jar cf anyname.jar one
then we open manifest.txt inside directory META-INF in anyname.jar file and write
Main-Class: one.mainclassname
in third line., then we run jar file by this command :
java -jar anyname.jar
to make jar file having more than one class file : jar cf anyname.jar one.class two.class three.class......
Just a note about difference beetween static and dynamic.
You can auto generate Image map from this website for selected area of image. https://www.image-map.net/
Easiest way to execute!
One notable reason to avoid overusing the heap is for performance -- specifically involving the performance of the default memory management mechanism used by C++. While allocation can be quite quick in the trivial case, doing a lot of new
and delete
on objects of non-uniform size without strict order leads not only to memory fragmentation, but it also complicates the allocation algorithm and can absolutely destroy performance in certain cases.
That's the problem that memory pools where created to solve, allowing to to mitigate the inherent disadvantages of traditional heap implementations, while still allowing you to use the heap as necessary.
Better still, though, to avoid the problem altogether. If you can put it on the stack, then do so.
In pom.xml file of the project,
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>X.X.X.RELEASE</version>
<relativePath> ../PROJECTNAME/pom.xml</relativePath>
</parent>
Pointing relativepath to the same MAVEN project POM file solved the issue for me.
The Jenkins admin console can run, even with the Master node offline. This can happen when Jenkins runs out of disk space.
To confirm, do the following (with thanks to geekride - jenkins-pending-waiting-for-next-available-executor):
The by far the simplest approach is:
yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)
one line solution for kotlin:
fun readFileText(fileName: String): String {
return assets.open(fileName).bufferedReader().use { it.readText() }
}
Also you can use it as extension function everyWhere
fun Context.readTextFromAsset(fileName : String) : String{
return assets.open(fileName).bufferedReader().use {
it.readText()}
}
Simply call in any context Class
context.readTextFromAsset("my file name")
**podria ser algo asi en react y electron**
xslToJson = workbook => {
//var data = [];
var sheet_name_list = workbook.SheetNames[0];
return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
raw: false,
dateNF: "DD-MMM-YYYY",
header:1,
defval: ""
});
};
handleFile = (file /*:File*/) => {
/* Boilerplate to set up FileReader */
const reader = new FileReader();
const rABS = !!reader.readAsBinaryString;
reader.onload = e => {
/* Parse data */
const bstr = e.target.result;
const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
/* Get first worksheet */
let arr = this.xslToJson(wb);
console.log("arr ", arr)
var dataNueva = []
arr.forEach(data => {
console.log("data renaes ", data)
})
// this.setState({ DataEESSsend: dataNueva })
console.log("dataNueva ", dataNueva)
};
if (rABS) reader.readAsBinaryString(file);
else reader.readAsArrayBuffer(file);
};
handleChange = e => {
const files = e.target.files;
if (files && files[0]) {
this.handleFile(files[0]);
}
};
Like Eric, I used homebrew, but I used the default recipe. So:
brew install mercurial
brew install vim
And after restarting the terminal homebrew's vim should be the default. If not, you should update your $PATH
so that /usr/local/bin
is before /usr/bin
. E.g. add the following to your .profile
:
export PATH=/usr/local/bin:$PATH
The solution is to install a browser plugin.
A web site which issues HTTP Header X-Frame-Options
with a value of DENY
(or SAMEORIGIN
with a different server origin) cannot be integrated into an IFRAME... unless you change this behavior by installing a Browser plugin which ignores the X-Frame-Options
Header (e.g. Chrome's Ignore X-Frame Headers).
Note that this not recommended at all for security reasons.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat
takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date
. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date
provides a getTime()
method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat
a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.
I have always used .val()
and to be honest I didnt even know you could get the value using .attr("value")
. I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');
=IF(A2="Y","Male",IF(A2="N","Female",""))
"This is my string with date in specified format $($theDate.ToString('u'))"
or
"This is my string with date in specified format $(Get-Date -format 'u')"
The sub-expression ($(...)
) can include arbitrary expressions calls.
MSDN Documents both standard and custom DateTime
format strings.
(copied this piece from my other answer in your other question)
Show progress when searching all files in a directory
Of course, as you already know, there are a lot of ways of doing the enumeration itself... but none will be instantaneous. You could try using the USN Journal of the file system to do the scan. Take a look at this project in CodePlex: MFT Scanner in VB.NET... it found all the files in my IDE SATA (not SSD) drive in less than 15 seconds, and found 311000 files.
You will have to filter the files by path, so that only the files inside the path you are looking are returned. But that is the easy part of the job!
$(document).ready( function(){
$("button").click(function(){
$("p").toggle(1000,'linear');
});
});
Using the "file" command may be useful for this:
#!/bin/bash
check_file(){
if [ -z "${1}" ] ;then
echo "Please input something"
return;
fi
f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
echo "DIRECTORY FOUND ($result) ";
else
echo "FILE FOUND ($result) ";
fi
}
check_file "${1}"
Output examples :
$ ./f.bash login
DIRECTORY FOUND (login: directory)
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or directory))
$ ./f.bash evil.php
FILE FOUND (evil.php: PHP script, ASCII text)
FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:
#!/bin/bash
check_file(){
local file="${1}"
[[ -s "${file}" ]] || { echo "is not valid"; return; }
[[ -d "${file}" ]] && { echo "is a directory"; return; }
[[ -f "${file}" ]] && { echo "is a file"; return; }
}
check_file ${1}
It sounds like you are trying to do something like this:
If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:
Here is one way to accomplish that...
web.xml - Map servlet to root (/)
<servlet>
<servlet-name>sprung</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
...
<servlet>
<servlet-mapping>
<servlet-name>sprung</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring JavaConfig
public class SpringSprungConfig extends DelegatingWebMvcConfiguration {
// Delegate resource requests to default servlet
@Bean
protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
return dsrh;
}
//map static resources by extension
@Bean
public SimpleUrlHandlerMapping resourceServletMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
//make sure static resources are mapped first since we are using
//a slightly different approach
mapping.setOrder(0);
Properties urlProperties = new Properties();
urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
mapping.setMappings(urlProperties);
return mapping;
}
@Override
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
//controller mappings must be evaluated after the static resource requests
handlerMapping.setOrder(1);
handlerMapping.setInterceptors(this.getInterceptors());
handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
handlerMapping.setRemoveSemicolonContent(false);
handlerMapping.setUseSuffixPatternMatch(false);
//set other options here
return handlerMapping;
}
}
Additional Considerations
Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)
edit: relevant paragraph follows:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:
'-' + vendor identifier + '-' + meaningful name '_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.
Other known examples:
-moz-box-sizing -moz-border-radius -wap-accesskey
An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.
Authors should avoid vendor-specific extensions
I found out that the naming of my css files was in conflict with the proxy filters
www.dating.com (which is not my site) was blocked and my css and js files were called dating.css and dating.js. The filter was blocking this. Maybe that is the case with some of you, working on corporates systems.
Set the color of the separator to be patterned with your image.
in viewDidLoad
:
self.tableView.separatorColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mySeparatorImage"]];
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
In my ubuntu, following lines in $HOME/.wgetrc did the trick!
http_proxy = http://uname:[email protected]:8080
use_proxy = on
Use String buffer.
final StringBuffer mText = new StringBuffer("SHOP MA\n"
+ "----------------------------\n"
+ "Pannampitiya\n"
+ "09-10-2012 harsha no: 001\n"
+ "No Item Qty Price Amount\n"
+ "1 Bread 1 50.00 50.00\n"
+ "____________________________\n");
Check out Xtify Web Push notifications. http://getreactor.xtify.com/ This tool allows you to push content onto a webpage and target visitors as well as trigger messages based on browser DOM events. It's designed specifically with mobile in mind.
You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.
In the case if "Copy Local" is already True, I find it sometimes to work if you remove the files where it has been published to and publish again.
For example if you're using IIS, remove the websites and the contents of the directory to which they are published to, and publish again.
There might be older versions of files at the destination, so to ensure you aren't using older versions, delete everything before publishing again.
You can also use the Ellipsis when specifying expected doctest output:
class MyClass(object):
"""Example of a doctest Ellipsis
>>> thing = MyClass()
>>> # Match <class '__main__.MyClass'> and <class '%(module).MyClass'>
>>> type(thing) # doctest:+ELLIPSIS
<class '....MyClass'>
"""
pass
The user's input will always be given to you in the form of a string of characters... if you want to convert the user's input from a string to an integer, you'll need to supply the code to do that. If the user types in a number (e.g. "1"), you can pass the string to atoi() to get the integer corresponding to the string. If the user types in an english string (e.g. "EASY") then you'll need to check for that string (e.g. with strcmp()) and assign the appropriate integer value to your variable based on which check matches. Once you have an integer value that was derived from the user's input string, you can pass it into the switch() statement as usual.
All of the grouped objects, or all of the types? It sounds like you may just want:
var query = types.GroupBy(t => t.Type)
.Select(g => new { Type = g.Key, Count = g.Count() });
foreach (var result in query)
{
Console.WriteLine("{0}, {1}", result.Type, result.Count);
}
EDIT: If you want it in a dictionary, you can just use:
var query = types.GroupBy(t => t.Type)
.ToDictionary(g => g.Key, g => g.Count());
There's no need to select into pairs and then build the dictionary.
None of the response works for me targeting a phonegapp App.
As the following link points, the solution below works.
@media screen and (device-height: 568px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
// css here
}
i had same issues , i was trying to mount C:\Users\ folder on docker
this is how i did it Docker Toolbox command line
$ docker run -it --name <containername> -v /c/Users:/myVolData <imagename>
While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:
/*
* Check a folder if changed in the latest commit.
* Returns true if changed, or false if no changes.
*/
def checkFolderForDiffs(path) {
try {
// git diff will return 1 for changes (failure) which is caught in catch, or
// 0 meaning no changes
sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
return false
} catch (err) {
return true
}
}
if ( checkFolderForDiffs('api/') ) {
//API folder changed, run steps here
}
Find below code if you want to download the contents of the specified URL also want to saves it to a file.
<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');
$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec ($ch);
curl_close ($ch);
fclose($fp);
?>
If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:
<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);
// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);
$server_file="test.pdf" //FTP server file path
$local_file = "new.pdf"; //Local server file path
##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
ftp_close($conn_id);
?>
I wasn't happy with the code provided by @Pr0gr4mm3r in https://stackoverflow.com/a/13592567/1211082 . The Stream-based solution does not do URLDecoding, the mutable version clumpsy.
Thus I elaborated a solution that
Map<String, List<Optional<String>>>
Optional.empty()
instead of null
)URLdecode
UnsupportedEncodingException
into a runtime exception RuntimeUnsupportedEncodingException
that allows interplay with stream. (Wrapping regular function into functions throwing checked exceptions is a pain. And Scala Try
is not available in the Java language default.)import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import static java.util.stream.Collectors.*;
public class URIParameterDecode {
/**
* Decode parameters in query part of a URI into a map from parameter name to its parameter values.
* For parameters that occur multiple times each value is collected.
* Proper decoding of the parameters is performed.
*
* Example
* <pre>a=1&b=2&c=&a=4</pre>
* is converted into
* <pre>{a=[Optional[1], Optional[4]], b=[Optional[2]], c=[Optional.empty]}</pre>
* @param query the query part of an URI
* @return map of parameters names into a list of their values.
*
*/
public static Map<String, List<Optional<String>>> splitQuery(String query) {
if (query == null || query.isEmpty()) {
return Collections.emptyMap();
}
return Arrays.stream(query.split("&"))
.map(p -> splitQueryParameter(p))
.collect(groupingBy(e -> e.get0(), // group by parameter name
mapping(e -> e.get1(), toList())));// keep parameter values and assemble into list
}
public static Pair<String, Optional<String>> splitQueryParameter(String parameter) {
final String enc = "UTF-8";
List<String> keyValue = Arrays.stream(parameter.split("="))
.map(e -> {
try {
return URLDecoder.decode(e, enc);
} catch (UnsupportedEncodingException ex) {
throw new RuntimeUnsupportedEncodingException(ex);
}
}).collect(toList());
if (keyValue.size() == 2) {
return new Pair(keyValue.get(0), Optional.of(keyValue.get(1)));
} else {
return new Pair(keyValue.get(0), Optional.empty());
}
}
/** Runtime exception (instead of checked exception) to denote unsupported enconding */
public static class RuntimeUnsupportedEncodingException extends RuntimeException {
public RuntimeUnsupportedEncodingException(Throwable cause) {
super(cause);
}
}
/**
* A simple pair of two elements
* @param <U> first element
* @param <V> second element
*/
public static class Pair<U, V> {
U a;
V b;
public Pair(U u, V v) {
this.a = u;
this.b = v;
}
public U get0() {
return a;
}
public V get1() {
return b;
}
}
}
... and for the sake of completeness I can not resist to provide the solution in Scala that dominates by brevity and beauty
import java.net.URLDecoder
object Decode {
def main(args: Array[String]): Unit = {
val input = "a=1&b=2&c=&a=4";
println(separate(input))
}
def separate(input: String) : Map[String, List[Option[String]]] = {
case class Parameter(key: String, value: Option[String])
def separateParameter(parameter: String) : Parameter =
parameter.split("=")
.map(e => URLDecoder.decode(e, "UTF-8")) match {
case Array(key, value) => Parameter(key, Some(value))
case Array(key) => Parameter(key, None)
}
input.split("&").toList
.map(p => separateParameter(p))
.groupBy(p => p.key)
.mapValues(vs => vs.map(p => p.value))
}
}
You can use a WScript
object and call the Sleep
method on it:
Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds
Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000
If you are making a cross-platform app (eg. using phonegap/cordova) then,
Don't use device-width or device-height. Rather use width or height in CSS media queries because Android device will give problems in device-width or device-height. For iOS it works fine. Only android devices doesn't support device-width/device-height.
If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/
It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.
Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".
def a(): code a
def b(): code b
def c(): code c
def d(): code d
for func in [a, b, c, d]: # change list order to change execution order.
try:
func()
break
except Exception as err:
print (err)
continue
I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).
character varying(n)
, varchar(n)
- (Both the same). value will be truncated to n characters without raising an error.
character(n)
, char(n)
- (Both the same). fixed-length and will pad with blanks till the end of the length.
text
- Unlimited length.
Example:
Table test:
a character(7)
b varchar(7)
insert "ok " to a
insert "ok " to b
We get the results:
a | (a)char_length | b | (b)char_length
----------+----------------+-------+----------------
"ok "| 7 | "ok" | 2
You need to add /// Comment for the member for which warning is displayed.
see below code
public EventLogger()
{
LogFile = string.Format("{0}{1}", LogFilePath, FileName);
}
It displays warning Missing XML comment for publicly visible type or member '.EventLogger()'
I added comment for the member and warning gone.
///<Summary>
/// To write a log <Anycomment as per your code>
///</Summary>
public EventLogger()
{
LogFile = string.Format("{0}{1}", LogFilePath, FileName);
}
You can use ToList to convert to a list. For example,
SomeItems.ToList()[1]
Try using %0A
in the URL, just like you've used %20
instead of the space character.
If you want to upload the file /Applications/XAMPP/htdocs/keypairfile.pem
to ec2-user@publicdns:/var/www/html
, you can simply do:
scp -Cr /Applications/XAMPP/htdocs/keypairfile.pem/uploads/ ec2-user@publicdns:/var/www/html/
Where:
-C
- Compress data-r
- RecursivePossibly mine isn't a great answer but here goes.
Since working more with truly RESTful web services over HTTP, I've tried to steer people away from using the term endpoint since it has no clear definition, and instead use the language of REST which is resources and resource locations.
To my mind, endpoint is a TCP term. It's conflated with HTTP because part of the URL identifies a listening server.
So resource isn't a newer term, I don't think, I think endpoint was always misappropriated and we're realising that as we're getting our heads around REST as a style of API.
Edit
I blogged about this.
https://medium.com/@lukepuplett/stop-saying-endpoints-92c19e33e819
Not sure if this works in all os, try it out.
ifconfig | awk -F"[ :]+" '/inet addr/ && !/127.0/ {print $4}'
In Python pandas provide head() and tail() to print head and tail data respectively.
import pandas as pd
train = pd.read_csv('file_name')
train.head() # it will print 5 head row data as default value is 5
train.head(n) # it will print n head row data
train.tail() #it will print 5 tail row data as default value is 5
train.tail(n) #it will print n tail row data
This may help if someone want it in PHP
$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);
Thanks Merritt :)
I've just updated this to MVC 3 in case anyone finds it useful: Conditional Validation in ASP.NET MVC 3.
The error in question may also be caused by disabled JarScanner in tomcat/conf/context.xml
.
See also Upgrade from Tomcat 8.0.39 to 8.0.41 results in 'failed to scan' errors.
<JarScanner scanManifest="false"/>
allows to avoid both problems.
For those who came here looking for a way to take pictures/photos programmatically using both Android's Camera and Camera2 API, take a look at the open source sample provided by Google itself here.
I found up-to-date resources here: Microsoft | SQL Docs | Python SQL Driver
There are these two options explained including all the prerequisites needed and code examples: Python SQL driver - pyodbc (tested & working) Python SQL driver - pymssql
You can also use this syntax: (in column D to concatenate A, B, and C)
=A2 & " """ & B2 & """ " & C2
Best approach to add a brand logo inside a navbar-inner
class and a container. About the <h3>
issue <h3>
has a certain padding given to it in bootstrap as @creimers told. And if you are using a bigger image, increase the height of navbar too or the logo will float outside.
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-inner"> <!--changes made here-->
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img src="http://placehold.it/150x50&text=Logo" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
</div>
</nav>
inputString.splitlines()
Will give you a list with each item, the splitlines()
method is designed to split each line into a list element.
font/woff2
For nginx add the following to the mime.types
file:
font/woff2 woff2;
Old Answer
The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2
.
Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2
is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/*
(font/ttf
, font/woff2
etc)...
N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.
You can check whether the connection was lost or not by using this function:-
var socket = io( /**connection**/ );
socket.on('disconnect', function(){
//Your Code Here
});
Hope it will help you.
If you need to set the UICollectionView scrolling Direction Horizental and you need to set cell width and height static. Please set the collectionview estimate size Automatic into None .
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname(); But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.
No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #
). You can do so by setting window.location.hash
.
Another way of doing this, using only JavaScript, would be this:
window.addEventListener('resize', functionName);
This fires every time the size changes, like the other answer.
functionName
is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).
When Bootstrap Select initializes, it'll build a set of custom divs that run alongside the original <select>
element and will typically synchronize state between the two input mechanisms.
Which is to say that one way to handle events on bootstrap select is to listen for events on the original select that it modifies, regardless of who updated it.
Just listen for a change
event and get the selected value using javascript or jQuery like this:
$('select').on('change', function(e){
console.log(this.value,
this.options[this.selectedIndex].value,
$(this).find("option:selected").val(),);
});
*NOTE: As with any script reliant on the DOM, make sure you wait for the DOM ready event before executing
$(function() {_x000D_
_x000D_
$('select').on('change', function(e){_x000D_
console.log(this.value,_x000D_
this.options[this.selectedIndex].value,_x000D_
$(this).find("option:selected").val(),);_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
As this answer alludes, Bootstrap Select has their own set of custom events, including changed.bs.select
which:
fires after the select's value has been changed. It passes through event, clickedIndex, newValue, oldValue.
And you can use that like this:
$("select").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
console.log(this.value, clickedIndex, newValue, oldValue)
});
$(function() {_x000D_
_x000D_
$("select").on("changed.bs.select", _x000D_
function(e, clickedIndex, newValue, oldValue) {_x000D_
console.log(this.value, clickedIndex, newValue, oldValue)_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
keep it simple and explicit. You can of course pre-define a dictionary.
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
If you plan on modifying your simulate
function to include more return codes, maintaining this code might become a bit of an issue.
The simulate
might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.
Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight
/outerWidth
functions to retrieve the width including padding/borders, e.g.
$(elem).outerWidth(); // Returns the width + padding + borders
To include the margin as well, simply pass true
:
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins
We can use setTag()
and getTag()
to set and get custom objects as per our requirement. The setTag()
method takes an argument of type Object
, and getTag()
returns an Object
.
For example,
Person p = new Person();
p.setName("Ramkailash");
p.setId(2000001);
button1.setTag(p);
The syntax of this question looks like Robot Framework syntax. In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead. The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male
The specific way to run it depends on whether you gave the image a tag/name or not.
$ docker images
REPOSITORY TAG ID CREATED SIZE
ubuntu 12.04 8dbd9e392a96 4 months ago 131.5 MB (virtual 131.5 MB)
With a name (let's use Ubuntu):
$ docker run -i -t ubuntu:12.04 /bin/bash
Without a name, just using the ID:
$ docker run -i -t 8dbd9e392a96 /bin/bash
Please see Docker run reference for more information.
If you are able to run a script, here is what I did for a similar situation:
Using a dictionary/hashMap (associative array) and variables for the sed
command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern
will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt'
) in a specific directory (source_dir
).
All the changes are written in the logfile
in the destin_dir
#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'
echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "
declare -A pairs=(
['WHAT1']='FOR1'
['OTHER_string_to replace']='string replaced'
)
for i in "${!pairs[@]}"; do
j=${pairs[$i]}
echo "[$i]=$j"
replace_what=$i
replace_for=$j
echo " "
echo "Replace: $replace_what for: $replace_for"
find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g"
find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done
echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile
First, the pairs array is declared, each pair is a replacement string, then WHAT1
will be replaced for FOR1
and OTHER_string_to replace
will be replaced for string replaced
in the file File.txt
. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i
and the second as replace_for=$j
. The find
command searches in the directory the filename (that may contain a wildcard) and the sed -i
command replaces in the same file(s) what was previously defined. Finally I added a grep
redirected to the logfile to log the changes made in the file(s).
This worked for me in GNU Bash 4.3
sed 4.2.2
and based upon VasyaNovikov's answer for Loop over tuples in bash.
this seems to be working nicely for me
$(window).bind('resize', function() {
jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');
JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
I used this code to convert all columns to numeric except the first one:
library(dplyr)
# check structure, row and column number with: glimpse(df)
# convert to numeric e.g. from 2nd column to 10th column
df <- df %>%
mutate_at(c(2:10), as.numeric)
In my case I don't use the Android studio (I am using eclipse). I did the following step: Solved just by running the command
android-sdks/tools/bin$ ./sdkmanager --update
Which created a licenses
directory and added a file called android-sdk-license
inside it.
Then you can run (licenses
option is not available unless you did the step above)
android-sdks/tools/bin$ ./sdkmanager --licenses
and accept the license (however, in my case I didn't need to do that)
You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation
<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>
<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals
There's not much of one in everyday work.
However, according to the documentation for both functions (accessed by putting a ?
before the function name and hitting enter), require
is used inside functions, as it outputs a warning and continues if the package is not found, whereas library
will throw an error.
In my case it works just commenting (or deleting) the anonymousAuthentication property:
<security>
<authentication>
<!--<anonymousAuthentication enabled="true" />-->
</authentication>
</security>
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test
command.
You can use this for some further reading:
If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX()
or isXXXX()
as a method name. From the Java Beans spec:
8.3.2 Boolean properties
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is
<PropertyName>()
;This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:
public boolean isMarsupial(); public void setMarsupial(boolean m);
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the delete
operator:
const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
Note that when delete
is applied to an index property of an Array
, you will create a sparsely populated array (ie. an array with a missing index).
When working with instances of Array
, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice
or Array#pop
.
Note that the delete
operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o
, then o
will subsequently be garbage collected in the normal way.
Using the delete
operator can affect JavaScript engines' ability to optimise code.
d = dict.fromkeys(a, 0)
a
is the list, 0
is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.
for the line you wrote
var g = $('<%=Label1.ClientID%>').val(); // Also I tried .text() and .html()
you missed adding #. it should be like this
var g = $('#<%=Label1.ClientID%>').text();
also I do not prefer using this method
that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.
you should ALWAYS call the ID of the control directly. like this
$('#ControlID')
this is simple and clear. but do not forget to set
ClientIDMode="Static"
in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID
I hope it clears the question Good Luck
Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):
>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n Garply\n \n"
>>> print a
Foo
Bar
Baz
Garply
>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
Garply
>>>
DELIMITER //
CREATE TRIGGER contacts_after_insert
AFTER INSERT
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing the INSERT into table
SELECT USER() INTO vUser;
-- Insert record into audit table
INSERT INTO contacts_audit
( contact_id,
deleted_date,
deleted_by)
VALUES
( NEW.contact_id,
SYSDATE(),
vUser );
END; //
DELIMITER ;
Adding the default_url in routes not the right solution although, it works for some cases.
You've to set the default_url in each environment(development, test, production).
You need make these changes.
config/environments/development.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
config/environments/test.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
config/environments/development.rb
config.action_mailer.default_url_options =
{ :host => 'your-host-name' } #if it is local then 'localhost:3000'
there isn't method to call Servlet. You should make mapping in web.xml and then trigger this mapping.
Example: web.xml:
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
This mapping means that every call to http://yoursite/yourwebapp/hello trigger this servlet For example this jsp:
<jsp:forward page="/hello"/>
In addition to the tools and methodes provided in the other anwers, static code analysis tools can be used to detect memory leaks (and other issues as well). A free an robust tool is Cppcheck. But there are a lot of other tools available. Wikipedia has a list of static code analysis tools.
Take a look at the System
log in Windows EventViewer (eventvwr
from the command line).
You should see entries with source as 'Service Control Manager'. e.g. on my WinXP machine,
Event Type: Information
Event Source: Service Control Manager
Event Category: None
Event ID: 7036
Date: 7/1/2009
Time: 12:09:43 PM
User: N/A
Computer: MyMachine
Description:
The Background Intelligent Transfer Service service entered the running state.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
Otherwise for old version, if '--show-item' is not recognize, you can use the following command :
svn log -r HEAD | grep -o -E "^r[0-9]{1,}" | sed 's/r//g'
Hope it helps.
Change the submit button to:
<button type="submit" ng-disabled="loginform.$invalid">Login</button>
if you need to do something before submitting data, you could use form's onsubmit.
<form method=post onsubmit="return doSomething()">
<input type=text name=text1>
<input type=submit>
</form>
Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.
An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"
A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
BinaryFormatter
may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.
If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer
or XmlSerializer
.
Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
try
{
string contents = File.ReadAllText(file.FullName);
Console.WriteLine("input : {0}", contents);
contents = contents.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", contents);
File.WriteAllText(file.FullName, contents);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
This seems to work:
select your_column
from your_table
order by
case when isnumeric(your_column) = 1 then your_column else 999999999 end,
your_column
For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes
instead of yAxes
. Note that an array (and plural) is used for yAxes
(or xAxes
), because you may as well have multiple axes.
If you navigate to where you have installed SQLExpress, e.g.
C:\Program Files\Microsoft SQL Server\110\Tools\Binn
You can run SQLLocalDB.exe and get a list of the all instances installed on your machine.
C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info
MSSQLLocalDB
ProjectsV12
v11.0
Then you can get further information on the instance.
C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info MSSQLLocalDB Name: MSSQLLocalDB
Version: 13.0.1601.5
Shared name:
Owner: Domain\User
Auto-create: Yes
State: Stopped
Last start time: 22/09/2016 10:19:33
Instance pipe name:
To show a grid line on every tick, add
plt.grid(True)
For example:
import matplotlib.pyplot as plt
points = [
(0, 10),
(10, 20),
(20, 40),
(60, 100),
]
x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))
plt.scatter(x, y)
plt.grid(True)
plt.show()
In addition, you might want to customize the styling (e.g. solid line instead of dashed line), add:
plt.rc('grid', linestyle="-", color='black')
For example:
import matplotlib.pyplot as plt
points = [
(0, 10),
(10, 20),
(20, 40),
(60, 100),
]
x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))
plt.rc('grid', linestyle="-", color='black')
plt.scatter(x, y)
plt.grid(True)
plt.show()
Swift 4.2 & 5
// *** Create date ***
let date = Date()
// *** create calendar object ***
var calendar = Calendar.current
// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date))
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get All components from date ***
let components = calendar.dateComponents([.hour, .year, .minute], from: date)
print("All Components : \(components)")
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")
Swift 3.0
// *** Create date ***
let date = Date()
// *** create calendar object ***
var calendar = NSCalendar.current
// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date))
// *** define calendar components to use as well Timezone to UTC ***
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get All components from date ***
let components = calendar.dateComponents(unitFlags, from: date)
print("All Components : \(components)")
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")
i always use connection.relase(); after pool.getconnetion like
pool.getConnection(function (err, connection) {
connection.release();
if (!err)
{
console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
//CHECKING USERNAME EXISTENCE
email = receivedValues.email
connection.query('SELECT * FROM users WHERE email = ?', [email],
function (err, rows) {
if (!err)
{
if (rows.length == 1)
{
if (bcrypt.compareSync(req.body.password, rows[0].password))
{
var alldata = rows;
var userid = rows[0].id;
var tokendata = (receivedValues, userid);
var token = jwt.sign(receivedValues, config.secret, {
expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
});
console.log("*** Authorised User");
res.json({
"code": 200,
"status": "Success",
"token": token,
"userData": alldata,
"message": "Authorised User!"
});
logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
return;
}
else
{
console.log("*** Redirecting: Unauthorised User");
res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
logger.error('*** Redirecting: Unauthorised User');
return;
}
}
else
{
console.error("*** Redirecting: No User found with provided name");
res.json({
"code": 200,
"status": "Error",
"message": "No User found with provided name"
});
logger.error('url=', URL.url, 'No User found with provided name');
return;
}
}
else
{
console.log("*** Redirecting: Error for selecting user");
res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
return;
}
});
connection.on('error', function (err) {
console.log('*** Redirecting: Error Creating User...');
res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
return;
});
}
else
{
Errors.Connection_Error(res);
}
});
What about defining an empty array as fallback if get_value()
is empty?
I can't think of a shortest way.
$values = get_values() ?: [];
foreach ($values as $value){
...
}
Try str.replace()
:
string = "it is icy"
print string.replace("i", "")
Create a branch where you are, then switch to master and merge it:
git branch my-temporary-work
git checkout master
git merge my-temporary-work
In CentOS this might be caused by the SELinux policy. Execute the following code to see if it is enabled.
getsebool httpd_can_sendmail
You can enable it by calling the command below. The -P parameter makes it permanent.
setsebool -P httpd_can_sendmail 1
You have already grouped by ContenderNum, no need to partition again by it. Use Dense_rank()and order by totals desc. In short,
SELECT contendernum,totals, **DENSE_RANK()**
OVER (ORDER BY totals **DESC**)
AS xRank
FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
You don't even have to set a specific width for the cells, table-layout: fixed
suffices to spread the cells evenly.
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid hotpink;_x000D_
vertical-align: middle;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz</li>_x000D_
</ul>
_x000D_
Note that for
table-layout
to work the table styled element must have a width set (100% in my example).
I searched for the error in the web and came to this page. I am using Visual Studio 2015 and this is my first MVC project.
If you miss the @ symbol before the render section you will get the same error. I would like to share this for future beginners.
@RenderSection("headscripts", required: false)
Simple answer - 5 is Italian "yy" and 105 is Italian "yyyy". Therefore:
SELECT convert(datetime,'21-02-12 6:10:00 PM',5)
will work correctly, but
SELECT convert(datetime,'21-02-12 6:10:00 PM',105)
will give error.
Likewise,
SELECT convert(datetime,'21-02-2012 6:10:00 PM',5)
will give error, where as
SELECT convert(datetime,'21-02-2012 6:10:00 PM',105)
will work.
If anybody is just like me willing to use jQuery, but still found himself looking to this question then this may help you guys:
https://html-online.com/articles/animated-scroll-anchorid-function-jquery/
$(document).ready(function () {_x000D_
$("a.scrollLink").click(function (event) {_x000D_
event.preventDefault();_x000D_
$("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);_x000D_
});_x000D_
});
_x000D_
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>_x000D_
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>_x000D_
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>_x000D_
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>
_x000D_
While ("run as SYSTEM") works, people should be advised this means going from a minimum-permissions type account to an account which has all permissions in the world. Which is very much not a recommended setup best practices or security-wise.
If you know what you are doing and know your SQL Server will always be run in an isolated environment (i.e. not on hotel or airport wifi) it's probably fine, but this creates a very real attack vector which can completely compromise a machine if on open internets.
This seems to be an error on Microsoft's part and people should be aware of the implications of the workaround posted.
For the sake of completeness -- just because none of the previous answers mentioned this method -- if you are working with Node.js and don't have to care about browser compatibility, the desired effect is pretty easy to achieve with the built in inherits
of the util
module (official docs here).
For example, let's suppose you want to create a custom error class that takes an error code as the first argument and the error message as the second argument:
file custom-error.js:
'use strict';
var util = require('util');
function CustomError(code, message) {
Error.captureStackTrace(this, CustomError);
this.name = CustomError.name;
this.code = code;
this.message = message;
}
util.inherits(CustomError, Error);
module.exports = CustomError;
Now you can instantiate and pass/throw your CustomError
:
var CustomError = require('./path/to/custom-error');
// pass as the first argument to your callback
callback(new CustomError(404, 'Not found!'));
// or, if you are working with try/catch, throw it
throw new CustomError(500, 'Server Error!');
Note that, with this snippet, the stack trace will have the correct file name and line, and the error instance will have the correct name!
This happens due to the usage of the captureStackTrace
method, which creates a stack
property on the target object (in this case, the CustomError
being instantiated). For more details about how it works, check the documentation here.
"foo is bar".replace(/ /g, '')
No, but since C++11 there is [u]int8_t.
Maybe there's a more simple answer, try to add any background color you like to the code, like background-color: #fff;
#alpha {
background-color: #fff;
opacity: 0.8;
filter: alpha(opacity=80);
}
You can't set the value
of a file
input in the markup, like you did with value="123"
.
This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/
Yes. In current versions of JS you can use:
app[func]( ...args );
Users of ES5 and older will need to use the .apply()
method:
app[func].apply( this, args );
Read up on these methods at MDN:
The same happened to me. But the scenario was a little different, I had master branch, and I carved out release_1 (say) out of it. Made some changes in release_1 branch and merged it into origin. then I did ssh and on the remote server I again checkout out release_1 using the command git checkout -b release_1 - which actually carves out a new branch release_! from the master rather than checking out the already existing branch release_1 from origin. Solved the problem by removing "-b" switch
I have bool? IsDisabled { get; set; }
in Model. Inserted if in View.
<div class="inputClass" id="disabled">
<div>
@if(Model.IsDisabled==null)
{
Model.IsDisabled = false;
}
@Html.CheckBoxFor(model => model.IsDisabled.Value)
</div>
</div>
You can do checks using lookarounds:
^(?=.*\bjack\b)(?=.*\bjames\b).*$
This approach has the advantage that you can easily specify multiple conditions.
^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$
It seems you don't import jquery. Those $ functions come with this non standard (but very useful) library.
Read the tutorial there : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery It starts with how to import the library.
If lib/__init__.py
defines the Helper class then in settings.py you can use:
from . import Helper
This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__
.
(Confirmed with python 2.7.10, running on Windows.)
I know this is old, but I just ran into the problem and didn't find a great solution. So, I decided on using some js to get the scrollBody's height, as compared to the tables height. If the scrollBody is smaller than the table, then I increase the tables width by 15px to account for the scrollbar. I set this up on resize event too, so that it works when my container changes sizes:
const tableHeight = $('#' + this.options.id).height();
const scrollBodyHeight = $('#' + this.options.id).closest('.dataTables_scrollBody').height();
if (tableHeight > scrollBodyHeight) {
$('#' + this.options.id).closest('.dataTables_scrollBody').css({
width: "calc(100% + 15px)",
})
} else {
$('#' + this.options.id).closest('.dataTables_scrollBody').css({
width: "100%",
})
}
As so many good answers said, an object must implement the Iterable interface
if it wants to use a for-each
loop.
I'll post a simple example and try to explain in a different way how a for-each
loop works.
The for-each
loop example:
public class ForEachTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
for (String str : list) {
System.out.println(str);
}
}
}
Then, if we use javap
to decompile this class, we will get this bytecode sample:
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=4, args_size=1
0: new #16 // class java/util/ArrayList
3: dup
4: invokespecial #18 // Method java/util/ArrayList."<init>":()V
7: astore_1
8: aload_1
9: ldc #19 // String 111
11: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
16: pop
17: aload_1
18: ldc #27 // String 222
20: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
25: pop
26: aload_1
27: invokeinterface #29, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
As we can see from the last line of the sample, the compiler will automatically convert the use of for-each
keyword to the use of an Iterator
at compile time. That may explain why object, which doesn't implement the Iterable interface
, will throw an Exception
when it tries to use the for-each
loop.
You could use the PHP in_array function
if( in_array( "bla" ,$yourarray ) )
{
echo "has bla";
}
something.data()
will return a pointer to the data space of the vector.
OK, it's 15 lines of code but the result is awesome! That's the kind of stuff that made me freak out when I was a child. This is from the PHP manual:
$x = 200;
$y = 200;
$gd = imagecreatetruecolor($x, $y);
$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);
$red = imagecolorallocate($gd, 255, 0, 0);
for ($i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x),round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}
header('Content-Type: image/png');
imagepng($gd);
I suggest you use a readdir() function and then loop and include the files (see the 1st example on that page).
Use double quotes instead of single quotes
e.g. echo "$foo"
as opposed to echo '$foo'
If you configured your pipeline to accept parameters using the Build with Parameters option, those parameters are accessible as Groovy variables of the same name. See Here.
You can drop the semicolon (;
), drop the parentheses (( and )
), and use single quotes ('
) instead of double ("
) if you do not need to perform variable substitutions. See Here. This clued me into my problem, though I've found that only the double ("
) is required to make it work.
Take a look at the Java standard API doc. Right next to LinkedHashMap
, there is a LinkedHashSet
. But note that the order in those is the insertion order, not the natural order of the elements. And you can only iterate in that order, not do random access (except by counting iteration steps).
There is also an interface SortedSet
implemented by TreeSet
and ConcurrentSkipListSet
. Both allow iteration in the natural order of their elements or a Comparator
, but not random access or insertion order.
For a data structure that has both efficient access by index and can efficiently implement the set criterium, you'd need a skip list, but there is no implementation with that functionality in the Java Standard API, though I am certain it's easy to find one on the internet.
This answer helped to me download image from server to client side.
<a download="original_file.jpg" href="file/path.jpg">
<img src="file/path.jpg" class="img-responsive" width="600" />
</a>
I was trying to find the same thing and got disappointed. I ended up changing the attribute size for the select box so it appears to open
$('#countries').attr('size',6);
and then when you're finished
$('#countries').attr('size',1);
Existing screen log can be saved by :
Ctrl+A : hardcopy -h filename
The Hibernate Validator requires — but does not include — an Expression Language (EL) implementation. Adding a dependency on one will will fix the issue.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>3.0.3</version>
</dependency>
This requirement is documented in the Getting started with Hibernate Validator documentation. In a Java EE environment, it would be provided by the container. In a standalone application such as yours, it needs to be provided.
Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages.
When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container.
In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance, you can add the following dependency to use the JSR 341 reference implementation:
<dependency> <groupId>org.glassfish</groupId> <artifactId>jakarta.el</artifactId> <version>${version.jakarta.el-api}</version> </dependency>
There are other EL implementations that can be used other than Glassfish. For instance, Spring Boot versions 2.2.x and earlier by default used embedded Tomcat (it's since switched to use the Jakarta EL reference implementation). That version of EL can be used as follows:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>9.0.41</version>
</dependency>
That said, in a Spring Boot project, typically one would use the spring-boot-starter-validation
dependency rather than specifying the Hibernate validator & EL libraries directly. That dependency includes both hibernate-validator
and the EL implementation.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.4.2.RELEASE</version>
</dependency>
aria-hidden="true"
will hide decorative items like glyphicon icons from screen readers, which doesn't have meaningful pronunciation so as not to cause confusions. It's a nice thing do as matter of good practice.
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
Use the built-in function round()
:
In [23]: round(66.66666666666,4)
Out[23]: 66.6667
In [24]: round(1.29578293,6)
Out[24]: 1.295783
help on round()
:
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.
Instead of window
use global
it('correct url is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
you could also try
const open = jest.fn()
Object.defineProperty(window, 'open', open);
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.
The tab character is \t
. Notice the use of "
instead of '
.
$chunk = "abc\tdef\tghi";
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
...
\t horizontal tab (HT or 0x09 (9) in ASCII)
Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.
Remove @ResponseBody annotation from your use parameters in method. Like this;
@Autowired
ProjectService projectService;
@RequestMapping(path = "/add", method = RequestMethod.POST)
public ResponseEntity<Project> createNewProject(Project newProject){
Project project = projectService.save(newProject);
return new ResponseEntity<Project>(project,HttpStatus.CREATED);
}
There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.
To modify a remote system's global environment variables, you would use
setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere
This does not require restarting Windows Explorer.
AnyOrigin didn't function well with some https sites, so I just wrote an open source alternative called whateverorigin.org that seems to work well with https.
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%
. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.
The simple single command line solution which of course can be also used in a batch file:
pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )
This command line contains three commands executed one after the other.
The first command PUSHD pushes current directory path on stack and next makes %PathToFolder%
the current directory for running command process.
This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.
PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:
The system cannot find the path specified.
This error message is suppressed by redirecting it with 2>nul
to device NUL.
The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.
The command RD with the options /Q
and /S
removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.
Not deleted are:
Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.
Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.
Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.
The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:
The process cannot access the file because it is being used by another process.
File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.
This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul
from handle STDERR to device NUL.
The third command, POPD, is executed independently of the exit value of command RD.
POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.
Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder%
remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%
.
One more interesting fact:
I tried the command line also using a UNC path by sharing local directory C:\Temp
with share name Temp
and using UNC path \\%COMPUTERNAME%\Temp\CleanTest
assigned to environment variable PathToFolder
on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1
, Subfolder1
is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1
again the current directory resulting in Z:\CleanTest
remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot%
to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.
For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.
pushd /?
popd /?
rd /?
Single line with multiple commands using Windows batch file explains the operators &&
and &
used here.
Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder%
and FOR and RD to delete the subfolders in %PathToFolder%
.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"
rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"
rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder
rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"
rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder
rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
:EndCleanFolder
endlocal
The batch file first makes sure that environment variable PathToFolder
is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder
is concatenated with other strings during batch file execution.
Important are the two lines:
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
The command DEL is used to delete all files in the specified directory.
/A
is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A
./F
is necessary to force deletion of files with the read-only attribute set./Q
is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.>nul
is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.2>nul
is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D
is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F
is used to run the following command line in a separate command process started in the background with %ComSpec% /c
:
dir "%PathToFolder%\*" /AD /B 2>nul
DIR outputs in bare format because of /B
the directory entries with attribute D
, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul
is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.
The redirection operator >
must be escaped with the caret character, ^
, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir
command line in a separate command process started in the background.
FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.
FOR with option /F
ignores empty lines which don't occur here as DIR with option /B
does not output empty lines.
FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=|
is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.
FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I
. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims=
is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I
, always the complete directory name.
Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
rem /?
set /?
setlocal /?
Ensure debug mode is on - either add APP_DEBUG=true
to .env file or set an environment variable
Log files are in storage/logs folder. laravel.log
is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.
In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).
If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).
try to upgrade each of those modules using pecl command
# pecl upgrade fileinfo
# pecl upgrade memcache
# pecl upgrade mhash
# pecl upgrade readline
etc...
Send your file as a base64 string.
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
target: '_blank',
download: fname
})[0].click();
If attr method not working in Firefox You can also use javaScript setAttribute method
If you prefer to use annotations to selectively silence rules, this is now possible using the @SuppressWarnings
annotation, starting with Checkstyle 5.7 (and supported by the Checkstyle Maven Plugin 2.12+).
First, in your checkstyle.xml
, add the SuppressWarningsHolder
module to the TreeWalker
:
<module name="TreeWalker">
<!-- Make the @SuppressWarnings annotations available to Checkstyle -->
<module name="SuppressWarningsHolder" />
</module>
Next, enable the SuppressWarningsFilter
there (as a sibling to TreeWalker
):
<!-- Filter out Checkstyle warnings that have been suppressed with the @SuppressWarnings annotation -->
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
...
Now you can annotate e.g. the method you want to exclude from a certain Checkstyle rule:
@SuppressWarnings("checkstyle:methodlength")
@Override
public boolean equals(Object obj) {
// very long auto-generated equals() method
}
The checkstyle:
prefix in the argument to @SuppressWarnings
is optional, but I like it as a reminder where this warning came from. The rule name must be lowercase.
Lastly, if you're using Eclipse, it will complain about the argument being unknown to it:
Unsupported @SuppressWarnings("checkstyle:methodlength")
You can disable this Eclipse warning in the preferences if you like:
Preferences:
Java
--> Compiler
--> Errors/Warnings
--> Annotations
--> Unhandled token in '@SuppressWarnings': set to 'Ignore'
After looking at the previous responses, I hope this will help resolve any ambiguities. In case the similarities in the previous solutions and my solution are illusive, or this method of solving for roots is unclear, I've also made a graph which can be found here.
(default is square root for the sake of this question)
#include <cmath>
// for "pow" function
double sqrt(double A, double root = 2) {
const double e = 2.71828182846;
return pow(e,(pow(10.0,9.0)/root)*(1.0-(pow(A,-pow(10.0,-9.0)))));
}
Explanation:
This works via Taylor series, logarithmic properties, and a bit of algebra.
Take, for example:
log A = N
x
*Note: for square-root, N = 2; for any other root you only need to change the one variable, N.
1) Change the base, convert the base 'x' log function to natural log,
log A => ln(A)/ln(x) = N
x
2) Rearrange to isolate ln(x), and eventually just 'x',
ln(A)/N = ln(x)
3) Set both sides as exponents of 'e',
e^(ln(A)/N) = e^(ln(x)) >~{ e^ln(x) == x }~> e^(ln(A)/N) = x
4) Taylor series represents "ln" as an infinite series,
ln(x) = (k=1)Sigma: (1/k)(-1^(k+1))(k-1)^n
<~~~ expanded ~~~>
[(x-1)] - [(1/2)(x-1)^2] + [(1/3)(x-1)^3] - [(1/4)(x-1)^4] + . . .
*Note: Continue the series for increased accuracy. For brevity, 10^9 is used in my function which expresses the series convergence for the natural log with about 7 digits, or the 10-millionths place, for precision,
ln(x) = 10^9(1-x^(-10^(-9)))
5) Now, just plug in this equation for natural log into the simplified equation obtained in step 3.
e^[((10^9)/N)(1-A^(-10^-9)] = nth-root of (A)
6) This implementation might seem like overkill; however, its purpose is to demonstrate how you can solve for roots without having to guess and check. Also, it would enable you to replace the pow function from the cmath library with your own pow function:
double power(double base, double exponent) {
if (exponent == 0) return 1;
int wholeInt = (int)exponent;
double decimal = exponent - (double)wholeInt;
if (decimal) {
int powerInv = 1/decimal;
if (!wholeInt) return root(base,powerInv);
else return power(root(base,powerInv),wholeInt,true);
}
return power(base, exponent, true);
}
double power(double base, int exponent, bool flag) {
if (exponent < 0) return 1/power(base,-exponent,true);
if (exponent > 0) return base * power(base,exponent-1,true);
else return 1;
}
int root(int A, int root) {
return power(E,(1000000000000/root)*(1-(power(A,-0.000000000001))));
}
Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.
Example for Google Chrome:
public class AssemblyLoader<T> where T:class
{
public void(){
var res = Load(@"C:\test\paquete.uno.dos.test.dll", "paquete.uno.dos.clasetest.dll")
}
public T Load(string assemblyFile, string objectToInstantiate)
{
var loaded = Activator.CreateInstanceFrom(assemblyFile, objectToInstantiate).Unwrap();
return loaded as T;
}
}
to_char
actually lets you pull out the Year and month in one fell swoop!
select to_char(date('2014-05-10'),'Mon-YY') as year_month; --'May-14'
select to_char(date('2014-05-10'),'YYYY-MM') as year_month; --'2014-05'
or in the case of the user's example above:
select to_char(date,'YY-Mon') as year_month
sum("Sales") as "Sales"
from some_table
group by 1;
Use This for MAC users
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
To call from command line chmod 755 /var/www/webroot/index.php
and use
/usr/bin/php /var/www/webroot/index.php arg1 arg2
To call from the browser, use
http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
Your best bet is to right click > inspect the element.
I am using Bootstrap 4 and none of the suggestions worked until I did this.
Once I found where the relevant code was in the inspect window, I copied and pasted the relevant code that was causing the :focus to be outlined blue and changed it accordingly.
This is the code that worked in my css
.btn.focus, .btn:focus
{
outline: 0;
box-shadow: 0 0 0 0;
}
VOLUME is used in Dockerfile
to expose the volume to be used by other containers. Example, create Dockerfile
as:
FROM ubuntu:14.04
RUN mkdir /myvol
RUN echo "hello world" > /myvol/greeting
VOLUME /myvol
build the image:
$ docker build -t testing_volume .
Run the container, say container1:
$ docker run -it <image-id of above image> bash
Now run another container with volumes-from option as (say-container2)
$ docker run -it --volumes-from <id-of-above-container> ubuntu:14.04 bash
You will get all data from container1 /myvol
directory into container2 at same location.
-v
option is given at run time of container which is used to mount container's directory on host. It is simple to use, just provide -v
option with argument as <host-path>:<container-path>
. The whole command may be as $ docker run -v <host-path>:<container-path> <image-id>
actions
in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.
Here is an example: myAction
returns a Promise
, makes a http call and resolves or rejects the Promise
later - all asynchronously
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
Now, when your Vue component initiates myAction
, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
As you can see above, it is highly beneficial for actions
to return a Promise
. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.
And a last note regarding mutators
- as you rightly pointed out, they are synchronous. They change stuff in the state
, and are usually called from actions
. There is no need to mix Promises
with mutators
, as the actions
handle that part.
Edit: My views on the Vuex cycle of uni-directional data flow:
If you access data like this.$store.state["your data key"]
in your components, then the data flow is uni-directional.
The promise from action is only to let the component know that action is complete.
The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"]
which is unidirectional and follows the vuex data lifecycle.
The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data)
, once the http call is completed in your action.
Here's how I solved it, with nullable double extension method.
public static bool NearlyEquals(this double? value1, double? value2, double unimportantDifference = 0.0001)
{
if (value1 != value2)
{
if(value1 == null || value2 == null)
return false;
return Math.Abs(value1.Value - value2.Value) < unimportantDifference;
}
return true;
}
...
double? value1 = 100;
value1.NearlyEquals(100.01); // will return false
value1.NearlyEquals(100.000001); // will return true
value1.NearlyEquals(100.01, 0.1); // will return true
Yes, but it's clunky as hell, e.g.
<c:choose>
<c:when test="${condition1}">
...
</c:when>
<c:when test="${condition2}">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>
Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.
In short, you add the selector after the URL. For example:
$('#result').load('ajax/test.html #container');
I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.
However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:
class Foo {
private int id;
private string name;
public Foo(int id = 0, string name = "") {
this.id = id;
this.name = name;
}
}
class Main() {
// Foo Int:
Foo myFooOne = new Foo(12);
// Foo String:
Foo myFooTwo = new Foo(name:"Timothy");
// Foo Both:
Foo myFooThree = new Foo(13, name:"Monkey");
}
When you implement the constructor, you can use the optional arguments since defaults have been set.
I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.
It is not required for me to use the PDFBox library, so a solution that uses another library is fine
Camelot and Excalibur
You may want to try Python library Camelot, an open source library for Python. If you are not inclined to write code, you may use the web interface Excalibur created around Camelot. You "upload" the document to a localhost web server, and "download" the result from this localhost server.
Here is an example from using this python code:
import camelot
tables = camelot.read_pdf('foo.pdf', flavor="stream")
tables[0].to_csv('foo.csv')
The input is a pdf containing this table:
Sample table from the PDF-TREX set
No help is provided to camelot, it is working on its own by looking at pieces of text relative alignment. The result is returned in a csv file:
PDF table extracted from sample by camelot
"Rules" can de added to help camelot identify where are fillets in sophisticated tables:
Rule added in Excalibur. Source
GitHub:
The two projects are active.
Here is a comparison with other software (with test based on actual documents), Tabula, pdfplumber, pdftables, pdf-table-extract.
I want is to be able to parse the file and know what each parsed number means
You cannot do that automatically, as pdf is not semantically structured.
Book versus document
Pdf "documents" are unstructured from a semantic standpoint (it's like a notepad file), the pdf document gives instructions on where to print a text fragment, unrelated to other fragments of the same section, there is no separation between content (what to print, and whether this is a fragment of a title, a table or a footnote) and the visual representation (font, location, etc). Pdf is an extension of PostScript, which describes a Hello world! page this way:
!PS
/Courier % font
20 selectfont % size
72 500 moveto % current location to print at
(Hello world!) show % add text fragment
showpage % print all on the page
(Wikipedia).
One can imagine what a table looks like with the same instructions.
We could say html is not clearer, however there is a big difference: Html describes the content semantically (title, paragraph, list, table header, table cell, ...) and associates the css to produce a visual form, hence content is fully accessible. In this sense, html is a simplified descendant of sgml which puts constraints to allow data processing:
Markup should describe a document's structure and other attributes rather than specify the processing that needs to be performed, because it is less likely to conflict with future developments.
exactly the opposite of PostScript/Pdf. SGML is used in publishing. Pdf doesn't embed this semantical structure, it carries only the css-equivalent associated to plain character strings which may not be complete words or sentences. Pdf is used for closed documents and now for the so-called workflow management.
After having experimented the uncertainty and difficulty in trying to extract data from pdf, it's clear pdf is not at all a solution to preserve a document content for the future (in spite Adobe has obtained from their pairs a pdf standard).
What is actually preserved well is the printed representation, as the pdf was fully dedicated to this aspect when created. Pdf are nearly as dead as printed books.
When reusing the content matters, one must rely again on manual re-entering of data, like from a printed book (possibly trying to do some OCR on it). This is more and more true, as many pdf even prevent the use of copy-paste, introducing multiple spaces between words or produce an unordered characters gibberish when some "optimization" is done for web use.
When the content of the document, not its printed representation, is valuable, then pdf is not the correct format. Even Adobe is unable to recreate perfectly the source of a document from its pdf rendering.
So open data should never be released in pdf format, this limits their use to reading and printing (when allowed), and makes reuse harder or impossible.
Follow the below example --
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:
$(boot2docker shellinit)
I had tested these commands:
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>> boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)
...
>> $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>> docker info
Containers: 3
...
My problem was that I was trying to create a ASPX web application in a subfolder of a folder that already had a web.config file, and
So I opened up the parent folder in Visual Studio as a Web Site (Open > Web Site) I was able to add a new item ASPX page that had no issue parsing/loading.
<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>
i used static array so that while returning array it should not throw error as you are returning address of local variable... so now you can send any locally created variable from function by making it as static...as it works as global variable....
#include<iostream>
using namespace std;
char *func(int n)
{
// char a[26]; /*if we use this then an error will occur because you are
// returning address of a local variable*/
static char a[26];
char temp='A';
for(int i=0;i<n;i++)
{
a[i]=temp;temp++;
}
return a;
}
int main()
{
int n=26;
char *p=func(n);
for(int i=0;i<n;i++)
cout<<*(p+i)<<" ";
//or you can also print like this
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
}
I had the exact same problem. Here is the solution that worked for me: simply put your properties file path in the cmd line this way :
-Dlog4j.configuration=<FILE_PATH> (ex: log4j.properties)
Hope this will help you
Here are some:
"Ali".eql? "Ali"
=> true
The spaceship (<=>
) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
"Apples" <=> "Apples"
=> 0
"Apples" <=> "Pears"
=> -1
"Pears" <=> "Apples"
=> 1
A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:
"Apples".casecmp "apples"
=> 0
If you want to revert the file to its state in master
:
git checkout origin/master [filename]