I found out that with MySQL probably the correct query is the following:
SELECT SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,
'%Y-%m-%d %H:%i:%S' ) , 1, 19 ) AS ts_CEILING,
SUM(value)
FROM group_interval
GROUP BY SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,
'%Y-%m-%d %H:%i:%S' ) , 1, 19 )
ORDER BY SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,
'%Y-%m-%d %H:%i:%S' ) , 1, 19 ) DESC
Let me know what you think.
There are several ways to use gitignore git
just create a .gitignore file and write in whatever you want to ignore a sample gitignore file would be:
# NPM packages folder.
node_modules
# Build files
dist/
# lock files
yarn.lock
package-lock.json
# Logs
logs
*.log
npm-debug.log*
# node-waf configuration
.lock-wscript
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Jest Coverage
coverage
.history/
You can find more on git documentation gitignore
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:
listoflists.append((list[:], list[0]))
However, list
is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list
as a variable name, and makes a copy:
listoflists = []
a_list = []
for i in range(0,10):
a_list.append(i)
if len(a_list)>3:
a_list.remove(a_list[0])
listoflists.append((list(a_list), a_list[0]))
print listoflists
Note that I demonstrated two different ways to make a copy of a list above: [:]
and list()
.
The first, [:]
, is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.
The second, list()
, is using the actual list
type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)
Adding to @StevePenny answer, you might want to cut the not-so-human-readable part:
stat -c%y Localizable.strings | cut -d'.' -f1
Multi-programming :-
More than one task(job) process can reside into main memory at a time. It is basically design to reduce CPU wastage during I/O operation , example : if a job is executing currently and need I/O operation . I/O operation is done using DMA and processor assign to some Other job from the job queue till I/O operation of job1 completed . then job1 continue again . In this way it reduce CPU wastage .
I also occured the error,and I sloved it by removing the curly braces,hope it will help someone else.
You can see that ,I did not put the con in the curly brace,and the error occured ,when I remove the burly brace , the error disappeared.
const modal = (props) => {
const { show, onClose } = props;
let con = <div className="modal" onClick={onClose}>
{props.children}
</div>;
return show === true ? (
{con}
) : (
<div>hello</div>
);
There are an article about the usage of the curly brace.click here
I would like to add a remark to the above solutions:
All these syntaxes work perfectly well IF YOUR COMMAND IS FOUND WITHIN THE PATH or IF THE COMMAND IS A cmdpath WITHOUT SPACES OR SPECIAL CHARACTERS.
But if you try to use an executable command located in a folder which path contains special characters then you would need to enclose your command path into double quotes (") and then the FOR /F syntax does not work.
Examples:
$ for /f "tokens=* USEBACKQ" %f in (
`""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" Hello '"F:\GLW7\Distrib\System\Shells and scripting"'`
) do echo %f
The filename, directory name, or volume label syntax is incorrect.
or
$ for /f "tokens=* USEBACKQ" %f in (
`"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'F:\GLW7\Distrib\System\Shells' is not recognized as an internal or external command, operable program or batch file.
or
`$ for /f "tokens=* USEBACKQ" %f in (
`""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello' is not recognized as an internal or external command, operable program or batch file.
In that case, the only solution I found to use a command and store its result in a variable is to set (temporarily) the default directory to the one of command itself :
pushd "%~d0%~p0"
FOR /F "tokens=* USEBACKQ" %%F IN (
`FOLDERBROWSE "Hello world!" "F:\GLW7\Distrib\System\Layouts (print,display...)"`
) DO (SET MyFolder=%%F)
popd
echo My selected folder: %MyFolder%
The result is then correct:
My selected folder: F:\GLW7\Distrib\System\OS install, recovery, VM\
Press any key to continue . . .
Of course in the above example, I assume that my batch script is located in the same folder as the one of my executable command so that I can use the "%~d0%~p0" syntax. If this is not your case, then you have to find a way to locate your command path and change the default directory to its path.
NB: For those who wonder, the sample command used here (to select a folder) is FOLDERBROWSE.EXE. I found it on the web site f2ko.de (http://f2ko.de/en/cmd.php).
If anyone has a better solution for that kind of commands accessible through a complex path, I will be very glad to hear of it.
Gilles
These are all close to the right answer, but I wouldn't say any solve the problem while remaining most readable to others reading your code. I'd say that answer is a combination of BrenBarn's Answer and tuomasttik's comment below that answer. BrenBarn's answer utilizes isspace
builtin, but does not support removing empty strings, as OP requested, and I would tend to attribute that as the standard use case of replacing strings with null.
I rewrote it with .apply
, so you can call it on a pd.Series
or pd.DataFrame
.
Python 3:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and x.isspace() else x)
To use this in Python 2, you'll need to replace str
with basestring
.
Python 2:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
Instead of using a regular expression, just check if string.length > 25
Could do this, but then the user has to separate the numbers by a space:
#include "stdio.h"
int main()
{
int minx, x, y, z;
printf("Enter four ints: ");
scanf( "%i %i %i %i", &minx, &x, &y, &z);
printf("You wrote: %i %i %i %i", minx, x, y, z);
}
Package Manager console (Visual Studio, Tools > NuGet Package Manager > Package Manager Console): Run the Update-Package -reinstall -ProjectName command where is the name of the affected project as it appears in Solution Explorer. Use Update-Package -reinstall by itself to restore all packages in the solution. See Update-Package. You can also reinstall a single package, if desired.
from https://docs.microsoft.com/en-us/nuget/quickstart/restore
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
For normalize form
select e1.name as 'Manager', e2.name as 'Staff'
from employee e1
left join manage m on m.mid = e1.id
left join employee e2 on m.eid = e2.id
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Now it is possible
But you will need to have your device rom run on java 1.8 and enable "jackOptions" to run it. Jack is the name for the new Android compiler that runs Java 8
https://developer.android.com/guide/platform/j8-jack.html
add these lines to build_gradle
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Java 8 seem to be the running java engine of Android studio 2.0, But it still does not accept the syntax of java 8 after I checked, and you cannot chose a compiler from android studio now. However, you can use the scala plugin if you need functional programming mechanism in your android client.
Please see the answer by Martin Smith for a better illustations and explanations of the different joins, including and especially differences between FULL OUTER JOIN
, RIGHT OUTER JOIN
and LEFT OUTER JOIN
.
These two table form a basis for the representation of the JOIN
s below:
SELECT *
FROM citizen
CROSS JOIN postalcode
The result will be the Cartesian products of all combinations. No JOIN
condition required:
INNER JOIN
is the same as simply: JOIN
SELECT *
FROM citizen c
JOIN postalcode p ON c.postal = p.postal
The result will be combinations that satisfies the required JOIN
condition:
LEFT OUTER JOIN
is the same as LEFT JOIN
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON c.postal = p.postal
The result will be everything from citizen
even if there are no matches in postalcode
. Again a JOIN
condition is required:
All examples have been run on an Oracle 18c. They're available at dbfiddle.uk which is also where screenshots of tables came from.
CREATE TABLE citizen (id NUMBER,
name VARCHAR2(20),
postal NUMBER, -- <-- could do with a redesign to postalcode.id instead.
leader NUMBER);
CREATE TABLE postalcode (id NUMBER,
postal NUMBER,
city VARCHAR2(20),
area VARCHAR2(20));
INSERT INTO citizen (id, name, postal, leader)
SELECT 1, 'Smith', 2200, null FROM DUAL
UNION SELECT 2, 'Green', 31006, 1 FROM DUAL
UNION SELECT 3, 'Jensen', 623, 1 FROM DUAL;
INSERT INTO postalcode (id, postal, city, area)
SELECT 1, 2200, 'BigCity', 'Geancy' FROM DUAL
UNION SELECT 2, 31006, 'SmallTown', 'Snizkim' FROM DUAL
UNION SELECT 3, 31006, 'Settlement', 'Moon' FROM DUAL -- <-- Uuh-uhh.
UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space' FROM DUAL;
JOIN
and WHERE
CROSS JOIN
resulting in rows as The General Idea/INNER JOIN
:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows
Using CROSS JOIN
to get the result of a LEFT OUTER JOIN
requires tricks like adding in a NULL
row. It's omitted.
INNER JOIN
becomes a cartesian products. It's the same as The General Idea/CROSS JOIN
:
SELECT *
FROM citizen c
JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN
This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.
Using INNER JOIN
to get the result of a LEFT OUTER JOIN
also requires tricks. It's omitted.
LEFT JOIN
results in rows as The General Idea/CROSS JOIN
:
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN
LEFT JOIN
results in rows as The General Idea/INNER JOIN
:
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON c.postal = p.postal
WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode
An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.
Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.
Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.
The set A
represents the set on the left (the citizen
table) and the set B
is the set on the right (the postalcode
table) in below discussion.
Every element in both sets are matched with every element in the other set, meaning we need A
amount of every B
elements and B
amount of every A
elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that UNION
fits at all.
The rows are distinct. The UNION
is 7 rows in total. But they're incompatible for a common SQL
results set. And this is not how a CROSS JOIN
works at all:
Trying to represent it like this:
..but now it just looks like an INTERSECTION
, which it's certainly not. Furthermore there's no element in the INTERSECTION
that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:
For reference one searchable result for CROSS JOIN
s can be seen at Tutorialgateway. The INTERSECTION
, just like this one, is empty.
The value of an element depends on the JOIN
condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning id=x
is only true for one row. Once a row in table A
(citizen
) matches multiple rows in table B
(postalcode
) under the JOIN
condition, the result has the same problems as the CROSS JOIN
: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the JOIN
condition determines the placement of an element in the diagram. Looking only at the values of the JOIN
condition with the rest of the row just along for the ride:
This representation falls completely apart when using an INNER JOIN
with a ON 1 = 1
condition making it into a CROSS JOIN
.
With a self-JOIN
, the rows are in fact idential elements in both tables, but representing the tables as both A
and B
isn't very suitable. For example a common self-JOIN
condition that makes an element in A
to be matching a different element in B is ON A.parent = B.child
, making the match from A
to B
on seperate elements. From the examples that would be a SQL
like this:
SELECT *
FROM citizen c1
JOIN citizen c2 ON c1.id = c2.leader
Meaning Smith is the leader of both Green and Jensen.
Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the OUTER JOIN
can be though of as to match the empty set. But in set theory the union of any set C
and an empty set, is always just C
. The empty set adds nothing. The representation of this LEFT OUTER JOIN
is usually just showing all of A
to illustrate that rows in A
are selected regardless of whether there is a match or not from B
. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to A
:
Finding all rows from a CROSS JOIN
with Smith and postalcode on the Moon:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
AND p.area = 'Moon';
Now the Venn diagram isn't used to reflect the JOIN
. It's used only for the WHERE
clause:
..and that makes sense.
As explained an INNER JOIN
is not really an INTERSECT
. However INTERSECT
s can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This SQL
will result in the same row as the one above WHERE
, and the Venn diagram will also be the same:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
INTERSECT
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE p.area = 'Moon';
An OUTER JOIN
is not a UNION
. However UNION
work under the same conditions as INTERSECT
, resulting in a return of all results combining both SELECT
s:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
UNION
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE p.area = 'Moon';
which is equivalent to:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
OR p.area = 'Moon';
..and gives the result:
Also here a Venn diagram makes sense:
An important note is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:
SELECT *
FROM citizen
WHERE name = 'Smith'
SELECT *
FROM postalcode
WHERE area = 'Moon';
..trying to combine the results with UNION
gives a
ORA-01790: expression must have same datatype as corresponding expression
For further interest read Say NO to Venn Diagrams When Explaining JOINs and sql joins as venn diagram. Both also cover EXCEPT
.
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
This seems to do what you want (I found it on http://huddledmasses.org/powershell-find-path/):
Function Find-Path($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
## You could comment out the function stuff and use it as a script instead, with this line:
#param($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
if($(Test-Path $Path -Type $type)) {
return $path
} else {
[string[]]$paths = @($pwd);
$paths += "$pwd;$env:path".split(";")
$paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
if($paths.Length -gt 0) {
if($All) {
return $paths;
} else {
return $paths[0]
}
}
}
throw "Couldn't find a matching path of type $type"
}
Set-Alias find Find-Path
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
Run PowerShell and type:
gci -Path "C:\Program Files*\Microsoft SQL Server" -Recurse -Include "Ssms.exe" | Select -ExpandProperty FullName
I found the same issue with Tomcat version 6.026.
I used the Mysql JDBC.jar in WebAPP Library as well as in TOMCAT Lib.
To fix the above by removing the Jar from the TOMCAT lib folder.
So what I understand is that TOMCAT is handling the JDBC memory leak properly. But if the MYSQL Jdbc jar is duplicated in WebApp and Tomcat Lib, Tomcat will only be able to handle the jar present in the Tomcat Lib folder.
Reason for the error:
Column
tries to expands in vertical axis, and so does the ListView
, hence you need to constrain the height of ListView
.
Solutions
Use either Expanded
or Flexible
if you want to allow ListView
to take up entire left space in Column
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
Use SizedBox
if you want to restrict the size of ListView
to a certain height.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
Use shrinkWrap
, if your ListView
isn't too big.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
If you don't care about loading the file into memory, as of Go 1.16, you can use the os.ReadFile
and bytes.Count
functions.
package main
import (
"log"
"os"
"bytes"
)
func main() {
data, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
n := bytes.Count(data, []byte{'\n'})
fmt.Printf("input.txt has %d lines\n", n)
}
If the input field has a class name formData use this :
$(".formData").val("data")
If the input field has an id attribute name formData use this :
$("#formData").val("data")
If the input name is given use this :
$("input[name='formData']").val("data")
You can also mention the type. Then it will refer to all the inputs of that type and the given class name:
$("input[type='text'].formData").val("data")
Solved!
$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
Expanding on John La Rooy (Python - List of unique dictionaries) answer, making it a bit more flexible:
def dedup_dict_list(list_of_dicts: list, columns: list) -> list:
return list({''.join(row[column] for column in columns): row
for row in list_of_dicts}.values())
Calling Function:
sorted_list_of_dicts = dedup_dict_list(
unsorted_list_of_dicts, ['id', 'name'])
In year of 2020, these code seems to return exception as
System.Net.Mail.SmtpStatusCode.MustIssueStartTlsFirst or The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
This code is working for me.
using (SmtpClient client = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 587,
UseDefaultCredentials = false, // This require to be before setting Credentials property
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("[email protected]", "password"), // you must give a full email address for authentication
TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
EnableSsl = true // Set to avoid secure connection exception
})
{
MailMessage message = new MailMessage()
{
From = new MailAddress("[email protected]"), // sender must be a full email address
Subject = subject,
IsBodyHtml = true,
Body = "<h1>Hello World</h1>",
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.UTF8,
};
var toAddresses = recipients.Split(',');
foreach (var to in toAddresses)
{
message.To.Add(to.Trim());
}
try
{
client.Send(message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
player.timeControlStatus == AVPlayer.TimeControlStatus.playing
You have several options:
If you can, design your JSON data structure by making use of the array indexes as IDs. You can even "normalize" your JSON arrays as long as you've no problem making use of the array indexes as "primary key" and "foreign key", something like RDBMS. As such, in future, you can even do something like this:
function getParentById(childID) {
var parentObject = parentArray[childArray[childID].parentID];
return parentObject;
}
This is the solution "By Design". For your case, simply:
var nameToFind = results[idToQuery - 1].name;
Of course, if your ID format is something like "XX-0001" of which its array index is 0, then you can either do some string manipulation to map the ID; or else nothing can be done about that except through the iteration approach.
To subset by column index (to avoid typing their names) you can do
dt[, .SD, .SDcols = -c(1:3, 5L)]
result seems ok
V4 V6 V7 V8 V9 V10
1: 0.51500037 0.919066234 0.49447244 0.19564261 0.51945102 0.7238604
2: 0.36477648 0.828889808 0.04564637 0.20265215 0.32255945 0.4483778
3: 0.10853112 0.601278633 0.58363636 0.47807015 0.58061000 0.2584015
4: 0.57569100 0.228642846 0.25734995 0.79528506 0.52067802 0.6644448
5: 0.07873759 0.840349039 0.77798153 0.48699653 0.98281006 0.4480908
6: 0.31347303 0.670762371 0.04591664 0.03428055 0.35916057 0.1297684
7: 0.45374290 0.957848949 0.99383496 0.43939774 0.33470618 0.9429592
8: 0.99403107 0.009750809 0.78816609 0.34713435 0.57937680 0.9227709
9: 0.62776909 0.400467655 0.49433474 0.81536420 0.01637135 0.4942351
10: 0.10318372 0.177712847 0.27678497 0.59554454 0.29532020 0.7117959
x += 5
is not exactly the same as saying x = x + 5
in Python.
Note here:
In [1]: x = [2, 3, 4]
In [2]: y = x
In [3]: x += 7, 8, 9
In [4]: x
Out[4]: [2, 3, 4, 7, 8, 9]
In [5]: y
Out[5]: [2, 3, 4, 7, 8, 9]
In [6]: x += [44, 55]
In [7]: x
Out[7]: [2, 3, 4, 7, 8, 9, 44, 55]
In [8]: y
Out[8]: [2, 3, 4, 7, 8, 9, 44, 55]
In [9]: x = x + [33, 22]
In [10]: x
Out[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]
In [11]: y
Out[11]: [2, 3, 4, 7, 8, 9, 44, 55]
See for reference: Why does += behave unexpectedly on lists?
System.out.println
and Log.d
both go to LogCat, not the Console.
Using 'javascript:void 0' will do cause problem in IE
when you click the link, it will trigger onbeforeunload event of window !
<!doctype html>
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" >Click me!</a>
<script>
window.onbeforeunload = function() {
alert( 'oops!' );
};
</script>
</body>
</html>
edit: This was answered before the google doc's api was released. See Evan Plaice's answer and Dan Dascalescu's answer for more up-to-date information.
It looks lke you can, but it's a pain to use. It involves using the Google data API.
http://gdatatips.blogspot.com/2008/12/using-javascript-client-library-w-non.html
"The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API."
and an example of writing a gadget that interfaces with spreadsheets: http://code.google.com/apis/spreadsheets/gadgets/
It's true that the use of grep -v -e '^$' can work, however it does not remove blank lines that have 1 or more spaces in them. I found the easiest and simplest answer for removing blank lines is the use of awk. The following is a modified a bit from the awk guys above:
awk 'NF' foo.txt
But since this question is for using grep I'm going to answer the following:
grep -v '^ *$' foo.txt
Note: the blank space between the ^ and *.
Or you can use the \s to represent blank space like this:
grep -v '^\s*$' foo.txt
Slight variation on the above instructions, worked for me. (MacOS Sierra 10.12.6)
npm install -g [email protected]
rm /usr/local/bin/npm
ln -s ~/.npm-packages/bin/npm /usr/local/bin/npm
npm --version
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
List<Conversation> conversations = **jdbcTemplate**.**queryForList**(
**SQL_QUERY**,
new Object[] {userId, dateFrom, dateTo}); //placeholders values
Suppose the sql query is like
SQL_QUERY = "**select** info,count(*),IF(info is null , 'DATA' , 'NO DATA') **from** table where userId=? , dateFrom=? , dateTo=?";
**HERE userId=? , dateFrom=? , dateTo=?**
the question marks are place holders
**SQL_QUERY**,
new Object[] {userId, dateFrom, dateTo});
It will go as an object array along with the sql query
A List
isn't a real thing in Java. It's an interface, a way of defining how an object is allowed to interact with other objects. As such, it can't ever be instantiated. An ArrayList
is an implementation of the List
interface, as is a linked list, and so on. Use those instead.
With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.
You have a couple of options:
The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:
http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http
810 style = "body { background-color: white; color: black; font-family: "
811 "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812 "hr { border: 0; border-bottom: 1px dashed; }\n";
E.g., try this:
font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;
Suppose your class is called MyStudent. Here's how you define your class constructor:
Public Class MyStudent
Public StudentId As Integer
'Here's the class constructor:
Public Sub New(newStudentId As Integer)
StudentId = newStudentId
End Sub
End Class
Here's how you call it:
Dim student As New MyStudent(studentId)
Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.
Easy solution if you don't want to code manually using Google Sheets Power Tools:
From the Jinja2 template designer documentation:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
values timestampdiff (16, char(
timestamp(current timestamp + 1 year + 2 month - 3 day)-
timestamp(current timestamp)))
1
=
422
values timestampdiff (16, char(
timestamp('2012-03-08-00.00.00')-
timestamp('2011-12-08-00.00.00')))
1
=
90
---------- EDIT BY galador
SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'
EDIT
As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:
SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00
WHERE CHSTAT = '05';
<audio>
audio::-webkit-media-controls-panel
audio::-webkit-media-controls-mute-button
audio::-webkit-media-controls-play-button
audio::-webkit-media-controls-timeline-container
audio::-webkit-media-controls-current-time-display
audio::-webkit-media-controls-time-remaining-display
audio::-webkit-media-controls-timeline
audio::-webkit-media-controls-volume-slider-container
audio::-webkit-media-controls-volume-slider
audio::-webkit-media-controls-seek-back-button
audio::-webkit-media-controls-seek-forward-button
audio::-webkit-media-controls-fullscreen-button
audio::-webkit-media-controls-rewind-button
audio::-webkit-media-controls-return-to-realtime-button
audio::-webkit-media-controls-toggle-closed-captions-button
You can add color in the style rule of your input: color:#ccc;
Use modulo
whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use
if (j % 4 == 0)
Upgrade to latest Angular 5
Angular Dep packages:
npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router}@latest --save
Other packages that are installed by the angular cli
npm install --save core-js@latest rxjs@latest zone.js@latest
Angular Dev packages:
npm install --save-dev @angular/{compiler-cli,cli,language-service}@latest
Types Dev packages:
npm install --save-dev @types/{jasmine,jasminewd2,node}@latest
Other packages that are installed as dev dev by the angular cli:
npm install --save-dev codelyzer@latest jasmine-core@latest jasmine-spec-reporter@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-coverage-istanbul-reporter@latest karma-jasmine@latest karma-jasmine-html-reporter@latest protractor@latest ts-node@latest tslint@latest
Install the latest supported version used by the Angular cli (don't do @latest):
npm install --save-dev [email protected]
Rename file angular-cli.json to .angular-cli.json and update the content:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "project3-example"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
In add_argument()
, type
is just a callable object that receives string and returns option value.
import ast
def arg_as_list(s):
v = ast.literal_eval(s)
if type(v) is not list:
raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s))
return v
def foo():
parser.add_argument("--list", type=arg_as_list, default=[],
help="List of values")
This will allow to:
$ ./tool --list "[1,2,3,4]"
Here's a cleaner way using the PackageManager
final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Log.d(TAG, "Installed package :" + packageInfo.packageName);
Log.d(TAG, "Source dir : " + packageInfo.sourceDir);
Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));
}
// the getLaunchIntentForPackage returns an intent that you can use with startActivity()
More info here http://qtcstation.com/2011/02/how-to-launch-another-app-from-your-app/
If you don't need in a complete reference to the most part of algorithms and data structures that are in use and just want to get acquainted with common techniques I would recommend something more lightweight than Cormen, Sedgewick or Knuth. I think, Algorithms and Data Structures by N. Wirth is not as bad choice even in spite of it was printed far ago.
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As @Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
I just coded a benchmark and tested the first 3 answers.
It seems that for short strings (<500 characters)
the third most voted answer is faster than the second most voted one.
For long strings (add ".repeat(300)" to the test string) the faster is answer 1 followed by the second and the third.
Note:
The above is true for browsers using v8 engine (chrome/chromium etc).
With firefox (SpiderMonkey engine) the results are totally different
Check for yourselves!! Firefox with the third solution seems to be
more than 4.5 times faster than Chrome with the first solution... crazy :D
function log(data) {_x000D_
document.getElementById("log").textContent += data + "\n";_x000D_
}_x000D_
_x000D_
benchmark = (() => {_x000D_
_x000D_
time_function = function(ms, f, num) {_x000D_
var z;_x000D_
var t = new Date().getTime();_x000D_
for (z = 0;_x000D_
((new Date().getTime() - t) < ms); z++) f(num);_x000D_
return (z / ms)_x000D_
} // returns how many times the function was run in "ms" milliseconds._x000D_
_x000D_
_x000D_
function benchmark() {_x000D_
function compare(a, b) {_x000D_
if (a[1] > b[1]) {_x000D_
return -1;_x000D_
}_x000D_
if (a[1] < b[1]) {_x000D_
return 1;_x000D_
}_x000D_
return 0;_x000D_
}_x000D_
_x000D_
// functions_x000D_
_x000D_
function replace1(s) {_x000D_
s.replace(/foo/g, "bar")_x000D_
}_x000D_
_x000D_
String.prototype.replaceAll2 = function(_f, _r){ _x000D_
_x000D_
var o = this.toString();_x000D_
var r = '';_x000D_
var s = o;_x000D_
var b = 0;_x000D_
var e = -1;_x000D_
// if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }_x000D_
_x000D_
while((e=s.indexOf(_f)) > -1)_x000D_
{_x000D_
r += o.substring(b, b+e) + _r;_x000D_
s = s.substring(e+_f.length, s.length);_x000D_
b += e+_f.length;_x000D_
}_x000D_
_x000D_
// Add Leftover_x000D_
if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }_x000D_
_x000D_
// Return New String_x000D_
return r;_x000D_
};_x000D_
_x000D_
String.prototype.replaceAll = function(str1, str2, ignore) {_x000D_
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);_x000D_
}_x000D_
_x000D_
function replace2(s) {_x000D_
s.replaceAll("foo", "bar")_x000D_
}_x000D_
_x000D_
function replace3(s) {_x000D_
s.split('foo').join('bar');_x000D_
}_x000D_
_x000D_
function replace4(s) {_x000D_
s.replaceAll2("foo", "bar")_x000D_
}_x000D_
_x000D_
_x000D_
funcs = [_x000D_
[replace1, 0],_x000D_
[replace2, 0],_x000D_
[replace3, 0],_x000D_
[replace4, 0]_x000D_
];_x000D_
_x000D_
funcs.forEach((ff) => {_x000D_
console.log("Benchmarking: " + ff[0].name);_x000D_
ff[1] = time_function(2500, ff[0], "foOfoobarBaR barbarfoobarf00".repeat(10));_x000D_
console.log("Score: " + ff[1]);_x000D_
_x000D_
})_x000D_
return funcs.sort(compare);_x000D_
}_x000D_
_x000D_
return benchmark;_x000D_
})()_x000D_
log("Starting benchmark...\n");_x000D_
res = benchmark();_x000D_
console.log("Winner: " + res[0][0].name + " !!!");_x000D_
count = 1;_x000D_
res.forEach((r) => {_x000D_
log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");_x000D_
});_x000D_
log("\nWinner code:\n");_x000D_
log(res[0][0].toString());
_x000D_
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>
_x000D_
The test will run for 10s (+2s) as you click the button.
My results (on the same pc):
Chrome/Linux Ubuntu 64:
1. replace1 score: 100% *winner* (766.18)
2. replace4 score: 99.07% speed of winner. (759.11)
3. replace3 score: 68.36% speed of winner. (523.83)
4. replace2 score: 59.35% speed of winner. (454.78)
Firefox/Linux Ubuntu 64
1. replace3 score: 100% *winner* (3480.1)
2. replace1 score: 13.06% speed of winner. (454.83)
3. replace4 score: 9.4% speed of winner. (327.42)
4. replace2 score: 4.81% speed of winner. (167.46)
Nice mess uh?
Took the liberty of adding more test results
Chrome/Windows 10
1. replace1 score: 100% *winner* (742.49)
2. replace4 score: 85.58% speed of winner. (635.44)
3. replace2 score: 54.42% speed of winner. (404.08)
4. replace3 score: 50.06% speed of winner. (371.73)
Firefox/Windows 10
1. replace3 score: 100% *winner* (2645.18)
2. replace1 score: 30.77% speed of winner. (814.18)
3. replace4 score: 22.3% speed of winner. (589.97)
4. replace2 score: 12.51% speed of winner. (331.13)
Edge/Windows 10
1. replace1 score: 100% *winner* (1251.24)
2. replace2 score: 46.63% speed of winner. (583.47)
3. replace3 score: 44.42% speed of winner. (555.92)
4. replace4 score: 20% speed of winner. (250.28)
Chrome on Galaxy Note 4
1. replace4 score: 100% *winner* (99.82)
2. replace1 score: 91.04% speed of winner. (90.88)
3. replace3 score: 70.27% speed of winner. (70.15)
4. replace2 score: 38.25% speed of winner. (38.18)
Here's an approach which uses a gradient to fake the line. It works with multiline strikes and doesn't need additional DOM elements. But as it's a background gradient, it's behind the text...
del, strike {
text-decoration: none;
line-height: 1.4;
background-image: -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.63em, transparent), color-stop(0.63em, #ff0000), color-stop(0.7em, #ff0000), color-stop(0.7em, transparent), to(transparent));
background-image: -webkit-linear-gradient(top, transparent 0em, transparent 0.63em, #ff0000 0.63em, #ff0000 0.7em, transparent 0.7em, transparent 1.4em);
background-image: -o-linear-gradient(top, transparent 0em, transparent 0.63em, #ff0000 0.63em, #ff0000 0.7em, transparent 0.7em, transparent 1.4em);
background-image: linear-gradient(to bottom, transparent 0em, transparent 0.63em, #ff0000 0.63em, #ff0000 0.7em, transparent 0.7em, transparent 1.4em);
-webkit-background-size: 1.4em 1.4em;
background-size: 1.4em 1.4em;
background-repeat: repeat;
}
See fiddle: http://jsfiddle.net/YSvaY/
Gradient color-stops and background size depend on line-height. (I used LESS for calculation and Autoprefixer afterwards...)
Applying the DRY principle to Omar's solution, here's an HTML Helper extension:
using System.Web.Mvc;
using System.Text.RegularExpressions;
namespace System.Web.Mvc.Html {
public static class MyHtmlHelpers {
public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
}
}
}
Usage (with improved regex):
@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")
This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.
My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.
$query = $this->db
->get_where('orders',array('order_date <='=>$first_date,'order_date >='=>$second_date))
->result_array();
This is my version, quite similar to the upper one, but I think good for reference.
if (mob_url == "") {
lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
lt_url = mob_url;
} else {
lt_url = desk_url;
}
You can cast a double to a decimal like this, without needing the M
literal suffix:
double dbl = 1.2345D;
decimal dec = (decimal) dbl;
You should use the M
when declaring a new literal decimal value:
decimal dec = 123.45M;
(Without the M
, 123.45 is treated as a double and will not compile.)
You have a class on your CSS that is overwriting your width and height, the class reads as such:
.postItem img {
height: auto;
width: 450px;
}
Remove that and your width/height properties on the img
tag should work.
If your compiler supports C++0x and using it is an option for you, then the new standard <random>
header is likely to meet your needs. It has a high quality uniform_int_distribution
which will accept minimum and maximum bounds (inclusive as you need), and you can choose among various random number generators to plug into that distribution.
Here is code that generates a million random int
s uniformly distributed in [-57, 365]. I've used the new std <chrono>
facilities to time it as you mentioned performance is a major concern for you.
#include <iostream>
#include <random>
#include <chrono>
int main()
{
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::duration<double> sec;
Clock::time_point t0 = Clock::now();
const int N = 10000000;
typedef std::minstd_rand G;
G g;
typedef std::uniform_int_distribution<> D;
D d(-57, 365);
int c = 0;
for (int i = 0; i < N; ++i)
c += d(g);
Clock::time_point t1 = Clock::now();
std::cout << N/sec(t1-t0).count() << " random numbers per second.\n";
return c;
}
For me (2.8 GHz Intel Core i5) this prints out:
2.10268e+07 random numbers per second.
You can seed the generator by passing in an int to its constructor:
G g(seed);
If you later find that int
doesn't cover the range you need for your distribution, this can be remedied by changing the uniform_int_distribution
like so (e.g. to long long
):
typedef std::uniform_int_distribution<long long> D;
If you later find that the minstd_rand
isn't a high enough quality generator, that can also easily be swapped out. E.g.:
typedef std::mt19937 G; // Now using mersenne_twister_engine
Having separate control over the random number generator, and the random distribution can be quite liberating.
I've also computed (not shown) the first 4 "moments" of this distribution (using minstd_rand
) and compared them to the theoretical values in an attempt to quantify the quality of the distribution:
min = -57
max = 365
mean = 154.131
x_mean = 154
var = 14931.9
x_var = 14910.7
skew = -0.00197375
x_skew = 0
kurtosis = -1.20129
x_kurtosis = -1.20001
(The x_
prefix refers to "expected")
Sohnee solutions is cleaner, but you can also try
window["bootbox"]
You have to use double double quotes to escape the double quotes (lol):
g = "abcd """ & a & """"
No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:
NOTE: remove any duplicates from the individual columns first!
Duplicates are now highlighted in red
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
when your assembly version and your Visual studio project Biuld setting on dot net 2 or 4 install with same version.
install service with installutil
that same version
if build in dot net 4
Type c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe
if build in dot net 2
Type c:\windows\microsoft.net\framework\v2.0.11319\installutil.exe
If you using windows authentication make sure that password of the user hasn't expired. An expired password can explain this error. This was the problem in my case.
Another option:
>>> import os, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')
['manage.py']
Here you go:
div{
display: none;
}
document.querySelector("button").addEventListener("click", function(){
document.querySelector("div").style.display = "block";
});
<div>blah blah blah</div>
<button>Show</button>
LIVE DEMO: http://jsfiddle.net/DerekL/p78Qq/
function drawDataURIOnCanvas(strDataURI, canvas) {
"use strict";
var img = new window.Image();
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0);
});
img.setAttribute("src", strDataURI);
}
Introduced in numpy 1.8:
Return a new array of given shape and type, filled with fill_value.
Examples:
>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf, inf],
[ inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
[10, 10]])
I would exploit the retransmission behaviour of TCP.
This assumes some kind of benefit of buckets or multiple passes.
Probably by sorting the batches/buckets and merging them. -> radix trees
Use this technique to accept and sort the first 80% then read the last 20%, verify that the last 20% do not contain numbers that would land in the first 20% of the lowest numbers. Then send the 20% lowest numbers, remove from memory, accept the remaining 20% of new numbers and merge.**
while True mean infinite loop, this usually use by long process. you can change
while True:
with
while 1:
std::move
?A: std::move()
is a function from the C++ Standard Library for casting to a rvalue reference.
Simplisticly std::move(t)
is equivalent to:
static_cast<T&&>(t);
An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.
int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
int b = a; // a is a lvalue, keeps existing after expression is evaluated
An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:
template <class T>
typename remove_reference<T>::type&&
std::move(T&& a)
{
return a;
}
As you can see, std::move
returns T&&
no matter if called with a value (T
), reference type (T&
), or rvalue reference (T&&
).
A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.
foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)
int a = 3 * 5;
foo(a); // how to tell the compiler to treat `a` as an rvalue?
foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`
What it does not do:
A: You should use std::move
if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).
This begs the following follow-up questions for me:
What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.
What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.
Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.
In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged.
This is probably the best answer, keeping in mind the cross browser issues.
CSS:
#file {
opacity: 0;
width: 1px;
height: 1px;
}
JS:
$(".file-upload").on('click',function(){
$("[name='file']").click();
});
HTML:
<a class="file-upload">Upload</a>
<input type="file" name="file">
I think the $() syntax is easier to read...
variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')
But the real issue is probably that $12
should not be qouted with ""
Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef
is and what is expected in variable.
UPDATE
Bootstrap 4 has spacing utilities to handle this https://getbootstrap.com/docs/4.0/utilities/spacing/
.mt-0 {
margin-top: 0 !important;
}
--
ORIGINAL ANSWER
If you are using SASS, this is what I normally do.
$margins: (xs: 0.5rem, sm: 1rem, md: 1.5rem, lg: 2rem, xl: 2.5rem);
@each $name, $value in $margins {
.margin-top-#{$name} {
margin-top: $value;
}
.margin-bottom-#{$name} {
margin-bottom: $value;
}
}
so you can later use margin-top-xs
for example
When connect to https
I got this error too, I add this line before HttpClient httpClient = new HttpClient();
and connect successfully:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
I know it from This Answer and Another Similar Anwser and the comment mentions:
This is a hack useful in development so putting a #if DEBUG #endif statement around it is the least you should do to make this safer and stop this ending up in production
Besides, I didn't try the method in Another Answer that use new X509Certificate()
or new X509Certificate2()
to make a Certificate, I'm not sure simply create by new()
will work or not.
EDIT: Some References:
Create a Self-Signed Server Certificate in IIS 7
Import and Export SSL Certificates in IIS 7
Best practices for using ServerCertificateValidationCallback
I find value of Thumbprint is equal to x509certificate.GetCertHashString()
:
From Oracle (but works in most SQL DBs):
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
HAVING COUNT(*) >= 3
P.S. it's faster one, because you have no Select withing Select methods here
I like Maxim's observation that DOS attacks can exhaust server resources. It also happens without an actually malicious adversary.
Some servers have to deal with the 'unintentional DOS attack' which occurs when the client app has a bug with connection leak, where they keep creating a new connection for every new command they send to your server. And then perhaps eventually closing their connections if they hit GC pressure, or perhaps the connections eventually time out.
Another scenario is when 'all clients have the same TCP address' scenario. Then client connections are distinguishable only by port numbers (if they connect to a single server). And if clients start rapidly cycling opening/closing connections for any reason they can exhaust the (client addr+port, server IP+port) tuple-space.
So I think servers may be best advised to switch to the Linger-Zero strategy when they see a high number of sockets in the TIME_WAIT state - although it doesn't fix the client behavior, it might reduce the impact.
solution is based on these things:
what does it do:
when first time toolbar is executing #setTitle, it creates AppCompatTextView and uses it to display title text.
when the AppCompatTextView is created, toolbar (as ViewGroup), adds it into it's own hierarchy with #addView method.
also, while trying to find solution i noticed that the textview has layout width set to "wrap_content", so i decided to make it "match_parent" and assign textalignment to "center".
MyToolbar.kt, skipping unrelated stuff (constructors/imports):
class MyToolbar : Toolbar {
override fun addView(child: View, params: ViewGroup.LayoutParams) {
if (child is TextView) {
params.width = ViewGroup.LayoutParams.MATCH_PARENT
child.textAlignment= View.TEXT_ALIGNMENT_CENTER
}
super.addView(child, params)
}
}
possible "side effects" - this will apply to "subtitle" too
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
I just discovered that the Mock library provides an assertRaisesWithMessage() method (in its unittest.TestCase subclass), which will check not only that the expected exception is raised, but also that it is raised with the expected message:
from testcase import TestCase
import mymod
class MyTestCase(TestCase):
def test1(self):
self.assertRaisesWithMessage(SomeCoolException,
'expected message',
mymod.myfunc)
I used this code:
Gson gson = new Gson();
HashMap<String, Object> fields = gson.fromJson(json, HashMap.class);
In case you also need to check if nextProps.blog
is not undefined
; you can do that in a single if
statement, like this:
if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
//
}
And, when an undefined
, empty
or null
value is not expected; you can make it more concise:
if (nextProps.blog && nextProps.blog.content) {
//
}
If an exception occurs in a thread, the best way is to re-raise it in the caller thread during join
. You can get information about the exception currently being handled using the sys.exc_info()
function. This information can simply be stored as a property of the thread object until join
is called, at which point it can be re-raised.
Note that a Queue.Queue
(as suggested in other answers) is not necessary in this simple case where the thread throws at most 1 exception and completes right after throwing an exception. We avoid race conditions by simply waiting for the thread to complete.
For example, extend ExcThread
(below), overriding excRun
(instead of run
).
Python 2.x:
import threading
class ExcThread(threading.Thread):
def excRun(self):
pass
def run(self):
self.exc = None
try:
# Possibly throws an exception
self.excRun()
except:
import sys
self.exc = sys.exc_info()
# Save details of the exception thrown but don't rethrow,
# just complete the function
def join(self):
threading.Thread.join(self)
if self.exc:
msg = "Thread '%s' threw an exception: %s" % (self.getName(), self.exc[1])
new_exc = Exception(msg)
raise new_exc.__class__, new_exc, self.exc[2]
Python 3.x:
The 3 argument form for raise
is gone in Python 3, so change the last line to:
raise new_exc.with_traceback(self.exc[2])
System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.
See Also:
The SQLite command line utility has a .schema TABLENAME
command that shows you the create statements.
Try dir /b
, for bare format.
dir /?
will show you documentation of what you can do with the dir
command. Here is the output from my Windows 7 machine:
C:\>dir /?
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years
Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.
To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper
directly, or make use of the @JsonInclude
annotation:
mapper.setSerializationInclusion(Include.NON_NULL);
or:
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Alternatively, you could use @JsonInclude
in a getter so that the attribute would be shown if the value is not null.
A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
Take screenshot of a view in android.
public static Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
MongoDB has a simple web based administrative port at 28017 by default.
There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.
To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.
If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.
LocalDateTime.parse( // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
"2014/10/29 18:10:45" // Convert input string to comply with standard ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE in the middle with a `T`.
.replace( "/" , "-" ) // Replace SLASH in the middle with a `-`.
)
.atZone( // Apply a time zone to provide the context needed to determine an actual moment.
ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust into UTC.
.toEpochMilli() // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.
1414602645000
The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?
Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo"
. Avoid the 3 or 4 letter codes which are neither standardized nor unique.
The modern approach uses the java.time classes.
Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T
. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime
, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime
has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.
ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Now we have a specific moment, in that ZonedDateTime
. Convert to UTC by extracting a Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = zdt.toInstant() ;
Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.
long millisSinceEpoch = instant.toEpochMilli() ;
Be aware of possible data loss. The Instant
object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.
Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.
The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.
Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T
. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.
String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();
Ctrl+Shift+P
on Windows or Command+Shift+P
on MacFirst run:
rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
Then run the command
npm install cross-env
npm install
and then you can also run
npm run dev
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
Another option if you do not know if the modal has already been opened or not yet and you need to configure the modal options:
Bootstrap 3.4
var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal
if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
$modal.modal({
keyboard: keyboard,
backdrop: backdrop
});
} else { // Modal has already been opened
$modal.data('bs.modal').options.keyboard = keyboard;
$modal.data('bs.modal').options.backdrop = backdrop;
if(keyboard === false) {
$modal.off('keydown.dismiss.bs.modal'); // Disable ESC
} else { //
$modal.data('bs.modal').escape(); // Resets ESC
}
}
Bootstrap 4.3+
var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal
if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
$modal.modal({
keyboard: keyboard,
backdrop: backdrop
});
} else { // Modal has already been opened
$modal.data('bs.modal')._config.keyboard = keyboard;
$modal.data('bs.modal')._config.backdrop = backdrop;
if(keyboard === false) {
$modal.off('keydown.dismiss.bs.modal'); // Disable ESC
} else { //
$modal.data('bs.modal').escape(); // Resets ESC
}
}
Change options to _config
For the TL;DR, here are 2 cents and a simpler version for your questions:
WebSockets provides these benefits over HTTP:
WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.
if you need to do it more often , you can even create your own method for pop the last element; something like this:
public void pop(List<string> myList) {
myList.RemoveAt(myList.Count - 1);
}
or even instead of void you can return the value like:
public string pop (List<string> myList) {
// first assign the last value to a seperate string
string extractedString = myList(myList.Count - 1);
// then remove it from list
myList.RemoveAt(myList.Count - 1);
// then return the value
return extractedString;
}
just notice that the second method's return type is not void , it is string b/c we want that function to return us a string ...
According to the documentation for 3.4, It is preferred to use attributes with attr()
method.
$('<div></div>').attr(
{
id: 'some dynanmic|static id',
"class": 'some dynanmic|static class'
}
).click(function() {
$( "span", this ).addClass( "bar" ); // example from the docs
});
Your'e almost there, you just need to get the properties from the type, rather than expect the properties to be accessible in the form of a collection or property bag:
var property in obj.GetType().GetProperties()
From there you can access like so:
property.Name
property.GetValue(obj, null)
With GetValue
the second parameter will allow you to specify index values, which will work with properties returning collections - since a string is a collection of chars, you can also specify an index to return a character if needs be.
For those struggling with this in Swift. This is the accepted answer by Jensen2k but in Swift.
Swift 2.3
override func viewDidLoad() {
//.....
let viewTapGestureRec = UITapGestureRecognizer(target: self, action: #selector(handleViewTap(_:)))
//this line is important
viewTapGestureRec.cancelsTouchesInView = false
self.view.addGestureRecognizer(viewTapGestureRec)
//.....
}
func handleViewTap(recognizer: UIGestureRecognizer) {
myTextField.resignFirstResponder()
}
Markdown doesn't have a defined syntax to underline text.
I guess this is because underlined text is hard to read, and that it's usually used for hyperlinks.
The scalar formatter supports collecting the exponents. The docs are as follows:
class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter
Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.
your technique would be:
from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3)) # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)
To get the exponent displayed in the format x10^5
, instantiate the ScalarFormatter with useMathText=True
.
You could also use:
xfmt.set_useOffset(10000)
To get a result like this:
If you have to disable SSL checks for one git server hosting several repositories, you can run :
git config --bool --add http.https://my.bad.server.sslverify false
This will add it to your user's configuration.
Command to check:
git config --bool --get-urlmatch http.sslverify https://my.bad.server
(If you still use git < v1.8.5, run git config --global http.https://my.bad.server.sslVerify false
)
Explanation from the documentation where the command is at the end, show the
.gitconfig
content looking like:
[http "https://my.bad.server"]
sslVerify = false
It will ignore any certificate checks for this server, whatever the repository.
You also have some explanation in the code
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
Static and final have some big differences:
Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:
public class Test{
public final int first = 10;
public static int second = 20;
public Test(){
second = second + 1
first = first + 1;
}
}
The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.
Linux minimal runnable examples with disassembly analysis
Since this is an implementation detail not specified by standards, let's just have a look at what the compiler is doing on a particular implementation.
In this answer, I will either link to specific answers that do the analysis, or provide the analysis directly here, and summarize all results here.
All of those are in various Ubuntu / GCC versions, and the outcomes are likely pretty stable across versions, but if we find any variations let's specify more precise versions.
Local variable inside a function
Be it main
or any other function:
void f(void) {
int my_local_var;
}
As shown at: What does <value optimized out> mean in gdb?
-O0
: stack-O3
: registers if they don't spill, stack otherwiseFor motivation on why the stack exists see: What is the function of the push / pop instructions used on registers in x86 assembly?
Global variables and static
function variables
/* BSS */
int my_global_implicit;
int my_global_implicit_explicit_0 = 0;
/* DATA */
int my_global_implicit_explicit_1 = 1;
void f(void) {
/* BSS */
static int my_static_local_var_implicit;
static int my_static_local_var_explicit_0 = 0;
/* DATA */
static int my_static_local_var_explicit_1 = 1;
}
0
or not initialized (and therefore implicitly initialized to 0
): .bss
section, see also: Why is the .bss segment required?.data
sectionchar *
and char c[]
As shown at: Where are static variables stored in C and C++?
void f(void) {
/* RODATA / TEXT */
char *a = "abc";
/* Stack. */
char b[] = "abc";
char c[] = {'a', 'b', 'c', '\0'};
}
TODO will very large string literals also be put on the stack? Or .data
? Or does compilation fail?
Function arguments
void f(int i, int j);
Must go through the relevant calling convention, e.g.: https://en.wikipedia.org/wiki/X86_calling_conventions for X86, which specifies either specific registers or stack locations for each variable.
Then as shown at What does <value optimized out> mean in gdb?, -O0
then slurps everything into the stack, while -O3
tries to use registers as much as possible.
If the function gets inlined however, they are treated just like regular locals.
const
I believe that it makes no difference because you can typecast it away.
Conversely, if the compiler is able to determine that some data is never written to, it could in theory place it in .rodata
even if not const.
TODO analysis.
Pointers
They are variables (that contain addresses, which are numbers), so same as all the rest :-)
malloc
The question does not make much sense for malloc
, since malloc
is a function, and in:
int *i = malloc(sizeof(int));
*i
is a variable that contains an address, so it falls on the above case.
As for how malloc works internally, when you call it the Linux kernel marks certain addresses as writable on its internal data structures, and when they are touched by the program initially, a fault happens and the kernel enables the page tables, which lets the access happen without segfaul: How does x86 paging work?
Note however that this is basically exactly what the exec
syscall does under the hood when you try to run an executable: it marks pages it wants to load to, and writes the program there, see also: How does kernel get an executable binary file running under linux? Except that exec
has some extra limitations on where to load to (e.g. is the code is not relocatable).
The exact syscall used for malloc
is mmap
in modern 2020 implementations, and in the past brk
was used: Does malloc() use brk() or mmap()?
Dynamic libraries
Basically get mmap
ed to memory: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710
envinroment variables and main
's argv
Above initial stack: https://unix.stackexchange.com/questions/75939/where-is-the-environment-string-actual-stored TODO why not in .data?
alternatively include event.preventDefault(); in your handleSubmit(event) {
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
One simple line in base R:
df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]
Same in two lines, for clarity/efficiency:
fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]
Use the jquery numeric value. Below function allows for decimal and numeric values.
Example:
$("#inputId").numeric({ allow: "." });
With File::Slurp:
use File::Slurp;
my $text = read_file('index.html');
It would appear that as of now (April of 2017) that the following works:
public string LoggedInUser => User.Identity.Name;
At least while within a Controller
Another flexible way using classpath containing fat jar (-cp fat.jar) or all jars (-cp "$JARS_DIR/*") and another custom config classpath or folder containing configuration files usually elsewhere and outside jar. So instead of the limited java -jar, use the more flexible classpath way as follows:
java \
-cp fat_app.jar \
-Dloader.path=<path_to_your_additional_jars or config folder> \
org.springframework.boot.loader.PropertiesLauncher
See Spring-boot executable jar doc and this link
If you do have multiple MainApps which is common, you can use How do I tell Spring Boot which main class to use for the executable jar?
You can add additional locations by setting an environment variable LOADER_PATH or loader.path in loader.properties (comma-separated list of directories, archives, or directories within archives). Basically loader.path works for both java -jar or java -cp way.
And as always you can override and exactly specify the application.yml it should pickup for debugging purpose
--spring.config.location=/some-location/application.yml --debug
Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?
Yes.
Create the .o (as per normal):
g++ -c header.cpp
Create the archive:
ar rvs header.a header.o
Test:
g++ test.cpp header.a -o executable_name
Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:
g++ test.cpp header.cpp -o executable_name
Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.
Hope this helps!
I'm just speculating:
I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:
int *doubleDigits;
And then allocate the space for it in the init-method:
@synthesize doubleDigits;
- (id)init {
if (self = [super init]) {
doubleDigits = malloc(sizeof(int) * 10);
/*
* This works, but is dangerous (forbidden) because bufferDoubleDigits
* gets deleted at the end of -(id)init because it's on the stack:
* int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
* [self setDoubleDigits:bufferDoubleDigits];
*
* If you want to be on the safe side use memcpy() (needs #include <string.h>)
* doubleDigits = malloc(sizeof(int) * 10);
* int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
* memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
*/
}
return self;
}
- (void)dealloc {
free(doubleDigits);
[super dealloc];
}
In this case the interface looks like this:
@interface MyClass : NSObject {
int *doubleDigits;
}
@property int *doubleDigits;
Edit:
I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)
int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.
Using xml-config it would go like this:
<bean id="foo-readers" scope="step"
class="...MyReader">
<property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>
See further at the Spring Batch documentation.
Perhaps it works by using @Scope
and defining the step scope in your xml-config:
<bean class="org.springframework.batch.core.scope.StepScope" />
You need to call the AddAddress
method once for every recipient. Like so:
$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..
Better yet, add them as Carbon Copy recipients.
$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
If you have a list of columns you want to concatenate and maybe you'd like to use some separator, here's what you can do
def concat_columns(df, cols_to_concat, new_col_name, sep=" "):
df[new_col_name] = df[cols_to_concat[0]]
for col in cols_to_concat[1:]:
df[new_col_name] = df[new_col_name].astype(str) + sep + df[col].astype(str)
This should be faster than apply
and takes an arbitrary number of columns to concatenate.
-None of the above consistently worked for me. So here is the solution i worked out that works consistently across all browsers as it uses basic functionality. Hope this may help others. Using jQuery 8.2
1) Get the jquery object for "span". 2) Get the DOM object from above. Using jquery .get(0) 3) Using DOM's object's innerText get the text.
Here is a simple example
var curSpan = $(this).parent().children(' span').get(0);
var spansText = curSpan.innerText;
HTML
<div >
<input type='checkbox' /><span >testinput</span>
</div>
<embed src="silence.mp3" type="audio/mp3" autostart="true" hidden="true">
<audio id="player" autoplay controls><source src="source/audio.mp3" type="audio/mp3"></audio>
With this solution, the open/save dialog of Internet Explorer is also avoided.
<embed src="http://deinesv.cf/silence.mp3" type="audio/mp3" autostart="true" hidden="true">
<audio id="player" autoplay controls><source src="https://freemusicarchive.org/file/music/ccCommunity/Mild_Wild/a_Alright_Okay_b_See_Through/Mild_Wild_-_Alright_Okay.mp3" type="audio/mp3"></audio>
_x000D_
In a rails 5.1 app, I use this core extension built on top of ActiveRecord::Type::Boolean
. It is working perfectly for me when I deserialize boolean from JSON string.
https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
# app/lib/core_extensions/string.rb
module CoreExtensions
module String
def to_bool
ActiveRecord::Type::Boolean.new.deserialize(downcase.strip)
end
end
end
initialize core extensions
# config/initializers/core_extensions.rb
String.include CoreExtensions::String
rspec
# spec/lib/core_extensions/string_spec.rb
describe CoreExtensions::String do
describe "#to_bool" do
%w[0 f F false FALSE False off OFF Off].each do |falsey_string|
it "converts #{falsey_string} to false" do
expect(falsey_string.to_bool).to eq(false)
end
end
end
end
Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.
SELECT COUNT(id) FROM users; #id is the primary key
Then, get a random twenty rows.
$start_row = mt_rand(0, $total_rows - 20);
The final query:
SELECT * FROM users ORDER BY name ASC LIMIT $start_row, 20;
A rework of impementation by @D'Nabre for C++. Don't forget to compile with -lcrypto at the end: gcc md5.c -o md5 -lcrypto
.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <openssl/md5.h>
using namespace std;
unsigned char result[MD5_DIGEST_LENGTH];
// function to print MD5 correctly
void printMD5(unsigned char* md, long size = MD5_DIGEST_LENGTH) {
for (int i=0; i<size; i++) {
cout<< hex << setw(2) << setfill('0') << (int) md[i];
}
}
int main(int argc, char *argv[]) {
if(argc != 2) {
cout << "Specify the file..." << endl;
return 0;
}
ifstream::pos_type fileSize;
char * memBlock;
ifstream file (argv[1], ios::ate);
//check if opened
if (file.is_open() ) { cout<< "Using file\t"<< argv[1]<<endl; }
else {
cout<< "Unnable to open\t"<< argv[1]<<endl;
return 0;
}
//get file size & copy file to memory
//~ file.seekg(-1,ios::end); // exludes EOF
fileSize = file.tellg();
cout << "File size \t"<< fileSize << endl;
memBlock = new char[fileSize];
file.seekg(0,ios::beg);
file.read(memBlock, fileSize);
file.close();
//get md5 sum
MD5((unsigned char*) memBlock, fileSize, result);
//~ cout << "MD5_DIGEST_LENGTH = "<< MD5_DIGEST_LENGTH << endl;
printMD5(result);
cout<<endl;
return 0;
}
I found three fixes:
This:
var bootstrapButton = $.fn.button.noConflict();
$.fn.bootstrapBtn = bootstrapButton;
helps. But other buttons look terrible. And now we don't have bootstrap buttons.
I just want to use bootsrap styles and also I want to have close button with an icon. I've done following:
How close button looks after fix
.ui-dialog-titlebar-close {
padding:0 !important;
}
.ui-dialog-titlebar-close:after {
content: '';
width: 20px;
height: 20px;
display: inline-block;
/* Change path to image*/
background-image: url(themes/base/images/ui-icons_777777_256x240.png);
background-position: -96px -128px;
background-repeat: no-repeat;
}
You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.
To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator
property of the current culture's NumberFormatInfo
.
Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString()
to output the format you want, without worrying about changing the culture each time you output a number.
(Note that a neutral culture cannot have its decimal separator changed.)
Please use this command and try :
redis-cli --raw keys "$PATTERN" | xargs redis-cli del
Try this:
foreach($array as $k => $obj) {
$obj->{'newKey'} = "value";
}
You separate the values you want to return by commas:
def get_name():
# you code
return first_name, last_name
The commas indicate it's a tuple, so you could wrap your values by parentheses:
return (first_name, last_name)
Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas
name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
Within your app theme you can set the android:itemBackground property to change the color of the action menu.
For example:
<style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">_x000D_
<item name="colorPrimary">@color/drk_colorPrimary</item>_x000D_
<item name="colorPrimaryDark">@color/drk_colorPrimaryDark</item>_x000D_
<item name="colorAccent">@color/drk_colorAccent</item>_x000D_
<item name="actionBarStyle">@style/NoTitle</item>_x000D_
<item name="windowNoTitle">true</item>_x000D_
<item name="android:textColor">@color/white</item>_x000D_
_x000D_
<!-- THIS IS WHERE YOU CHANGE THE COLOR -->_x000D_
<item name="android:itemBackground">@color/drk_colorPrimary</item>_x000D_
</style>
_x000D_
I guess that this code should answer your question:
use strict;
use warnings;
my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
$hash{$key}++;
}
for my $key (keys %hash)
{
print "$key: ", $hash{$key}, "\n";
}
Output:
three: 1
one: 1
two: 2
The iteration can be simplified to:
$hash{$_}++ for (@keys);
(See $_
in perlvar.) And you can even write something like this:
$hash{$_}++ or print "Found new value: $_.\n" for (@keys);
Which reports each key the first time it’s found.
ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...
If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...
HTH
I think this only happens when you have 'Preserve log' checked and you are trying to view the response data of a previous request after you have navigated away.
For example, I viewed the Response to loading this Stack Overflow question. You can see it.
The second time, I reloaded this page but didn't look at the Headers or Response. I navigated to a different website. Now when I look at the response, it shows 'Failed to load response data'.
This is a known issue, that's been around for a while, and debated a lot. However, there is a workaround, in which you pause on onunload
, so you can view the response before it navigates away, and thereby doesn't lose the data upon navigating away.
window.onunload = function() { debugger; }
As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.
For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.
$person = "Rasmus Lerdorf";
$found = false;
foreach($organization as $oKey=>$department)
{
foreach($department as $dKey=>$group)
{
foreach($group as $gKey=>$employee)
{
if ($employee['fullname'] == $person)
{
$found = true;
break 3;
}
} // group
} // department
} // organization
$q->where("a = 1")
->andWhere("b = 1 OR b = 2")
->andWhere("c = 2 OR c = 2")
;
Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.
def get_domain_suffixes():
import requests
res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
lst=set()
for line in res.text.split('\n'):
if not line.startswith('//'):
domains=line.split('.')
cand=domains[-1]
if cand:
lst.add('.'+cand)
return tuple(sorted(lst))
domain_suffixes=get_domain_suffixes()
def reminds_url(txt:str):
"""
>>> reminds_url('yandex.ru.com/somepath')
True
"""
ltext=txt.lower().split('/')[0]
return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)
print "Matched!\n" if ($str1 eq $str2)
Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.
file_exists($filepath)
will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed.
is_file($filepath)
will only return true for fully filepaths
First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Then you use it like this. Caution! Makes the code extremely readable.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
// Do stuff here
}
use
require_once(__DIR__.'/_path/_of/_filename.php');
This will also help in importing files in from different folders.
Try extends
method to inherit the classes in that file and reuse the functions
Here is what i did for logback.
I created a TestAppender class:
public class TestAppender extends AppenderBase<ILoggingEvent> {
private Stack<ILoggingEvent> events = new Stack<ILoggingEvent>();
@Override
protected void append(ILoggingEvent event) {
events.add(event);
}
public void clear() {
events.clear();
}
public ILoggingEvent getLastEvent() {
return events.pop();
}
}
Then in the parent of my testng unit test class I created a method:
protected TestAppender testAppender;
@BeforeClass
public void setupLogsForTesting() {
Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
testAppender = (TestAppender)root.getAppender("TEST");
if (testAppender != null) {
testAppender.clear();
}
}
I have a logback-test.xml file defined in src/test/resources and I added a test appender:
<appender name="TEST" class="com.intuit.icn.TestAppender">
<encoder>
<pattern>%m%n</pattern>
</encoder>
</appender>
and added this appender to the root appender:
<root>
<level value="error" />
<appender-ref ref="STDOUT" />
<appender-ref ref="TEST" />
</root>
Now in my test classes that extend from my parent test class I can get the appender and get the last message logged and verify the message, the level, the throwable.
ILoggingEvent lastEvent = testAppender.getLastEvent();
assertEquals(lastEvent.getMessage(), "...");
assertEquals(lastEvent.getLevel(), Level.WARN);
assertEquals(lastEvent.getThrowableProxy().getMessage(), "...");
I just did the same. If you look in the "Android SDK Manager" in the "Android 4.0 (API 14)" section you'll see a few packages. One of these is named "ARM EABI v7a System Image".
This is what you need to download in order to create an Android 4.0 virtual device:
The other answers have pointed out the solution for the majority of cases involving PropertySources
, but none have mentioned that certain property sources are unable to be casted into useful types.
One such example is the property source for command line arguments. The class that is used is SimpleCommandLinePropertySource
. This private class is returned by a public method, thus making it extremely tricky to access the data inside the object. I had to use reflection in order to read the data and eventually replace the property source.
If anyone out there has a better solution, I would really like to see it; however, this is the only hack I have gotten to work.
SELECT *
FROM my_table
WHERE column_a <=> column_b AND column_a <=> column_c
======authorization====== MIDDLEWARE_x000D_
_x000D_
const jwt = require('../helpers/jwt')_x000D_
const User = require('../models/user')_x000D_
_x000D_
module.exports = {_x000D_
authentication: function(req, res, next) {_x000D_
try {_x000D_
const user = jwt.verifyToken(req.headers.token, process.env.JWT_KEY)_x000D_
User.findOne({ email: user.email }).then(result => {_x000D_
if (result) {_x000D_
req.body.user = result_x000D_
req.params.user = result_x000D_
next()_x000D_
} else {_x000D_
throw new Error('User not found')_x000D_
}_x000D_
})_x000D_
} catch (error) {_x000D_
console.log('langsung dia masuk sini')_x000D_
_x000D_
next(error)_x000D_
}_x000D_
},_x000D_
_x000D_
adminOnly: function(req, res, next) {_x000D_
let loginUser = req.body.user_x000D_
if (loginUser && loginUser.role === 'admin') {_x000D_
next()_x000D_
} else {_x000D_
next(new Error('Not Authorized'))_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
====error handler==== MIDDLEWARE_x000D_
const errorHelper = require('../helpers/errorHandling')_x000D_
_x000D_
module.exports = function(err, req, res, next) {_x000D_
// console.log(err)_x000D_
let errorToSend = errorHelper(err)_x000D_
// console.log(errorToSend)_x000D_
res.status(errorToSend.statusCode).json(errorToSend)_x000D_
}_x000D_
_x000D_
_x000D_
====error handling==== HELPER_x000D_
var nodeError = ["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]_x000D_
var mongooseError = ["MongooseError","DisconnectedError","DivergentArrayError","MissingSchemaError","DocumentNotFoundError","MissingSchemaError","ObjectExpectedError","ObjectParameterError","OverwriteModelError","ParallelSaveError","StrictModeError","VersionError"]_x000D_
var mongooseErrorFromClient = ["CastError","ValidatorError","ValidationError"];_x000D_
var jwtError = ["TokenExpiredError","JsonWebTokenError","NotBeforeError"]_x000D_
_x000D_
function nodeErrorMessage(message){_x000D_
switch(message){_x000D_
case "Token is undefined":{_x000D_
return 403;_x000D_
}_x000D_
case "User not found":{_x000D_
return 403;_x000D_
}_x000D_
case "Not Authorized":{_x000D_
return 401;_x000D_
}_x000D_
case "Email is Invalid!":{_x000D_
return 400;_x000D_
}_x000D_
case "Password is Invalid!":{_x000D_
return 400;_x000D_
}_x000D_
case "Incorrect password for register as admin":{_x000D_
return 400;_x000D_
}_x000D_
case "Item id not found":{_x000D_
return 400;_x000D_
}_x000D_
case "Email or Password is invalid": {_x000D_
return 400_x000D_
}_x000D_
default :{_x000D_
return 500;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
module.exports = function(errorObject){_x000D_
// console.log("===ERROR OBJECT===")_x000D_
// console.log(errorObject)_x000D_
// console.log("===ERROR STACK===")_x000D_
// console.log(errorObject.stack);_x000D_
_x000D_
let statusCode = 500; _x000D_
let returnObj = {_x000D_
error : errorObject_x000D_
}_x000D_
if(jwtError.includes(errorObject.name)){_x000D_
statusCode = 403;_x000D_
returnObj.message = "Token is Invalid"_x000D_
returnObj.source = "jwt"_x000D_
}_x000D_
else if(nodeError.includes(errorObject.name)){_x000D_
returnObj.error = JSON.parse(JSON.stringify(errorObject, ["message", "arguments", "type", "name"]))_x000D_
returnObj.source = "node";_x000D_
statusCode = nodeErrorMessage(errorObject.message);_x000D_
returnObj.message = errorObject.message;_x000D_
}else if(mongooseError.includes(errorObject.name)){_x000D_
returnObj.source = "database"_x000D_
returnObj.message = "Error from server"_x000D_
}else if(mongooseErrorFromClient.includes(errorObject.name)){_x000D_
returnObj.source = "database";_x000D_
errorObject.message ? returnObj.message = errorObject.message : returnObj.message = "Bad Request"_x000D_
statusCode = 400;_x000D_
}else{_x000D_
returnObj.source = "unknown error";_x000D_
returnObj.message = "Something error";_x000D_
}_x000D_
returnObj.statusCode = statusCode;_x000D_
_x000D_
return returnObj;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
===jwt====_x000D_
const jwt = require('jsonwebtoken')_x000D_
_x000D_
function generateToken(payload) {_x000D_
let token = jwt.sign(payload, process.env.JWT_KEY)_x000D_
return token_x000D_
}_x000D_
_x000D_
function verifyToken(token) {_x000D_
let payload = jwt.verify(token, process.env.JWT_KEY)_x000D_
return payload_x000D_
}_x000D_
_x000D_
module.exports = {_x000D_
generateToken, verifyToken_x000D_
}_x000D_
_x000D_
===router index===_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
// router.get('/', )_x000D_
router.use('/users', require('./users'))_x000D_
router.use('/products', require('./product'))_x000D_
router.use('/transactions', require('./transaction'))_x000D_
_x000D_
module.exports = router_x000D_
_x000D_
====router user ====_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
const User = require('../controllers/userController')_x000D_
const auth = require('../middlewares/auth')_x000D_
_x000D_
/* GET users listing. */_x000D_
router.post('/register', User.register)_x000D_
router.post('/login', User.login)_x000D_
router.get('/', auth.authentication, User.getUser)_x000D_
router.post('/logout', auth.authentication, User.logout)_x000D_
module.exports = router_x000D_
_x000D_
_x000D_
====app====_x000D_
require('dotenv').config()_x000D_
const express = require('express')_x000D_
const cookieParser = require('cookie-parser')_x000D_
const logger = require('morgan')_x000D_
const cors = require('cors')_x000D_
const indexRouter = require('./routes/index')_x000D_
const errorHandler = require('./middlewares/errorHandler')_x000D_
const mongoose = require('mongoose')_x000D_
const app = express()_x000D_
_x000D_
mongoose.connect(process.env.DB_URI, {_x000D_
useNewUrlParser: true,_x000D_
useUnifiedTopology: true,_x000D_
useCreateIndex: true,_x000D_
useFindAndModify: false_x000D_
})_x000D_
_x000D_
app.use(cors())_x000D_
app.use(logger('dev'))_x000D_
app.use(express.json())_x000D_
app.use(express.urlencoded({ extended: false }))_x000D_
app.use(cookieParser())_x000D_
_x000D_
app.use('/', indexRouter)_x000D_
app.use(errorHandler)_x000D_
_x000D_
module.exports = app
_x000D_
var xyz : NSDictionary?
// case 1:
xyz = ["1":"one"]
// case 2: (empty dictionary)
xyz = NSDictionary()
// case 3: do nothing
if xyz { NSLog("xyz is not nil.") }
else { NSLog("xyz is nil.") }
This test worked as expected in all cases.
BTW, you do not need the brackets ()
.
To reverse a string without using reversed
or [::-1]
, try something like:
def reverse(text):
# Container for reversed string
txet=""
# store the length of the string to be reversed
# account for indexes starting at 0
length = len(text)-1
# loop through the string in reverse and append each character
# deprecate the length index
while length>=0:
txet += "%s"%text[length]
length-=1
return txet
I would rather use the following class to generate random numbers:
byte[] random;
System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
prov.GetBytes(random);
Below code works with Spring boot(kotlin):
val authReader = InputStreamReader(javaClass.getResourceAsStream("/file1.json"))
What might be informing you coworker is a notion that most C++ code should be templated to allow for maximum usability. And if it's templated, then everything will need to be in a header file, so that client code can see it and instantiate it. If it's good enough for Boost and the STL, it's good enough for us.
I don't agree with this point of view, but it may be where it's coming from.
On SQL Server 2012, you can use the following stored procedure:
sp_columns '<table name>'
For example, given a database table named users:
sp_columns 'users'
If you already know what type it can cast to, use a C-style cast:
var o = (string) iKnowThisIsAString;
Note that only with a C-style cast can you perform explicit type coercion.
If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:
var s = o as string;
if (s != null) return s.Replace("_","-");
//or for early return:
if (s==null) return;
Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.
Use ToString() to get a human-readable string representation of any object, even if it can't cast to string.
A slightly shorter solution, that only moves the item to the end, not anywhere is this:
l += [l.pop(0)]
For example:
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
Ok the issue it seems to come from this line:
https://github.com/angular-ui/ui-date/blob/master/src/date.js#L106.
Actually this line it's the binding with jQuery UI which it should be the place to inject the data format.
As you can see in var opts
there is no property dateFormat
with the value from ng-date-format as you could espect.
Anyway the directive has a constant called uiDateConfig
to add properties to opts
.
The flexible solution (recommended):
From here you can see you can insert some options injecting in the directive a controller variable with the jquery ui options.
<input ui-date="dateOptions" ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />
myAppModule.controller('MyController', function($scope) {
$scope.dateOptions = {
dateFormat: "dd-M-yy"
};
});
The hardcoded solution:
If you don't want to repeat this procedure all the time change the value of uiDateConfig
in date.js to:
.constant('uiDateConfig', { dateFormat: "dd-M-yy" })
Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.
If you want to delete file first close all the connections and streams. after that delete the file.
Check this: https://github.com/plank/MarkerClusterer
This is the MarkerCluster modified to have a infoWindow in a cluster marker, when you have several markers in the same position.
You can see how it works here: http://culturedays.ca/en/2013-activities
On the other thread C# naming convention for enum and matching property someone pointed out what I think is a very good idea:
"I know my suggestion goes against the .NET Naming conventions, but I personally prefix enums with 'E' and enum flags with 'F' (similar to how we prefix Interfaces with 'I')."
One possibility is to delete to cookie you are looking for the expiration date from and rewrite it. Then you'll know the expiration date.
The other option, which could turn out to be a lot of work if you have a lot of commits, is an interactive rebase (assuming your git version is >=1.7.12):git rebase --root -i
When presented with a list of commits in your editor:
Save and close. Git will start rebasing.
At the end you would have a new root commit that is a combination of all the ones that came after it.
The advantage is that you don't have to delete your repository and if you have second thoughts you always have a fallback.
If you really do want to nuke your history, reset master to this commit and delete all other branches.
It can also be done with a positive assertion of removal, like this:
textContent = textContent.replace(/[\u{0080}-\u{FFFF}]/gu,"");
This uses unicode. In Javascript, when expressing unicode for a regular expression, the characters are specified with the escape sequence \u{xxxx}
but also the flag 'u'
must present; note the regex has flags 'gu'
.
I called this a "positive assertion of removal" in the sense that a "positive" assertion expresses which characters to remove, while a "negative" assertion expresses which letters to not remove. In many contexts, the negative assertion, as stated in the prior answers, might be more suggestive to the reader. The circumflex "^
" says "not" and the range \x00-\x7F
says "ascii," so the two together say "not ascii."
textContent = textContent.replace(/[^\x00-\x7F]/g,"");
That's a great solution for English language speakers who only care about the English language, and its also a fine answer for the original question. But in a more general context, one cannot always accept the cultural bias of assuming "all non-ascii is bad." For contexts where non-ascii is used, but occasionally needs to be stripped out, the positive assertion of Unicode is a better fit.
A good indication that zero-width, non printing characters are embedded in a string is when the string's "length" property is positive (nonzero), but looks like (i.e. prints as) an empty string. For example, I had this showing up in the Chrome debugger, for a variable named "textContent":
> textContent
""
> textContent.length
7
This prompted me to want to see what was in that string.
> encodeURI(textContent)
"%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B"
This sequence of bytes seems to be in the family of some Unicode characters that get inserted by word processors into documents, and then find their way into data fields. Most commonly, these symbols occur at the end of a document. The zero-width-space "%E2%80%8B"
might be inserted by CK-Editor (CKEditor).
encodeURI() UTF-8 Unicode html Meaning
----------- -------- ------- ------- -------------------
"%E2%80%8B" EC 80 8B U 200B ​ zero-width-space
"%E2%80%8E" EC 80 8E U 200E ‎ left-to-right-mark
"%E2%80%8F" EC 80 8F U 200F ‏ right-to-left-mark
Some references on those:
http://www.fileformat.info/info/unicode/char/200B/index.htm
https://en.wikipedia.org/wiki/Left-to-right_mark
Note that although the encoding of the embedded character is UTF-8, the encoding in the regular expression is not. Although the character is embedded in the string as three bytes (in my case) of UTF-8, the instructions in the regular expression must use the two-byte Unicode. In fact, UTF-8 can be up to four bytes long; it is less compact than Unicode because it uses the high bit (or bits) to escape the standard ascii encoding. That's explained here:
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
This is another solution which I use:
public class CustomAnimator {
private static final String TAG = "com.example.CustomAnimator";
private static Stack<AnimationEntry> animation_stack = new Stack<>();
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
public static final int DIRECTION_UP = 2;
public static final int DIRECTION_DOWN = -2;
static class AnimationEntry {
View in;
View out;
int direction;
long duration;
}
public static boolean hasHistory() {
return !animation_stack.empty();
}
public static void reversePrevious() {
if (!animation_stack.empty()) {
AnimationEntry entry = animation_stack.pop();
slide(entry.out, entry.in, -entry.direction, entry.duration, false);
}
}
public static void clearHistory() {
animation_stack.clear();
}
public static void slide(final View in, View out, final int direction, long duration) {
slide(in, out, direction, duration, true);
}
private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {
ViewGroup in_parent = (ViewGroup) in.getParent();
ViewGroup out_parent = (ViewGroup) out.getParent();
if (!in_parent.equals(out_parent)) {
return;
}
int parent_width = in_parent.getWidth();
int parent_height = in_parent.getHeight();
ObjectAnimator slide_out;
ObjectAnimator slide_in;
switch (direction) {
case DIRECTION_LEFT:
default:
slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
break;
case DIRECTION_RIGHT:
slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
break;
case DIRECTION_UP:
slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
break;
case DIRECTION_DOWN:
slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
break;
}
AnimatorSet animations = new AnimatorSet();
animations.setDuration(duration);
animations.playTogether(slide_in, slide_out);
animations.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationCancel(Animator arg0) {
}
@Override
public void onAnimationEnd(Animator arg0) {
out.setVisibility(View.INVISIBLE);
if (save) {
AnimationEntry ae = new AnimationEntry();
ae.in = in;
ae.out = out;
ae.direction = direction;
ae.duration = duration;
animation_stack.push(ae);
}
}
@Override
public void onAnimationRepeat(Animator arg0) {
}
@Override
public void onAnimationStart(Animator arg0) {
in.setVisibility(View.VISIBLE);
}
});
animations.start();
}
}
The usage of class. Let's say you have two fragments (list and details fragments)as shown below
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ui_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/details_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</FrameLayout>
Usage
View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);
You can use the function CustomAnimator.reversePrevious();
to get the previous view when the user pressed back.
One more idea that worked. It's really silly, but, apparently, the default target OS setting (bottom right corner of the screen) is Vista / Windows Server 2008
. As we're past the 10 year mark, it is likely that your Powershell script will not be compatible to these.
Changing the target to Windows Server 2016, as shown on the screenshot below, did the trick for me.
Look how I format my date $jour in the parameters. It depends if you use a expr()->like or a expr()->lte
$qb
->select('e')
->from('LdbPlanningBundle:EventEntity', 'e')
->where(
$qb->expr()->andX(
$qb->expr()->orX(
$qb->expr()->like('e.start', ':jour1'),
$qb->expr()->like('e.end', ':jour1'),
$qb->expr()->andX(
$qb->expr()->lte('e.start', ':jour2'),
$qb->expr()->gte('e.end', ':jour2')
)
),
$qb->expr()->eq('e.user', ':user')
)
)
->andWhere('e.user = :user ')
->setParameter('user', $user)
->setParameter('jour1', '%'.$jour->format('Y-m-d').'%')
->setParameter('jour2', $jour->format('Y-m-d'))
->getQuery()
->getArrayResult()
;
Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:
import signal
import sys
import time
import threading
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()
In RunCommand
write "MSINFO32"
and hit enter
It will show All information related to system
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
Are you using the interactive interpreter? You can use
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?
Your question is based on assumption that the code which may throw NullPointerException
is worse than the code which may not. This assumption is wrong. If you expect that your foobar
is never null due to the program logic, it's much better to use Optional.of(foobar)
as you will see a NullPointerException
which will indicate that your program has a bug. If you use Optional.ofNullable(foobar)
and the foobar
happens to be null
due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.
In addition to @Boaz's and @vegemite4me's answers....
By implementing ImplicitNamingStrategy
you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder
during Hibernate's initialization:
metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());
It works for @UniqueConstraint
, but not for @Column(unique = true)
, which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).
There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586
Thanks.
You can use ESCAPE
:
WHERE columnName LIKE '%\%%' ESCAPE '\'
This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.
There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.
The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like
1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host
EDIT
Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication
You want getActivity()
inside your class. It's better to use
yourclassname.this.getActivity()
Try this. It's helpful for you.
The auto-completion with Jupyter Notebook is so weak, even with hinterland extension. Thanks for the idea of deep-learning-based code auto-completion. I developed a Jupyter Notebook Extension based on TabNine which provides code auto-completion based on Deep Learning. Here's the Github link of my work: jupyter-tabnine.
It's available on pypi index now. Simply issue following commands, then enjoy it:)
pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine
There's no benefit to using properties with primitive types. @property
is used with heap allocated NSObjects
like NSString*
, NSNumber*
, UIButton*
, and etc, because memory managed accessors are created for free. When you create a BOOL
, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking
is simply the popular way of expressing the state of a boolean value.
In another OO language you would make a variable private bool working;
and two accessors: SetWorking
for the setter and IsWorking
for the accessor.
JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
You can't, you either need to keep the index separately:
int index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}
or use a normal for loop:
for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}
The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"
For long long (or __int64) using MSVS, you should use %I64d:
__int64 a;
time_t b;
...
fprintf(outFile,"%I64d,%I64d\n",a,b); //I is capital i
This way is comparatively more easy
SELECT doc_id,serial_number,status FROM date_time ORDER BY date_time DESC LIMIT 0,1;
There is a handy HAProxy wrapper.
docker run -it -p LOCALPORT:PROXYPORT --rm --link TARGET_CONTAINER:EZNAME -e "BACKEND_HOST=EZNAME" -e "BACKEND_PORT=PROXYPORT" demandbase/docker-tcp-proxy
This creates an HAProxy to the target container. easy peasy.
There are multiple techniques available to handle collision. I will explain some of them
Chaining: In chaining we use array indexes to store the values. If hash code of second value also points to the same index then we replace that index value with an linked list and all values pointing to that index are stored in the linked list and actual array index points to the head of the the linked list. But if there is only one hash code pointing to an index of array then the value is directly stored in that index. Same logic is applied while retrieving the values. This is used in Java HashMap/Hashtable to avoid collisions.
Linear probing: This technique is used when we have more index in the table than the values to be stored. Linear probing technique works on the concept of keep incrementing until you find an empty slot. The pseudo code looks like this:
index = h(k)
while( val(index) is occupied)
index = (index+1) mod n
Double hashing technique: In this technique we use two hashing functions h1(k) and h2(k). If the slot at h1(k) is occupied then the second hashing function h2(k) used to increment the index. The pseudo-code looks like this:
index = h1(k)
while( val(index) is occupied)
index = (index + h2(k)) mod n
Linear probing and double hashing techniques are part of open addressing technique and it can only be used if available slots are more than the number of items to be added. It takes less memory than chaining because there is no extra structure used here but its slow because of lot of movement happen until we find an empty slot. Also in open addressing technique when an item is removed from a slot we put an tombstone to indicate that the item is removed from here that is why its empty.
For more information see this site.
Command:
netstat -aon | findstr 4723
Output:
TCP 0.0.0.0:4723 0.0.0.0:0 LISTENING 10396
Now cut the process ID, "10396", using the for
command in Windows.
Command:
for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
10396
If you want to cut the 4th number of the value means "LISTENING" then command in Windows.
Command:
for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
LISTENING
With redis-cli
:
FLUSHDB - Removes data from your connection's CURRENT database.
FLUSHALL - Removes data from ALL databases.
This happened to me on windows. Any of these commands will work
On Windows CMD (not switching to bash)
docker exec -it <container-id> /bin/sh
On Windows CMD (after switching to bash)
docker exec -it <container-id> //bin//sh
or
winpty docker exec -it <container-id> //bin//sh
On Git Bash
winpty docker exec -it <container-id> //bin//sh
NB: You might need to run use /bin/bash
or /bin/sh
, depending on the shell in your container.
The reason is documented in the ReleaseNotes file of Git and it is well explained here - Bash in Git for Windows: Weirdness...
"The cause has to do with trying to ensure that posix paths end up being passed to the git utilities properly. For this reason, Git for Windows includes a modified MSYS layer that affects command arguments."
Update to Davids answer to even detect browsers that do not support pushstate:
if (history.pushState) {
window.history.pushState("object or string", "Title", "/new-url");
} else {
document.location.href = "/new-url";
}
This can be done very straightforwardly.
Define your struct explicitly with [StructLayout(LayoutKind.Explicit)]
int size = list.GetLength(0);
IntPtr addr = Marshal.AllocHGlobal(size * sizeof(DataStruct));
DataStruct *ptrBuffer = (DataStruct*)addr;
foreach (DataStruct ds in list)
{
*ptrBuffer = ds;
ptrBuffer += 1;
}
This code can only be written in an unsafe context. You have to free addr
when you're done with it.
Marshal.FreeHGlobal(addr);
I realize this is a later answer, but I found another reference to a way to address this issue that might help others in the future. This web page describes setting an environment variable (COMPLUS_ZapDisable=1) that prevents optimization, at least it did for me! (Don't forget the second part of disabling the Visual Studio hosting process.) In my case, this might have been even more relevant because I was debugging an external DLL thru a symbol server, but I'm not sure.
You can't use a LinearLayout for this, but you can use a FrameLayout
. In a FrameLayout
, the z-index is defined by the order in which the items are added, for example:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_drawable"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:padding="5dp"
android:text="My Label"
/>
</FrameLayout>
In this instance, the TextView would be drawn on top of the ImageView, along the bottom center of the image.
actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101)
will change the DATETIME format to date (one day)
so:
SELECT
sum(amount)
FROM
sales
GROUP BY
convert(varchar,created,101)
the magix number 101
is what date format it is converted to
Use http://jsfiddle.net//show/light/
then just use inspect element function of browser. you will get code in iframe tab. . in chrome just right click and cick on edit as html tab. and copy the html content. that is your actual code.