Anchor tags generated by different Markdown parsers are not even.
If you are working with Markdown parsers GFM (GitHub Flavored Markdown) or Redcarpet, I wrote a Vim plugin to handle table of contents.
Generate table of contents for Markdown files.
Supported Markdown parsers:
Update existing table of contents.
Auto update existing table of contents on save.
Generate table of contents
Move the cursor to the line you want to append table of contents, then type a command below suit you. The command will generate headings after the cursor into table of contents.
:GenTocGFM
Generate table of contents in GFM link style.
This command is suitable for Markdown files in GitHub repositories, like README.md, and Markdown files for GitBook.
:GenTocRedcarpet
Generate table of contents in Redcarpet link style.
This command is suitable for Jekyll or anywhere else use Redcarpet as its Markdown parser.
You can view here to know differences between GFM and Redcarpet style toc links.
Update existing table of contents manually
Generally you don't need to do this, existing table of contents will auto update on save by default. If you want do it manually, just use :UpdateToc
command.
To extend the answer a little bit to support local images, just replace FILE_PATH_PLACEHOLDER
to your image path and check it out.
<p align="center">
<img src="FILE_PATH_PLACEHOLDER">
</p>
I strongly recommend placing the video in a project website created with GitHub Pages instead of the readme, like described in VonC's answer; it will be a lot better than any of these ideas. But if you need a quick fix just like I needed, here are some suggestions.
See aloisdg's answer, result is awesome, gifs are rendered on github's readme ;)
You could trick the user into thinking the video is on the readme page with a picture. It sounds like an ad trick, it's not perfect, but it works and it's funny ;).
Example:
[![Watch the video](https://i.imgur.com/vKb2F1B.png)](https://youtu.be/vt5fpE0bzSY)
Result:
You can also use the picture generated by youtube for your video.
For youtube urls in the form of:
https://www.youtube.com/watch?v=<VIDEO ID>
https://youtu.be/<VIDEO URL>
The preview urls are in the form of:
https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg
https://img.youtube.com/vi/<VIDEO ID>/hqdefault.jpg
Example:
[![Watch the video](https://img.youtube.com/vi/T-D1KVIuvjA/maxresdefault.jpg)](https://youtu.be/T-D1KVIuvjA)
Result:
If your use case is something that runs in a terminal, asciinema lets you record a terminal session and has nice markdown embedding.
Hit share button and copy the markdown snippet.
Example:
[![asciicast](https://asciinema.org/a/113463.png)](https://asciinema.org/a/113463)
Result:
My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.
{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)
#data wrangling
library(dplyr)
#text processing
library(stringi)
I tried everything but this worked for me while using Pandoc markdown with TexLive as LaTex engine. In order to add blank lines, you can try adding a blank line but remove ""
## \newline
Just repeat the above, each will add a new blank line
In slim markdown use this:
markdown:
{:.cool-heading}
#Some Title
Translates to:
<h1 class="cool-heading">Some Title</h1>
From now I use http://marxi.co/. Marxi.co has online and offline version.
Try adding 2 spaces (or a backslash \
) after the first line:
[Name of link](url)
My line of text\
Visually:
[Name of link](url)<space><space>
My line of text\
Output:
<p><a href="url">Name of link</a><br>
My line of text<br></p>
pandoc
with browser
works well for me.
Usage: cat README.md | pandoc -f markdown_github | browser
Installation (Assuming you are using Mac OSX):
$ brew install pandoc
$ brew install browser
Or on Debian/Ubuntu: apt-get install pandoc browser
.md
stands for markdown and is generated at the bottom of your github page as html.
Typical syntax includes:
Will become a heading
==============
Will become a sub heading
--------------
*This will be Italic*
**This will be Bold**
- This will be a list item
- This will be a list item
Add a indent and this will end up as code
For more details: http://daringfireball.net/projects/markdown/
$ cat foo.md
Key 1 | Value 1
Key 2 | Value 2
$ kramdown foo.md
<table>
<tbody>
<tr>
<td>Key 1</td>
<td>Value 1</td>
</tr>
<tr>
<td>Key 2</td>
<td>Value 2</td>
</tr>
</tbody>
</table>
Just follow the format below.
[TEXT TO SHOW](actual URL to navigate)
The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:
#### 1.1 My Subtitle \
1.1 My Subtitle
Next paragraph text.
An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).
### My Subtitle
1.1 My Subtitle
Next paragraph text.
GitHub Pages now uses kramdown as its markdown engine so you can use the following syntax:
Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.
http://kramdown.gettalong.org/syntax.html#images
I haven't tested it on GitHub wiki though.
Microsoft's Visual Studio Code text editor has built in support for .md files written in markdown syntax.
The syntax is automatically color-coded inside of the .md file, and a preview window of the rendered markdown can be viewed by pressing Shift+Ctrl+V
(Windows) or Shift+Cmd+V
(Mac).
To see them side-by-side, drag the preview tab to the right side of the editor, or use Ctrl+K V
(Windows) or Cmd+K V
(Mac) instead.
VS Code uses the marked library for parsing, and has Github Flavored Markdown support enabled by default, but it will not display the Github Emoji inline like Github's Atom text editor does.
Also, VS Code supports has several markdown plugins available for extended functionality.
Another reason is that <u>
tags are deprecated in XHTML and HTML5, so it would need to produce something like <span style="text-decoration:underline">this</span>
. (IMHO, if <u>
is deprecated, so should be <b>
and <i>
.) Note that Markdown produces <strong>
and <em>
instead of <b>
and <i>
, respectively, which explains the purpose of the text therein instead of its formatting. Formatting should be handled by stylesheets.
Update:
The <u>
element is no longer deprecated in HTML5.
If you can provide your image in SVG format and if it is an icon and not a photo so it can be animated with SMIL animations, then it would be definitely the superior alternative to gif images (or even other formats).
SVG images, like other image files, could be used with either standard markup or HTML <img>
element:
![image description](the_path_to/image.svg)
<img src="the_path_to/image.svg" width="128"/>
In a generic Markdown document, use:
<style>body {text-align: right}</style>
or
<style>body {text-align: justify}</style>
Does not seem to work with Jupyter though.
For completed alex answered (Dec 13 '10)
A more smart injection target could be done with this code :
/*
* For all links in the current page...
*/
$(document.links).filter(function() {
/*
* ...keep them without `target` already setted...
*/
return !this.target;
}).filter(function() {
/*
* ...and keep them are not on current domain...
*/
return this.hostname !== window.location.hostname ||
/*
* ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
*/
/\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
* For all link kept, add the `target="_blank"` attribute.
*/
}).attr('target', '_blank');
You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?)
group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).
and for a without jQuery version, check code below:
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (!links[i].target) {
if (
links[i].hostname !== window.location.hostname ||
/\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
) {
links[i].target = '_blank';
}
}
}
The best way to create internal links (related with sections) is create list but instead of link, put #section
or #section-title
if the header includes spaces.
Markdown
Go to section
* [Hello](#hello)
* [Hello World](#hello-world)
* [Another section](#new-section) <-- it's called 'Another section' in this list but refers to 'New section'
## Hello
### Hello World
## New section
List preview
Go to section
Hello <-- [Hello](#hello) -- go to `Hello` section
Hello World <-- [Hello World](#hello world) -- go to `Hello World` section
Another section <-- [Another section](#new-section) -- go to `New section`
HTML
<p>Go to section</p>
<ul>
<li><a href="#hello">Hello</a></li>
<li><a href="#hello-world">Hello World</a></li>
<li><a href="#new-section">Another section</a> <– it’s called ‘Another section’ in this list but refers to ‘New section’</li>
</ul>
<h2 id="hello">Hello</h2>
<h3 id="hello-world">Hello World</h3>
<h2 id="new-section">New section</h2>
It doesn't matter whether it's h1
, h2
, h3
, etc. header, you always refer to it using just one #
.
All references in section list should be converted to lowercase text as it is shown in the example above.
The link to the section should be lowercase. It won't work otherwise. This technique works very well for all Markdown variants, also MultiMarkdown.
Currently I'm using the Pandoc to convert documents format. It's much better than MultiMarkdown.
Test Pandoc here
Many Markdown "extra" processors support attributes. So you can include a class name like so (PHP Markdown Extra):
![Flowers](/flowers.jpeg){.callout}
or, alternatively (Maruku, Kramdown, Python Markdown):
![Flowers](/flowers.jpeg){: .callout}
Then, of course, you can use a stylesheet the proper way:
.callout {
float: right;
}
If yours supports this syntax, it gives you the best of both worlds: no embedded markup, and a stylesheet abstract enough to not need to be modified by your content editor.
How to add new line in Markdown presentation?
Check the following resource Line Return
To force a line return, place two empty spaces at the end of a line.
If I need only to highlight the first word as a command, I often use properties
:
```properties
npm run build
```
I obtain something like:
npm run build
Have you tried using double tabs? To make a box:
Start on a fresh line
Hit tab twice, type up the content
Your content should appear in a box
It works for me in a regular Rmarkdown document with html output. The double-tabbed portion should appear in a rounded rectangular light grey box.
I contacted GitHub to say that github.io-hosted SVGs are no longer displayed in GitHub READMEs. I received this reply:
We have had to disable svg image rendering on GitHub.com due to potential cross site scripting vulnerabilities.
An alternative is to put comments within stylized HTML tags. This way, you can toggle their visibility as needed. For example, define a comment class in your CSS stylesheet.
.comment { display: none; }
Then, the following enhanced MARKDOWN
We do <span class="comment">NOT</span> support comments
appears as follows in a BROWSER
We do support comments
Some more spins on the <a name="">
trick:
<a id="a-link"></a> Title
------
#### <a id="a-link"></a> Title (when you wanna control the h{N} with #'s)
Although the question is about GitHub flavored Markdown, I think it's worth mentioning that as of 2013, GitHub supports AsciiDoc which has this feature builtin. You only need to rename your file with a .adoc
extension and use:
A statement.footnote:[Clarification about this statement.]
A bold statement!footnote:disclaimer[Opinions are my own.]
Another bold statement.footnote:disclaimer[]
You can use the diff
language tag to generate some colored text:
```diff
- text in red
+ text in green
! text in orange
# text in gray
@@ text in purple (and bold)@@
```
However, it adds it as a new line starting with either - + ! #
or starts and ends with @@
This issue was raised in github markup #369, but they haven't made any change in decision since then (2014).
You can link to images in your project from README.md (or externally) using the alternative github CDN link.
The URL will look like this:
https://cdn.rawgit.com/<USER>/<REPO>/<BRANCH>/<PATH>/<TO>/<FILE>
I have an SVG image in my project, and when I reference it in my Python project documentation, it does not render.
Here is the project link to the file (does not render as an image):
https://github.com/jongracecox/anybadge/blob/master/examples/awesomeness.svg
Example embedded image:
Here is the RAW link to the file (still does not render as an image):
https://raw.githubusercontent.com/jongracecox/anybadge/master/examples/awesomeness.svg
Example embedded image:
Using the CDN link, I can link to the file using (renders as an image):
https://cdn.rawgit.com/jongracecox/anybadge/master/examples/awesomeness.svg
Example embedded image:
This is how I am able to use images from my project in both my README.md
file, and in my PyPi project reStructredText doucmentation (here)
None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.
The include_graphics()
function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo
to FALSE
and fig.align=center
you get the wished result.
```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```
Note that there are also a number of extensions available that will fix this behaviour for specific contexts of Markdown use.
For example, sane_lists extension of python-markdown (used in mkdocs, for example), will recognize numbers used in Markdown lists. You just need to enable this extension arkdown.markdown(some_text, extensions=['sane_lists'])
I've had success with
<span class="someclass"></span>
Caveat : the class must already exist on the site.
To center align, surround the text you wish to center align with arrows (->
<-
) like so:
-> This is center aligned <-
An alternative approach, which I've recently implemented, is to use the div-table plugin with panflute.
This creates a table from a set of fenced divs (standard in the pandoc implementation of markdown), in a similar layout to html:
---
panflute-filters: [div-table]
panflute-path: 'panflute/docs/source'
---
::::: {.divtable}
:::: {.tcaption}
a caption here (optional), only the first paragraph is used.
::::
:::: {.thead}
[Header 1]{width=0.4 align=center}
[Header 2]{width=0.6 align=default}
::::
:::: {.trow}
::: {.tcell}
1. any
2. normal markdown
3. can go in a cell
:::
::: {.tcell}
![](https://pixabay.com/get/e832b60e2cf7043ed1584d05fb0938c9bd22ffd41cb2144894f9c57aae/bird-1771435_1280.png?attachment){width=50%}
some text
:::
::::
:::: {.trow bypara=true}
If bypara=true
Then each paragraph will be treated as a separate column
::::
any text outside a div will be ignored
:::::
Looks like:
It's possible, as addressed in Issue #7396:
When you do want to insert a
<br />
break tag using Markdown, you end a line with two or more spaces, then type return or Enter.
```javascript
{ "some": "json" }
```
I tried using json
but didn't like the way it looked. javascript
looks a bit more pleasing to my eye.
Create a directory named like Images
and put all the images that will be rendered by the Markdown.
For example, put example.png
into Images
.
To load example.png
that was located under the Images
directory before.
![title](Images/example.png)
Note : Images
directory must be located under the same directory of your markdown text file which has .md
extension.
I'll answer your question with a counter-question...
What do you think of Org-mode? It's not as pure as Markdown, but it is Markdown-like, and I find it as easy to work with, and it allows embedding of Latex. Cf. http://www.gnu.org/software/emacs/manual/html_node/org/Embedded-LaTeX.html
Postscript
In case you haven't looked at org-mode, it has one great strength as a general purpose "natural markup language" over Markdown, namely its treatment of tables. The source:
| 1 | 0 | 0 | | -1 | 1 | 0 | | -1 | -1 | 1 |
represents just what you think it will...
And the Latex is rendered in pieces using tex-mode's preview-latex.
Multimarkdown has this natively. It calls it file transclusion:
{{some_other_file.txt}}
is all it takes. Weird name, but ticks all the boxes.
You could just use some HTML in your Markdown:
<img src="drawing.jpg" alt="drawing" width="200"/>
Or via style
attribute (not supported by GitHub)
<img src="drawing.jpg" alt="drawing" style="width:200px;"/>
Or you could use a custom CSS file as described in this answer on Markdown and image alignment
![drawing](drawing.jpg)
CSS in another file:
img[alt=drawing] { width: 200px; }
Late to the party, but I think this addition might be useful for people working with rmarkdown
. In rmarkdown
there is built-in support for references to headers in your document.
Any header defined by
# Header
can be referenced by
get me back to that [header](#header)
The following is a minimal standalone .rmd
file that shows this behavior. It can be knitted to .pdf
and .html
.
---
title: "references in rmarkdown"
output:
html_document: default
pdf_document: default
---
# Header
Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text.
Go back to that [header](#header).
The universal solution is using the HTML tag <sup>
, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.
Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.
Finally, I would like to remember the simplest solution for some documents: the character ^
.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.
Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.
Un updated answer: in knitr 1.17
you can simply use
![Image Title](path/to/your/image){width=250px}
edit as per comment from @jsb
Note this works only without spaces, e.g. {width=250px} not {width = 250px}
A slight riff on the top voted answer that I found to be a little more explicit is to use the jekyll syntax for adding a class to something and then style it that way.
So in the post you would have:
![My image](/images/my-image.png)
{:.image-caption}
*The caption for my image*
And then in your CSS file you can do something like this:
.image-caption {
text-align: center;
font-size: .8rem;
color: light-grey;
Comes out looking good!
When you're exporting to HTML, using <br>
works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:
+---------------+---------------+--------------------+
| Fruit | Price | Advantages |
+===============+===============+====================+
| Bananas | first line\ | first line\ |
| | next line | next line |
+---------------+---------------+--------------------+
| Bananas | first line\ | first line\ |
| | next line | next line |
+---------------+---------------+--------------------+
One other work-around is to use jupyter notebooks and use the markdown mode in cells to render equations.
Basic stuff seems to work perfectly, like centered equations
\begin{equation}
...
\end{equation}
or inline equations
$ \sum_{\forall i}{x_i^{2}} $
Although, one of the functions that I really wanted did not render at all in github was \mbox{}
, which was a bummer. But, all in all this has been the most successful way of rendering equations on github.
Dog
Cat
I'd suggest using wasabi then you can either use the markdown-ish feel like this
root/ # entry comments can be inline after a '#'
# or on their own line, also after a '#'
readme.md # a child of, 'root/', it's indented
# under its parent.
usage.md # indented syntax is nice for small projects
# and short comments.
src/ # directories MUST be identified with a '/'
fileOne.txt # files don't need any notation
fileTwo* # '*' can identify executables
fileThree@ # '@' can identify symlinks
and throw that exact syntax at the js library for this
You can simply use raw html tags like
foo <font color='red'>bar</font> foo
Be aware that this will not survive a conversion of the notebook to latex.
As there are some complaints about the deprecation of the proposed solution. They are totally valid and Scott has already answered the question with a more recent, i.e. CSS based approach. Nevertheless, this answer shows some general approach to use html tags within IPython to style markdown cell content beyond the available pure markdown capabilities.
I googled a few similar questions and did not see any answers with my problem and its quite simple/easy solution.
Here goes: like the OP, I wanted an image in my Github README, and, knowing the Markdown syntax for doing so, typed it in:
![My Image](https://storage.cloud.google.com/${MY_BUCKET}/${MY_IMAGE}
You need to complete the actual substitutions above (e.g. MY_IMAGE=image.jpg) for this to work.
But, wait...failure--there's no actual rendered photo! And the link is exactly as given by Google Storage!
camo
- Anonymous ImagesGithub hosts your images anonymously, yay! However, this presents an issue for Google storage assets. You need to get the generated url from your Google Cloud Console.
I'm sure there's a smoother way, however, simply visit your given URL endpoint and copy the long URL. Details:
https
not gs
) into a new browser tab/windowHopefully this helps speed up and clarify this issue for anyone else.
I'm surprised no one mentioned the HTML entities  
and  
which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than
.
 
 
Along with <space>
and  
, these are the five entities HTML provides for horizontal white space.
Note that except for
, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With
it would wrap to a new line as a block even if the text before
could fit on the previous line.
Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John
Doe), addresses or references (see eq.
5), breaking as a block is usually undesired.
Adding a link with the thumbnail, originally used by YouTube is a solution, that works. The thumbnail, used by YouTube is accessible the following way:
https://www.youtube.com/watch?v=5yLzZikS15k
https://img.youtube.com/vi/5yLzZikS15k/0.jpg
Following this logic, the code below produces flawless results:
<div align="left">
<a href="https://www.youtube.com/watch?v=5yLzZikS15k">
<img src="https://img.youtube.com/vi/5yLzZikS15k/0.jpg" style="width:100%;">
</a>
</div>
_x000D_
To answer MengLu and @lifebalance's questions in response to SColvin's answer (which I much prefer to the accepted answer for the control it provides), it seems as though you could just target a parent element of the lists when setting the display to none, adding a surrounding element if necessary. So if we suppose we're doing this for a table of contents, we can extend SColvin's answer:
HTML
<nav class="table-of-contents">
this is a normal line of text
* this is the first level of bullet points, made up of <space><space>*<space>
* this is more indented, composed of <space><space><space><space>*<space>
</nav>
CSS
.table-of-contents ul {
list-style-type: none;
}
Simple tree
command will do the job. For example: tree -o readme.md
will print the tree structure of your current working directory and write it to readme.md
. Then open readme.md file in one of text editor like Sublime and wrap its content within a pair of triple backticks (```).
FYI: you might have to brew install tree in OSX if it's not already installed. In Linux and Windows it should just work fine. Also in windows you might have to replace hyphen with forward slash.
I hope this helps.
You link to a local file the same way you link to local images. Here is an example to link to file start_caQtDM_7id.sh
in the same directory as the markdown source:
![start_caQtDM_7id.sh](./start_caQtDM_7id.sh)
Alternatively you can do:
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getString(1);
}
But use Sean Bright's answer instead for your scenario.
This problem got resolved by mentioning the package name
I moved my file Test_Steps.java which was under package stepDefinition
by just adding the package stepDefinition the problem got resolved
So this problem can occur when you have a package and you are not using in your class file.
Adding it has resolved the problem and the error was no longer appearing.
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
Neither code is always better. They do different things, so they are good at different things.
InvariantCultureIgnoreCase
uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.
OrdinalIgnoreCase
compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é
or ö
. This is also faster because there are no extra rules to apply before comparing.
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
$("#img_id").error(function(){
//$(this).hide();
//alert("img not loaded");
//some action you whant here
});
careful - .error() event will not trigger when the src attribute is empty for an image.
In my case I had code like this:
function.call(context, arg);
I got error message under IE
TypeError: Object doesn't support property or method 'error'
In the body of 'function' I had "console.error" and it turns that console object is undefined when your console is closed. I have fixed this by checking if console and console.error are defined
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
the same solution as Basit .. but the version 3.0 doesn't work for me try this .. it works for me to integrate struts 2.x
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>blabla</display-name>
...
</web-app>
the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)
input.ng-invalid.ng-touched{
border-bottom: 1px solid #e74c3c !important;
}
Turns out you can download a MS version of this header from:
https://github.com/mattn/gntp-send/blob/master/include/msinttypes/stdint.h
A portable one can be found here:
http://www.azillionmonkeys.com/qed/pstdint.h
Thanks to the Software Ramblings blog.
In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok
Full version:
<? echo date('F Y'); ?>
Short version:
<? echo date('M Y'); ?>
Here is a good reference for the different date options.
update
To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp
parameter for the date() function. Like this:
echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));
This will also work (it's typically used to get the last day of the previous month):
echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));
Hope that helps.
If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved
method of your service as follows:
Intent intent = new Intent("com.android.ServiceStopped");
sendBroadcast(intent);
and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.
Works in Google Chrome v66.x, Mozilla v59.x and Microsoft Edge... Solution with jQuery.
I test in Internet Explorer 9 and not supported.
$("#YourElement").blur(function(e){
var InputTarget = $(e.relatedTarget).attr("id"); // GET ID Element
console.log(InputTarget);
if(target == "YourId") { // If you want validate or make a action to specfic element
... // your code
}
});
Comment your test in others internet explorer versions.
Yes, it is. Declare parameter as so:
@Sort varchar(50) = NULL
Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).
Instead of using count(*)
you can SELECT *
and you will return all of the details that you want including data_type
:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'
MSDN Docs on INFORMATION_SCHEMA.COLUMNS
Having a table with a foreign key to itself does make sense to me.
You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.
Use this Layout in your xml file
<LinearLayout
android:id="@+id/contacts_type"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</LinearLayout>
Define your layout in .class file
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);
Now if you want to display this layout just write
linearLayout.setVisibility(View.VISIBLE);
and if you want to hide layout just write
linearLayout.setVisibility(View.INVISIBLE);
'1.43'.replace('.','',1).isdigit()
which will return true
only if there is one or no '.' in the string of digits.
'1.4.3'.replace('.','',1).isdigit()
will return false
'1.ww'.replace('.','',1).isdigit()
will return false
package sn;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
final String username = "[email protected]";//
final String password = "0000000";
try{
Session session = Session.getDefaultInstance(props,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent.");
}catch (MessagingException e){
System.out.println("Erreur d'envoi, cause: " + e);
}
}
}
@media print {
.footer,
#non-printable {
display: none !important;
}
#printable {
display: block;
}
}
Error:(30, 13) Failed to resolve: com.google.firebase:firebase-auth:9.6.1
If you ever get this error and you are using Android studio 2.2 that comes with firebase component integrated in it which has libraries version 9.6.0 by default and you are adding the latest dependencies like 9.6.1 . You might need to downgrade com.google.firebase:firebase-auth:9.6.1
to com.google.firebase:firebase-auth:9.6.0
Or check the library version of your pre-installed firebase and make sure it is of the same version with the new library you are trying to add or added to your project.
You will find de log4j.properties in solr/examples/resources.
If you don't find the file, i put it here:
# Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n
#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9
#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF
Regards
The Pumping lemma for regular languages is the reason why you can't do that.
The generated automaton will have a finite number of states, say k, so a string of k+1 opening braces is bound to have a state repeated somewhere (as the automaton processes the characters). The part of the string between the same state can be duplicated infinitely many times and the automaton will not know the difference.
In particular, if it accepts k+1 opening braces followed by k+1 closing braces (which it should) it will also accept the pumped number of opening braces followed by unchanged k+1 closing brases (which it shouldn't).
Here's a solution using the new async/await syntax.
async function testWait() {
alert('going to wait for 5 second');
await wait(5000);
alert('finally wait is over');
}
function wait(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, time);
});
}
Note: You can call function wait only in async functions
In first scenario I supposed that your table have IDENTITY column
CREATE TRIGGER [dbo].[insupddel_yourTable] ON [yourTable]
FOR INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0 return
SET NOCOUNT ON;
DECLARE @action nvarchar(10)
SELECT @action = CASE WHEN COUNT(i.Id) > COUNT(d.Id) THEN 'inserted'
WHEN COUNT(i.Id) < COUNT(d.Id) THEN 'deleted' ELSE 'updated' END
FROM inserted i FULL JOIN deleted d ON i.Id = d.Id
In second scenario don't need to use IDENTITTY column
CREATE TRIGGER [dbo].[insupddel_yourTable] ON [yourTable]
FOR INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0 return
SET NOCOUNT ON;
DECLARE @action nvarchar(10),
@insCount int = (SELECT COUNT(*) FROM inserted),
@delCount int = (SELECT COUNT(*) FROM deleted)
SELECT @action = CASE WHEN @insCount > @delCount THEN 'inserted'
WHEN @insCount < @delCount THEN 'deleted' ELSE 'updated' END
you can do it like this:
function MyClass() {
this.abc = function() {
alert("abc");
}
}
var myObject = new MyClass();
myObject["abc"]();
rake gitlab:import:repos might be a more suitable method for mass importing:
repos_path
(/home/git/repositories/group/repo.git
). Directory name must end in .git
and be under a group or user namespace.bundle exec rake gitlab:import:repos
The owner will the first admin, and a group will get created if not already existent.
See also: How to import an existing bare git repository into Gitlab?
The navbar-toggler-icon
(hamburger) in Bootstrap 4 uses an SVG background-image
. There are 2 "versions" of the toggler icon image. One for a light navbar, and one for a dark navbar...
navbar-dark
for a light/white toggler on darker backgroundsnavbar-light
for a dark/gray toggler on lighter backgrounds// this is a black icon with 50% opacity
.navbar-light .navbar-toggler-icon {
background-image: url("data:image/svg+xml;..");
}
// this is a white icon with 50% opacity
.navbar-dark .navbar-toggler-icon {
background-image: url("data:image/svg+xml;..");
}
Therefore, if you want to change the color of the toggler image to something else, you can customize the icon. For example, here I set the RGB value to pink (255,102,203). Notice the stroke='rgba(255,102,203, 0.5)'
value in the SVG data:
.custom-toggler .navbar-toggler-icon {
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255,102,203, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E");
}
.custom-toggler.navbar-toggler {
border-color: rgb(255,102,203);
}
Demo http://www.codeply.com/go/4FdZGlPMNV
OFC, another option to just use an icon from another library ie: Font Awesome, etc..
Update Bootstrap 4.0.0:
As of Bootstrap 4 Beta, navbar-inverse
is now navbar-dark
to use on navbars with darker background colors to produce lighter link and toggler colors.
Use transform;
<style type="text/css">
#mydiv {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
Javascript Solution :
var left = (screen.width / 2) - (530 / 2);
var top = (screen.height / 2) - (500 / 2);
var _url = 'PopupListRepair.aspx';
window.open(_url, self, "width=530px,height=500px,status=yes,resizable=no,toolbar=no,menubar=no,left=" + left + ",top=" + top + ",scrollbars=no");
You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.
str=xpath.replaceAll("\\.", "/*/"); //replaces a literal . with /*/
You could try to put a ServletFilter
in front of the webservice and inspect request and response going to / returned from the service.
Although you specifically did not ask for a proxy, sometimes I find tcptrace is enough to see what goes on on a connection. It's a simple tool, no install, it does show the data streams and can write to file too.
Just use an ALTER TABLE... MODIFY...
query and add NOT NULL
into your existing column definition. For example:
ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;
A word of caution: you need to specify the full column definition again when using a MODIFY
query. If your column has, for example, a DEFAULT
value, or a column comment, you need to specify it in the MODIFY
statement along with the data type and the NOT NULL
, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable
query, modify it to include the NOT NULL
constraint, and paste it into your ALTER TABLE... MODIFY...
query.
Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
It uses setSelectionRange if supported, else has a solid fallback.
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
Then you can just do:
input.putCursorAtEnd();
In some cases, this might happen when:
obj = new obj();
...
obj.Dispose(); // <----------------- Incorrect disposal causes it
obj.abc...
As from Android developer guide :
"orientation" The screen orientation has changed — the user has rotated the device. Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.
"screenSize" The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device). Added in API level 13.
So, in the AndroidManifest.xml file, we can put:
<activity
android:name=".activities.role_activity.GeneralViewPagerActivity"
android:label="@string/title_activity_general_view_pager"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize"
>
</activity>
Rachel's solution is working fine, although you need to use the third party script from raw.githubusercontent.com
By now there is a feature they show on the landing page when advertisng the "modular" script. You can see a legend there with this structure:
<div class="labeled-chart-container">
<div class="canvas-holder">
<canvas id="modular-doughnut" width="250" height="250" style="width: 250px; height: 250px;"></canvas>
</div>
<ul class="doughnut-legend">
<li><span style="background-color:#5B90BF"></span>Core</li>
<li><span style="background-color:#96b5b4"></span>Bar</li>
<li><span style="background-color:#a3be8c"></span>Doughnut</li>
<li><span style="background-color:#ab7967"></span>Radar</li>
<li><span style="background-color:#d08770"></span>Line</li>
<li><span style="background-color:#b48ead"></span>Polar Area</li>
</ul>
</div>
To achieve this they use the chart configuration option legendTemplate
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
You can find the doumentation here on chartjs.org This works for all the charts although it is not part of the global chart configuration.
Then they create the legend and add it to the DOM like this:
var legend = myPie.generateLegend();
$("#legend").html(legend);
Sample See also my JSFiddle sample
Rather than relying on key codes, which can be quite cumbersome, you can instead use regular expressions. By changing the pattern we can easily restrict the input to fit our needs. Note that this works with the keypress
event and will allow the use of backspace (as in the accepted answer). It will not prevent users from pasting 'illegal' chars.
function testInput(event) {_x000D_
var value = String.fromCharCode(event.which);_x000D_
var pattern = new RegExp(/[a-zåäö ]/i);_x000D_
return pattern.test(value);_x000D_
}_x000D_
_x000D_
$('#my-field').bind('keypress', testInput);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>_x000D_
Test input:_x000D_
<input id="my-field" type="text">_x000D_
</label>
_x000D_
I Hope that will help
$.each(myobj, function(index, value) {
console.log(myobj[index]);
)};
From this answer I've known a CORS Everywhere Firefox extension and it works for me. It creates MITM proxy intercepting headers to disable CORS. You can find the extension at addons.mozilla.org or here.
This one works for me very well. (https?|ftp)://(www\d?|[a-zA-Z0-9]+)?\.[a-zA-Z0-9-]+(\:|\.)([a-zA-Z0-9.]+|(\d+)?)([/?:].*)?
You can specify minDate as today by adding minDate: 0
to the options.
$("input.DateFrom").datepicker({
minDate: 0,
...
});
make sure your body and divs have not a
position:fixed
else it would not work
The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor
" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog
"
By disabling the post processor had stopped throwing those errors.
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
You can use some div or span instead of button and then on click call some function which submits form at he end.
<form id="my_form">
<span onclick="submit()">submit</span>
</form>
<script>
function submit()
{
//do something
$("#my_form").submit();
}
</script>
You need to add the ruby gem executable directory to your path
export PATH=$PATH:/opt/ruby-enterprise-1.8.7-2010.02/bin
As of today (Feb 27), there is a new For-Each toolbox on the MATLAB File Exchange that accomplishes the concept of foreach
. foreach
is not a part of the MATLAB language but use of this toolbox gives us the ability to emulate what foreach
would do.
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
You can remove it completely by specifying:
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
...
@Configuration
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public static MainApp { ... }
However, do note that doing so will probably cause servlet container's whitelabel pages to show up instead :)
EDIT: Another way to do this is via application.yaml. Just put in the value:
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
For Spring Boot < 2.0, the class is located in package org.springframework.boot.autoconfigure.web
.
Taking the answer above as guidance;
I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.
Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.
The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.
Thanks to the guy above for the idea!
If the place you're gonna paste have no problem with pasting a table formating (like the browser URL bar), I think the easiest way is this:
Sheets(1).Range("A1000").Value = string
Sheets(1).Range("A1000").Copy
MsgBox "Paste before closing this dialog."
Sheets(1).Range("A1000").Value = ""
To get a local timestamp using datetime library, Python 3.x
#wanted format: year-month-day hour:minute:seconds
from datetime import datetime
# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')
# print it to screen
print(timeStamp)
I might be late to the party, but as per my understanding , you're looking for something like this :
for(String params : Collections.list(httpServletRequest.getParameterNames())) {
// Whatever you want to do with your map
// Key : params
// Value : httpServletRequest.getParameter(params)
}
export class ClassName extends Component{
constructor(props){
super(props);
this.state = {
id:parseInt(props.match.params.id,10)
}
}
render(){
return(
//Code
{this.state.id}
);
}
What's worked for me recently is to remove all height=""
and width=""
attributes from the <svg>
tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.
Before:
<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
After:
<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
For Windows users there's an additional user friendly option: CloneVDI Tool by mpack. It's a GUI front-end to VBoxManage that makes things a little easier to work with.
http://forums.virtualbox.org/viewtopic.php?f=6&t=22422
As Alexander M. mentioned, you'll still have to use GParted, Partition Magic or a similar partition editor to grow your partition to the newly allocated physical drive. To do this just download the GParted iso, mount it as a bootable drive in the VirtualBox and boot from it.
I do not think there is a method for that. The fragment rebuilds it's UI on onCreateView()... but that happens when the fragment is created or recreated.
You'll have to implement your own updateUI method or where you will specify what elements and how they should update. It's rather a good practice, since you need to do that when the fragment is created anyway.
However if this is not enough you could do something like replacing fragment with the same one forcing it to call onCreateView()
FragmentTransaction tr = getFragmentManager().beginTransaction();
tr.replace(R.id.your_fragment_container, yourFragmentInstance);
tr.commit()
NOTE
To refresh ListView you need to call notifyDataSetChanged()
on the ListView's adapter.
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
None, False and True
all are available within template tags and filters. None, False
, the empty string ('', "", """"""
) and empty lists/tuples all evaluate to False
when evaluated by if
, so you can easily do
{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}
A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:
# someapp/models.py
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
# other fields
def get_full_name(self):
if not self.user.first_name:
return
return ' '.join([self.user.first_name, self.user.last_name])
# template
{{ user.get_profile.get_full_name }}
Hope this helps :)
<form class="upload-form">
<input class="upload-file" data-max-size="2048" type="file" >
<input type=submit>
</form>
<script>
$(function(){
var fileInput = $('.upload-file');
var maxSize = fileInput.data('max-size');
$('.upload-form').submit(function(e){
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
alert('file size is more then' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct- '+fileSize+' bytes');
}
}else{
alert('choose file, please');
return false;
}
});
});
</script>
It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.
jQuery.fn.mouseIsOver = function () {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
In case someone else stumbles here... you can set padding as well, for instance:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
int padding = 200 // padding left and right
toolbar.setPadding(padding, toolbar.getPaddingTop(), padding, toolbar.getPaddingBottom());
Or contentInset:
toolbar.setContentInsetsAbsolute(toolbar.getContentInsetLeft(), 200);
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
$(`input[id="${this.name}"]`).hide();
As you're using an ID, this would perform better
$(`#${this.name}`).hide();
I highly recommend being more specific with your approach to hiding elements via button clicks. I would opt for using data-attributes instead. For example
<input id="bx" type="text">
<button type="button" data-target="#bx" data-method="hide">Hide some input</button>
Then, in your JavaScript
// using event delegation so no need to wrap it in .ready()
$(document).on('click', 'button[data-target]', function() {
var $this = $(this),
target = $($this.data('target')),
method = $this.data('method') || 'hide';
target[method]();
});
Now you can completely control which element you're targeting and what happens to it via the HTML. For example, you could use data-target=".some-class"
and data-method="fadeOut"
to fade-out a collection of elements.
Eclipse likes lots of RAM. Use at least -Xmx512M. More if available.
This can sometimes be an issue with a postgres upgrade.
In my case, it happened when upgrading from 9.3 to 9.4.
See http://www.postgresql.org/docs/9.4/static/upgrading.html
OS X/Homebrew:
Try running postgres -D /usr/local/var/postgres
-- it will give you a much more verbose output if postgres fails to start.
In my case, running rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8
removed my old databases and then reinitialized the postgres db schema.
Thanks to https://github.com/Homebrew/homebrew/issues/35240 for that solution.
After regenerating my databases (with rake db:create
) everything worked fine again.
you can just use this code to hit the script using cron job using cpanel:
wget https://www.example.co.uk/unique-code
The other answers didn't work for me. This did:
<div class="span6">
<h2>Document</h2>
</p>
<textarea class="field span12" id="textarea" rows="6" placeholder="Enter a short synopsis"></textarea>
<button class="btn">Upload</button>
</div>
Note the span12
in a div with span6
.
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
Further to @cw24's answer • as of Laravel 5.4
you would instead have the following amendment in public/index.php
try {
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
} catch(\Exception $e) {
echo "<pre>";
echo $e;
echo "</pre>";
}
And in my case, I had forgotten to fire up MySQL.
Which, by the way, is usually mysql.server start
in Terminal
I've create a ClassPathResourceReader class in a java 8 way to make easy read files from classpath
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
public final class ClassPathResourceReader {
private final String path;
private String content;
public ClassPathResourceReader(String path) {
this.path = path;
}
public String getContent() {
if (content == null) {
try {
ClassPathResource resource = new ClassPathResource(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
content = reader.lines().collect(Collectors.joining("\n"));
reader.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return content;
}
}
Utilization:
String content = new ClassPathResourceReader("data.sql").getContent();
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
simply change <div>
to <tbody>
<table id="authenticationSetting" style="display: none">
<tbody id="authenticationOuterIdentityBlock" style="display: none;">
<tr>
<td class="orionSummaryHeader">
<orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
<td class="orionSummaryColumn">
<orion:textbox id="authenticationOuterIdentity" size="30" />
</td>
</tr>
</tbody>
</table>
Here is the code of removing duplicates values from NSMutable Array..it will work for you. myArray is your Mutable Array that you want to remove duplicates values..
for(int j = 0; j < [myMutableArray count]; j++){
for( k = j+1;k < [myMutableArray count];k++){
NSString *str1 = [myMutableArray objectAtIndex:j];
NSString *str2 = [myMutableArray objectAtIndex:k];
if([str1 isEqualToString:str2])
[myMutableArray removeObjectAtIndex:k];
}
} // Now print your array and will see there is no repeated value
I have come accross the above issue. I have solved it as below. Its working fine for me.
Download the 'org.apache.commons.io.jar' file on navigating to [org.apache.commons.io.FileUtils] [ http://www.java2s.com/Code/Jar/o/Downloadorgapachecommonsiojar.htm ]
Extract the downloaded zip file to a specified folder.
Update the project properties by using below navigation Right click on project>Select Properties>Select Java Build Path> Click Libraries tab>Click Add External Class Folder button>Select the folder where zip file is extracted for org.apache.commons.io.FileUtils.zip file.
Now access the File Utils.
For those who reached here searching if they could undo git clean -f -d
, by which a file created in eclipse was deleted,
You can do the same from the UI using "restore from local history" for ref:Restore from local history
Use platform specific socket functions to encapsulate the HTTP protocol, just like guys behind Apache did.
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
Date
has the time part, so we only need to extract it from Date
I personally prefer the default format
parameter of the Date
when date and time needs to be separated instead of using the extra SimpleDateFormat
Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")
println "datePart : " + datePart + "\ttimePart : " + timePart
You'll need to add the other repository as a remote, then fetch its changes. From there you see the commit and you can cherry-pick it.
Like that:
git remote add other https://example.link/repository.git
git fetch other
Now you have all the information to simply do git cherry-pick
.
More info about working with remotes here: https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes
It is possible. Here is some step by step:
In $PROJECT_DIR/jni/Application.mk:
APP_STL := stlport_static
I tried using stlport_shared, but no luck. Same with libstdc++.
In $PROJECT_DIR/jni/Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
Nothing special here, but make sure your files are .cpp.
In $PROJECT_DIR/jni/hello-jni.cpp:
#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <iostream>
#include <vector>
#define LOG_TAG "hellojni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
// Comments omitted.
void
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
std::vector<std::string> vec;
// Go ahead and do some stuff with this vector of strings now.
}
#ifdef __cplusplus
}
#endif
The only thing that bite me here was #ifdef __cplusplus.
Watch the directories.
To compile, use ndk-build clean && ndk-build
.
I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.
I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly.
Here is the syntax:
set terminal pdf {monochrome|color|colour}
{{no}enhanced}
{fname "<font>"} {fsize <fontsize>}
{font "<fontname>{,<fontsize>}"}
{linewidth <lw>} {rounded|butt}
{solid|dashed} {dl <dashlength>}}
{size <XX>{unit},<YY>{unit}}
and an example:
set terminal pdfcairo monochrome enhanced font "Times-New-Roman,12" dashed
I don't know about CSS but this Javascript code should work:
function getBrowserSize(){
var w, h;
if(typeof window.innerWidth != 'undefined')
{
w = window.innerWidth; //other browsers
h = window.innerHeight;
}
else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
{
w = document.documentElement.clientWidth; //IE
h = document.documentElement.clientHeight;
}
else{
w = document.body.clientWidth; //IE
h = document.body.clientHeight;
}
return {'width':w, 'height': h};
}
if(parseInt(getBrowserSize().width) < 1026){
document.getElementById("fadeshow1").style.display = "none";
}
For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/
But basically:
To install it:
npm install vue-fragment
To use it:
import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);
// or
import { Plugin } from 'vue-fragment';
Vue.use(Plugin);
Then, in your component:
<template>
<fragment>
<tr class="hola">
...
</tr>
<tr class="hello">
...
</tr>
</fragment>
</template>
create two Date
objects and call valueOf()
on both, then compare them.
I agree the above approved answer. But usually I use $results->isNotEmpty()
method as given below.
if($results->isNotEmpty())
{
//do something
}
It's more verbose than if(!results->isEmpty())
because sometimes we forget to add '!' in front which may result in unwanted error.
Note that this method exists from version 5.3 onwards.
What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json
and you will see JSON output. render :json
essentially calls to_json
and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback
option to specify the name of the callback you would like to call via JSONP.
For instance, lets say we have a User
model that looks like this: {name: 'Max', email:' [email protected]'}
We also have a controller that looks like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
end
end
Now, if we do an AJAX call using jQuery like this:
$.ajax({
type: "GET",
url: "/users/5",
dataType: "json",
success: function(data){
alert(data.name) // Will alert Max
}
});
As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.
To give an example of the callback
option, take a look at the following:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user, callback: "testFunction"
end
end
Now we can crate a JSONP request as follows:
function testFunction(data) {
alert(data.name); // Will alert Max
};
var script = document.createElement("script");
script.src = "/users/5";
document.getElementsByTagName("head")[0].appendChild(script);
The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.
In Mongoose, we can update array value using $set
inside dot(.
) notation to specific value in following way
db.collection.update({"_id": args._id, "viewData._id": widgetId}, {$set: {"viewData.$.widgetData": widgetDoc.widgetData}})
Try this :
####################
# GZIP COMPRESSION #
####################
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip
I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)
There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12
from operator import itemgetter
from itertools import groupby
lki = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
lki.sort(key=itemgetter(1))
glo = [[x for x,y in g]
for k,g in groupby(lki,key=itemgetter(1))]
print glo
.
EDIT
Another solution that needs no import , is more readable, keeps the orders, and is 22 % shorter than the preceding one:
oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
newlist, dicpos = [],{}
for val,k in oldlist:
if k in dicpos:
newlist[dicpos[k]].extend(val)
else:
newlist.append([val])
dicpos[k] = len(dicpos)
print newlist
For getting all post parameters there is Map which contains request param name as key and param value as key.
Map params = servReq.getParameterMap();
And to get parameters with known name normal
String userId=servReq.getParameter("user_id");
List and Set are two subclasses of Collection.
In List, data is in particular order.
In Set, it can not contain the same data twice.
In Collection, it just stores data with no particular order and can contain duplicate data.
You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.
Upload using Object Model:
String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
In My case, I've written below code in build.gradle
android {
// ...
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false
// ...
}
It's work for me!...
I'm using GitWebAccess for many projects for half a year now, and it's proven to be the best of what I've tried. It seems, though, that lately sources are not supported, so - don't take latest binaries/sources. Currently they're broken :(
You can build from this version or download compiled binaries which I use from here.
[ngStyle] with condition based if and else case.
<label for="file" [ngStyle]="isPreview ? {'cursor': 'default'} : {'cursor': 'pointer'}">Attachment
[a-zA-Z]{2}\d{6}
[a-zA-Z]{2}
means two letters
\d{6}
means 6 digits
If you want only uppercase letters, then:
[A-Z]{2}\d{6}
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
I don't know why nobody mention Carbon yet.
https://github.com/briannesbitt/Carbon
This is actually an extension to php dateTime (which was already used here) and it has: diffForHumans method. So all you need to do is:
$dt = Carbon::parse('2012-9-5 23:26:11.123789');
echo $dt->diffForHumans();
more examples: http://carbon.nesbot.com/docs/#api-humandiff
Pros of this solution:
Until today, for since at least 3 months ago, I regularly encountered hundreds of tree conflicts when attempting to merge a branch back into the trunk (using TortoiseSVN 1.11). Whether rebased or not, BTW. I've been using TortoiseSVN since its v1, back in 2004, and I used to reintegrate branches all the time. Something must have happened recently I suppose?
So today I ran this simple experiment, and I found what was creating these crazy conflicts:
Discussion: (see attachment)
all revisions... of what? Little did I know that the client must have been referring to "all revisions of the target! (trunk)", as, in the process of reintegrating that branch, I saw the mention "Merging revisions 1-HEAD"! OMG. Poor Devil, you're falling to your death here. That branch was born @393, can't you read its birth certificate, for God's sake?
Resolution:
Moral: I can't comprehend why they still haven't fixed that bug, because it is one, I'm sorry. I should take the time to report this with them.
You can use git reset
. This will 'unstage' all the files you've added after your last commit.
If you want to unstage only some files, use git reset -- <file 1> <file 2> <file n>
.
Also it's possible to unstage some of the changes in files by using git reset -p
.
Noneof the answers worked for me, I was getting "'HttpRequestBase' does not contain a definition for 'Query'", but this did work:
HttpContext.Current.Request.QueryString["index"]
Above tools extract the jar. Also there are certain other tools and commands to extract the jar. But AFAIK you cant get the java code in case code has been obfuscated.
I believe it means 'anything but a whitespace character'.
GraphQL query format was designed in order to allow:
However, according to GraphQL documentation, you may create fragments in order to make selection sets more reusable:
# Only most used selection properties
fragment UserDetails on User {
id,
username
}
Then you could query all user details by:
FetchUsers {
users() {
...UserDetails
}
}
You can also add additional fields alongside your fragment:
FetchUserById($id: ID!) {
users(id: $id) {
...UserDetails
count
}
}
The parent directory of an included file would be
dirname(getcwd())
e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php
then by calling /file/index.php
getcwd() is /var/www/html/folder
__DIR__ is /var/www/html/folder/inc
so dirname(__DIR__) is /var/www/html/folder
but what we want is /var/www/html which is dirname(getcwd())
in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.
1- hsqldb.jar
2- jackcess 2.0.4.jar
3- commons-lang-2.6.jar
4- commons-logging-1.1.1.jar
5- ucanaccess-2.0.8.jar
add these libraries to your java project and start with following lines.
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();
path could be like E:/Project/JAVA/DBApp
and then your query to be executed. Like
ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));
certain imports to be used. try catch block must be used and some necessary things no to be forgotten.
Remember, no need of bridging drivers like jdbc odbc or any stuff.
static
means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
Because of use of a static
keyword main()
is your first method to be invoked..
static
doesn't need to any object to instance...
so,main( )
is called by the Java interpreter before any objects are made.
purrr::flatten_*()
is also a good option. the flatten_*
functions add thin sanity checks and ensure type safety.
myList <- list('A'=1, 'B'=2, 'C'=3)
purrr::flatten_dbl(myList)
## [1] 1 2 3
site-packages
is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install
), you will find the installed modules in site-packages
by default.
There are standard locations:
prefix/lib/pythonX.Y/site-packages
exec-prefix/lib/pythonX.Y/site-packages
prefix\Lib\site-packages
1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.
site-packages
is by default part of the Python search path, so modules installed there can be imported easily afterwards.
Got the solution
Go to references right click the desired dll you will get option "Embed Interop Types" to "False" or "True".
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
you can set margin based on screen resolution
@media screen and (min-width:768px) and (max-width:991px) {
body {
margin-top:100px;
}
@media screen and (min-width:992px) and (max-width:1199px) {
body {
margin-top:50px;
}
}
body{
padding-top: 10%;
}
#nav{
position: fixed;
background-color: #8b0000;
width: 100%;
top:0;
}
The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.
$list = ['string1', 'string2', 'string3'];
$index = array_search('string2',array_values($list));
If You are creating table in mysql then use following :
create table package_template_mapping (
mapping_id int(10) not null auto_increment ,
template_id int(10) NOT NULL ,
package_id int(10) NOT NULL ,
remark varchar(100),
primary key (mapping_id) ,
UNIQUE KEY template_fun_id (template_id , package_id)
);
Swift 4
Don't forget to write ".first as? CustomView".
if let customView = Bundle.main.loadNibNamed("myXib", owner: self, options: nil)?.first as? CustomView {
self.view.addSubview(customView)
}
If you want to use anywhere
The Best Solution is Robert Gummesson's answer.
extension UIView {
class func fromNib<T: UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}
Then call it like this:
let myCustomView: CustomView = UIView.fromNib()
The trick seems to be understanding that the .git
directory for submodules are now kept in the master repository, under .git/modules
, and each submodule has a .git
file that points to it. This is the procedure you need now:
.git
file in the submodule's working directory, and modify the path it contains so that it points to the right directory in the master repository's .git/modules
directory..git/modules
directory, and find the directory corresponding to your submodule.config
file, updating the worktree
path so that it points to the new location of the submodule's working directory..gitmodules
file in the root of the master repository, updating the path to the working directory of the submodule.git add -u
git add <parent-of-new-submodule-directory>
(It's important that you add the parent, and not the submodule directory itself.)A few notes:
[submodule "submodule-name"]
lines in .gitmodules
and .git/config
must match each other, but don't correspond to anything else..git
directory must correctly point to each other..gitmodules
and .git/config
files should be synchronised.It looks like there's an extra space character in your string. You can use trim()
to remove leading and trailing whitespaces:
temp1 = Integer.parseInt(display.getText().trim(), 16 );
Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.
Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.
nohup ./my-script-that-may-take-long-to-finish.sh & ./check-if-previous-script-ran-or-exit.sh
echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt
So in the second one you just check if the file exists.
Just set the label
and tooltip
options like so
...
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
}
Fiddle - http://jsfiddle.net/g19220r6/
you can use CSharpProvider:
var code = @"
public class Abc {
public string Get() { return ""abc""; }
}
";
var options = new CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = false;
var provider = new CSharpCodeProvider();
var compile = provider.CompileAssemblyFromSource(options, code);
var type = compile.CompiledAssembly.GetType("Abc");
var abc = Activator.CreateInstance(type);
var method = type.GetMethod("Get");
var result = method.Invoke(abc, null);
Console.WriteLine(result); //output: abc
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
For people using a mac. When you're using different host names say test.local and test2.local. Try changing test.local to test.dev. I found out that Mac OS X lion controls the .local tld. So when you change it to something else it's faster.
And of course use above suggestions like turning off the ipv6 reference in your hosts file:
#::1 localhost
and setting this in the hosts file: 127.0.0.1 localhost
so it points to ipv4.
In my case this solution is useful:
Solution: Disable the "Just My Code" option in the Debugging/General settings.
Reference: c-sharpcorner
A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true
or false
.
.attr("hidden", false)
will remove the attribute the same as using .removeAttr("hidden")
.
.attr("hidden", "false")
is incorrect and the tag remains hidden.
You should not be setting hidden
, checked
, selected
, or several others to any string value to toggle it.
Just add ?author=<emailaddress>
or ?author=<githubUserName>
to the url when viewing the "commits" section of a repo.
Yes, some how the ajax call aborted. The cause may be following.
Installing XCode requires:
To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:
https://github.com/kennethreitz/osx-gcc-installer
The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.
The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.
I was looking for a different answer for the question title, so maybe other people will be too.
To set type as an ObjectId (so you may reference author
as the author of book
, for example), you may do like:
const Book = mongoose.model('Book', {
author: {
type: mongoose.Schema.Types.ObjectId, // here you set the author ID
// from the Author colection,
// so you can reference it
required: true
},
title: {
type: String,
required: true
}
});
As the rank doesn't depend at all from the contacts
RANKED_RSLTS
QRY_ID | RES_ID | SCORE | RANK
-------------------------------------
A | 1 | 15 | 3
A | 2 | 32 | 1
A | 3 | 29 | 2
C | 7 | 61 | 1
C | 9 | 30 | 2
Thus :
SELECT
C.*
,R.SCORE
,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT *,
MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
FROM RSLTS) R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID
A good solution here for VSCode users, if a string breaking down into multiple lines causes the problem (I faced this when I had to test a long JWT token, and somehow using template literals didn't do the trick.)
retval.Direction = ParameterDirection.Output;
ParameterDirection.ReturnValue
should be used for the "return value" of the procedure, not output parameters. It gets the value returned by the SQL RETURN
statement (with the parameter named @RETURN_VALUE
).
Instead of RETURN @b
you should SET @b = something
By the way, return value parameter is always int
, not string.
You can run the dropdb command from the command line:
dropdb 'database name'
Note that you have to be a superuser or the database owner to be able to drop it.
You can also check the pg_stat_activity
view to see what type of activity is currently taking place against your database, including all idle processes.
SELECT * FROM pg_stat_activity WHERE datname='database name';
Note that from PostgreSQL v13 on, you can disconnect the users automatically with
DROP DATABASE dbname FORCE;
or
dropdb -f dbname
Quoting API on referencedColumnName:
The name of the column referenced by this foreign key column.
Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.
Where this would be used?
When there is a composite PK in referenced table, then you need to specify column name you are referencing.
Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.
to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
From R 3.0.0 onwards mean(<data.frame>)
is defunct (and passing a data.frame to mean
will give the error you state)
A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".
In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following
lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)
In your Case you can write the following jquery code:
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").attr("readonly", false);
}
else{
$("#no_of_staff").attr("readonly", true);
}
});
});
Here is the Fiddle: http://jsfiddle.net/P4QWx/3/
For those looking for a Java implementation of a MBDB file reader, there are several out there:
"iPhone Analyzer" project (very clean code): http://sourceforge.net/p/iphoneanalyzer/code/HEAD/tree/trunk/library/src/main/java/com/crypticbit/ipa/io/parser/manifest/Mbdb.java
"iPhone Stalker" project: https://code.google.com/p/iphonestalker/source/browse/trunk/src/iphonestalker/util/io/MBDBReader.java
There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).
## list of columns
l1 = ['PM2.5', 'PM10', 'TEMP', 'BP', ' RH', 'WS','CO', 'O3', 'Nox', 'SO2']
for i in l1:
for j in range(0, 8431): #rows = 8431
df[i][j] = int(df[i][j])
I recommend you to use this only with small data. This code has complexity of O(n^2).
ECMAScript5 provides a map
method for Array
s, applying a function to all elements of an array.
Here is an example:
var a = ['1','2','3']
var result = a.map(function (x) {
return parseInt(x, 10);
});
console.log(result);
_x000D_
I'm pretty new to vba & excel - only been doing this for about 3 months - I thought I'd share my array de-duplication method here as this post seems relevant to it:
This code if part of a bigger application that analyses pipe data- Pipes are listed in a sheet with number in xxxx.1, xxxx.2, yyyy.1, yyyy.2 .... format. so thats why all the string manipulation exists. basically it only collects the pipe number once only, and not the .2 or .1 part.
With wbPreviousSummary.Sheets(1)
' here, we will write the edited pipe numbers to a collection - then pass the collection to an array
Dim PipeDict As New Dictionary
Dim TempArray As Variant
TempArray = .Range(.Cells(3, 2), .Cells(3, 2).End(xlDown)).Value
For ele = LBound(TempArray, 1) To UBound(TempArray, 1)
If Not PipeDict.Exists(Left(TempArray(ele, 1), Len(TempArray(ele, 1) - 2))) Then
PipeDict.Add Key:=Left(TempArray(ele, 1), Len(TempArray(ele, 1) - 2)), _
Item:=Left(TempArray(ele, 1), Len(TempArray(ele, 1) - 2))
End If
Next ele
TempArray = PipeDict.Items
For ele = LBound(TempArray) To UBound(TempArray)
MsgBox TempArray(ele)
Next ele
End With
wbPreviousSummary.Close SaveChanges:=False
Set wbPreviousSummary = Nothing 'done early so we dont have the information loaded in memory
Using a heap of message boxes for debugging atm - im sure you'll change it to suit your own work.
I hope people find this useful, Regards Joe
I managed to stop the video using "get(0)" (Retrieve the DOM elements matched by the jQuery object):
$("#closeSimple").click(function() {
$("div#simpleModal").removeClass("show");
$("#videoContainer").get(0).pause();
return false;
});
This is a very broad question, so I am going to give a broad answer.
That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.
if you running docker under docker-machine?
execute to get ip:
docker-machine ip <machine>
returns the ip for the machine and try connect mysql:
mysql -h<docker-machine-ip>
Install tk-devel
(or a similarly-named package) before building Python.
This is not really an answer to the present question, however it might help others too.
At least I can tell there is a technical limit of 32767 values (=Short.MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1.
This is a test of "delete from x where id in (... 100k values...)" with the postgresql jdbc driver:
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 100000
at org.postgresql.core.PGStream.SendInteger2(PGStream.java:201)
Try find
. You can look it up exactly in the man page, but it's sorta like this:
find [start directory] -name [what to find]
so for your example
find . -name "*.txt"
should give you what you want.
def xstr(s):
return s or ""
In [16]: def shuffle(df, n=1, axis=0):
...: df = df.copy()
...: for _ in range(n):
...: df.apply(np.random.shuffle, axis=axis)
...: return df
...:
In [17]: df = pd.DataFrame({'A':range(10), 'B':range(10)})
In [18]: shuffle(df)
In [19]: df
Out[19]:
A B
0 8 5
1 1 7
2 7 3
3 6 2
4 3 4
5 0 1
6 9 0
7 4 6
8 2 8
9 5 9
Phew, Django documentation really does not have good example about this. I spent over 2 hours to dig up all the pieces to understand how this works. With that knowledge I implemented a project that makes possible to upload files and show them as list. To download source for the project, visit https://github.com/axelpale/minimal-django-file-upload-example or clone it:
> git clone https://github.com/axelpale/minimal-django-file-upload-example.git
Update 2013-01-30: The source at GitHub has also implementation for Django 1.4 in addition to 1.3. Even though there is few changes the following tutorial is also useful for 1.4.
Update 2013-05-10: Implementation for Django 1.5 at GitHub. Minor changes in redirection in urls.py and usage of url template tag in list.html. Thanks to hubert3 for the effort.
Update 2013-12-07: Django 1.6 supported at GitHub. One import changed in myapp/urls.py. Thanks goes to Arthedian.
Update 2015-03-17: Django 1.7 supported at GitHub, thanks to aronysidoro.
Update 2015-09-04: Django 1.8 supported at GitHub, thanks to nerogit.
Update 2016-07-03: Django 1.9 supported at GitHub, thanks to daavve and nerogit
A basic Django 1.3 project with single app and media/ directory for uploads.
minimal-django-file-upload-example/
src/
myproject/
database/
sqlite.db
media/
myapp/
templates/
myapp/
list.html
forms.py
models.py
urls.py
views.py
__init__.py
manage.py
settings.py
urls.py
To upload and serve files, you need to specify where Django stores uploaded files and from what URL Django serves them. MEDIA_ROOT and MEDIA_URL are in settings.py by default but they are empty. See the first lines in Django Managing Files for details. Remember also set the database and add myapp to INSTALLED_APPS
...
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'database.sqlite3'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
...
INSTALLED_APPS = (
...
'myapp',
)
Next you need a model with a FileField. This particular field stores files e.g. to media/documents/2011/12/24/ based on current date and MEDIA_ROOT. See FileField reference.
# -*- coding: utf-8 -*-
from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
To handle upload nicely, you need a form. This form has only one field but that is enough. See Form FileField reference for details.
# -*- coding: utf-8 -*-
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
A view where all the magic happens. Pay attention how request.FILES
are handled. For me, it was really hard to spot the fact that request.FILES['docfile']
can be saved to models.FileField just like that. The model's save() handles the storing of the file to the filesystem automatically.
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myapp.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'myapp/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in developement stage.
See django.conf.urls.static.static reference for details. See also this discussion about serving media files.
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
(r'^', include('myapp.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
To make the view accessible, you must specify urls for it. Nothing special here.
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns('myapp.views',
url(r'^list/$', 'list', name='list'),
)
The last part: template for the list and the upload form below it. The form must have enctype-attribute set to "multipart/form-data" and method set to "post" to make upload to Django possible. See File Uploads documentation for details.
The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
Just run syncdb and runserver.
> cd myproject
> python manage.py syncdb
> python manage.py runserver
Finally, everything is ready. On default Django developement environment the list of uploaded documents can be seen at localhost:8000/list/
. Today the files are uploaded to /path/to/myproject/media/documents/2011/12/17/ and can be opened from the list.
I hope this answer will help someone as much as it would have helped me.
Based on Guy Daher's answer.
I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.
I would do nil check if statement:
class CustomView: UIView
{
override func draw(_ rect: CGRect)
{
super.draw(rect)
if let context = UIGraphicsGetCurrentContext()
{
context.setStrokeColor(UIColor.gray.cgColor)
context.setLineWidth(1)
context.move(to: CGPoint(x: 0, y: bounds.height))
context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
context.strokePath()
}
}
}
You need a reverse DNS entry. You need to not send the same content to the same user twice. You need to test it with some common webmail and email clients. Personally I ran mine through a freshly installed spam assassin, a trained spam assassin, and multiple hotmail, gmail, and aol accounts.
But have you seen that spam that doesn't seem to link to or advertise anything? That's a spammer trying to affect your Bayesian filter. If he can get a high rating and then include some words that would be in his future emails it might be automatically learned as good. So you can't really guess what a user's filter is going to be set as at the time of your mailing.
Lastly, I did not sort my list by the domains, but randomized it.
This is how I do you ajax pages... its a pretty easy method...
function ajax_urls() {
var objApps= ['ads','user'];
$("a.ajx").each(function(){
var url = $(this).attr('href');
for ( var i=0;i< objApps.length;i++ ) {
if (url.indexOf("/"+objApps[i]+"/")>-1) {
$(this).attr("href",url.replace("/"+objApps[i]+"/","/"+objApps[i]+"/#p="));
}
}
});
}
How this works is it basically looks at all URLs that have the class 'ajx' and it replaces a keyword and adds the # sign... so if js is turned off then the urls would act as they normally do... all "apps" (each section of the site) has its own keyword... so all i need to do is add to the js array above to add more pages...
So for example my current settings are set to:
var objApps= ['ads','user'];
So if i have a url such as:
www.domain.com/ads/3923/bla/dada/bla
the js script would replace the /ads/ part so my URL would end up being
www.domain.com/ads/#p=3923/bla/dada/bla
Then I use jquery bbq plugin to load the page accordingly...
For what it's worth, I eventually gave up on fighting with Web Deploy to get it to do what I wanted (copy deployable files and nothing else), so I scripted it in PowerShell and am really happy with the result. It's much faster than anything I tried through MSBuild/Web Publish, presumably because those methods were still doing things I didn't need.
Here's the gist (literally):
function copy-deployable-web-files($proj_path, $deploy_dir) {
# copy files where Build Action = "Content"
$proj_dir = split-path -parent $proj_path
[xml]$xml = get-content $proj_path
$xml.Project.ItemGroup | % { $_.Content } | % { $_.Include } | ? { $_ } | % {
$from = "$proj_dir\$_"
$to = split-path -parent "$deploy_dir\$_"
if (!(test-path $to)) { md $to }
cp $from $to
}
# copy everything in bin
cp "$proj_dir\bin" $deploy_dir -recurse
}
In my case I'm calling this in a CI environment (TeamCity), but it could easily be hooked into a post-build event as well.
I had the same issue as you, I figured it out. Facebook now roles some features as plugins. In the left hand side select Products and add product. Then select Facbook Login. Pretty straight forward from there, you'll see all the Oauth options show up.
<div id="container">
<div><span>Two Words</span></div>
<div><span>Two Words</span></div>
<div><span>Two Words</span></div>
<div><span>Two Words</span></div>
</div>
#container{
width:450px;
height:200px;
margin:0px auto;
border:1px solid red;
}
#container div{
position:relative;
width:100px;
height:100px;
border:1px solid #ccc;
float:left;
margin-right:5px;
}
#container div span{
position:absolute;
bottom:0;
right:0;
}
Make sure your Main.class should be on top of your controllers. In case of the following example:
Main.class containing:
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
EmployeeController.class containing:
@RestController
public class EmployeeController {
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@RequestMapping(value = "/employee/save", method = RequestMethod.GET)
public String save(){
Employee newEmp = new Employee();
newEmp.setAge(25);
newEmp.setFirstName("Pikachu");
newEmp.setId(100);
return "Name: " + newEmp.getFirstName() + ", Age: " + newEmp.getAge() + ", Id = " + newEmp.getId();
}
}
If your main class is in the root folder, just like this path: {projectname}/src/main/java/main then make sure your controllers below your Main class. For example {projectname}/src/main/java/main/controllers.
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
All latest versions of mongodb updateMany() is working fine
db.getCollection('workers').updateMany({},{$set: {"assignedVehicleId" : "45680"}});
Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer:
# d = Pandas Dataframe,
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ]
def chart(d,ys):
from itertools import cycle
fig, ax = plt.subplots()
axes = [ax]
for y in ys[1:]:
# Twin the x-axis twice to make independent y-axes.
axes.append(ax.twinx())
extra_ys = len(axes[2:])
# Make some space on the right side for the extra y-axes.
if extra_ys>0:
temp = 0.85
if extra_ys<=2:
temp = 0.75
elif extra_ys<=4:
temp = 0.6
if extra_ys>5:
print 'you are being ridiculous'
fig.subplots_adjust(right=temp)
right_additive = (0.98-temp)/float(extra_ys)
# Move the last y-axis spine over to the right by x% of the width of the axes
i = 1.
for ax in axes[2:]:
ax.spines['right'].set_position(('axes', 1.+right_additive*i))
ax.set_frame_on(True)
ax.patch.set_visible(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
i +=1.
# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
cols = []
lines = []
line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
'1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
colors = cycle(matplotlib.rcParams['axes.color_cycle'])
for ax,y in zip(axes,ys):
ls=line_styles.next()
if len(y)==1:
col = y[0]
cols.append(col)
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
ax.set_ylabel(col,color=color)
#ax.tick_params(axis='y', colors=color)
ax.spines['right'].set_color(color)
else:
for col in y:
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
cols.append(col)
ax.set_ylabel(', '.join(y))
#ax.tick_params(axis='y')
axes[0].set_xlabel(d.index.name)
lns = lines[0]
for l in lines[1:]:
lns +=l
labs = [l.get_label() for l in lns]
axes[0].legend(lns, labs, loc=0)
plt.show()
for me worked to add this at the end of my view:
<script type="text/javascript">
$(document).ready(function(){
$("#myCarousel").carousel({
interval : 8000,
pause: false
});
});
</script>
it gives to the carousel an interval of 8 seconds
Are you using JavaScript or jQuery besides the html? If you are, you can do something like:
HTML:
<select id='some_selector'></select>?
jQuery:
var select = '';
for (i=1;i<=100;i++){
select += '<option val=' + i + '>' + i + '</option>';
}
$('#some_selector').html(select);
As you can see here.
Another option for compatible browsers instead of select, you can use is HTML5's input type=number
:
<input type="number" min="1" max="100" value="1">
Try setting its position
to absolute. That takes it out of the flow of the document.
Just an additional note about reflection: I have observed in some special cases, when several classes with the same name exist in different packages, that reflection as used in the top answer may fail to pick the correct class from the object. So if you know what is the package.class of the object, then it's better to access its private field values as follows:
org.deeplearning4j.nn.layers.BaseOutputLayer ll = (org.deeplearning4j.nn.layers.BaseOutputLayer) model.getLayer(0);
Field f = Class.forName("org.deeplearning4j.nn.layers.BaseOutputLayer").getDeclaredField("solver");
f.setAccessible(true);
Solver s = (Solver) f.get(ll);
(This is the example class that was not working for me)
Another option is http://localtunnel.me/ if you're running NodeJS
npm install -g localtunnel
Start a webserver on any local port such as 8080, and create a tunnel to that port:
lt -p 8080
which will return a public URL for your localhost at randomname.localtunnel.me. You can request your own subdomain if it's available:
lt -p 8080 -s myname
which will return myname.localtunnel.me
if key in array:
# do something
Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.
Take care of performance:
I experienced that at least with EF Core the different answers given here might result in different performance. I'm aware that the OP asked about Linq to SQL, but it seems to me that the same questions occur also with EF Core.
In a specific case I had to handle, the (syntactically nicer) suggestion by Marc Gravell resulted in left joins inside a cross apply -- similarly to what Mike U described -- which had the result that the estimated costs for this specific query were two times as high compared to a query with no cross joins. The server execution times differed by a factor of 3. [1]
The solution by Marc Gravell resulted in a query without cross joins.
Context: I essentially needed to perform two left joins on two tables each of which again required a join to another table. Furthermore, there I had to specify other where-conditions on the tables on which I needed to apply the left join. In addition, I had two inner joins on the main table.
Estimated operator costs:
Server execution times in ms (queries executed 10 times; measured using SET STATISTICS TIME ON):
(The very first run was slower for both queries; seems that something is cached.)
Table sizes:
EF Core version: 2.2.1.
SQL Server version: MS SQL Server 2017 - 14... (on Windows 10).
All relevant tables had indexes on the primary keys only.
My conclusion: it's always recommended to look at the generated SQL since it can really differ.
[1] Interestingly enough, when setting the 'Client statistics' in MS SQL Server Management Studio on, I could see an opposite trend; namely that last run of the solution without cross apply took more than 1s. I suppose that something was going wrong here - maybe with my setup.
From the MSDN website:
This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block.
So declare the variable outside the block.
Is Ruby pass by reference or by value?
Ruby is pass-by-reference. Always. No exceptions. No ifs. No buts.
Here is a simple program which demonstrates that fact:
def foo(bar)
bar.object_id
end
baz = 'value'
puts "#{baz.object_id} Ruby is pass-by-reference #{foo(baz)} because object_id's (memory addresses) are always the same ;)"
=> 2279146940 Ruby is pass-by-reference 2279146940 because object_id's (memory addresses) are always the same ;)
def bar(babar)
babar.replace("reference")
end
bar(baz)
puts "some people don't realize it's reference because local assignment can take precedence, but it's clearly pass-by-#{baz}"
=> some people don't realize it's reference because local assignment can take precedence, but it's clearly pass-by-reference
Use the getResourceAsStream()
method on the ServletContext object, e.g.
servletContext.getResourceAsStream("/WEB-INF/myfile");
How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?
EDITED: If you're inside a Servlet object, then call getServletContext()
. If you're in JSP, use the predefined variable application
.
Using ASCII(RIGHT(ProductAlternateKey, 1))
you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.
This can not be removed using the standard LTrim
RTrim
functions.
You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')
You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:
--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');
This list of potential white space characters could be used to create a function such as :
Create Function [dbo].[CleanAndTrimString]
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
--NULL
Set @MyString = Replace(@MyString,CHAR(0),'');
--Horizontal Tab
Set @MyString = Replace(@MyString,CHAR(9),'');
--Line Feed
Set @MyString = Replace(@MyString,CHAR(10),'');
--Vertical Tab
Set @MyString = Replace(@MyString,CHAR(11),'');
--Form Feed
Set @MyString = Replace(@MyString,CHAR(12),'');
--Carriage Return
Set @MyString = Replace(@MyString,CHAR(13),'');
--Column Break
Set @MyString = Replace(@MyString,CHAR(14),'');
--Non-breaking space
Set @MyString = Replace(@MyString,CHAR(160),'');
Set @MyString = LTRIM(RTRIM(@MyString));
Return @MyString
End
Go
Which you could then use as follows:
Select
dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
Just restarting Eclipse fixed the issue in my project
//this can be easily understandable for beginners
int score=12344534;
int div;
for (div = 1; div <= score; div *= 10)
{
}
/*for (div = 1; div <= score; div *= 10); for loop with semicolon or empty body is same*/
while(score>0)
{
div /= 10;
printf("%d\n`enter code here`", score / div);
score %= div;
}
The Request.Files collection contains any files uploaded with your form, regardless of whether they came from a FileUpload control or a manually written <input type="file">
.
So you can just write a plain old file input tag in the middle of your WebForm, and then read the file uploaded from the Request.Files collection.
This is what I recently did for my Data Visualization Application which has a 2008 SQL Database. In this example I am recieving a list returned from a stored procedure:
public List<CumulativeInstrumentsDataRow> GetCumulativeInstrumentLogs(RunLogFilter filter)
{
EFDbContext db = new EFDbContext();
if (filter.SystemFullName == string.Empty)
{
filter.SystemFullName = null;
}
if (filter.Reconciled == null)
{
filter.Reconciled = 1;
}
string sql = GetRunLogFilterSQLString("[dbo].[rm_sp_GetCumulativeInstrumentLogs]", filter);
return db.Database.SqlQuery<CumulativeInstrumentsDataRow>(sql).ToList();
}
And then this extension method for some formatting in my case:
public string GetRunLogFilterSQLString(string procedureName, RunLogFilter filter)
{
return string.Format("EXEC {0} {1},{2}, {3}, {4}", procedureName, filter.SystemFullName == null ? "null" : "\'" + filter.SystemFullName + "\'", filter.MinimumDate == null ? "null" : "\'" + filter.MinimumDate.Value + "\'", filter.MaximumDate == null ? "null" : "\'" + filter.MaximumDate.Value + "\'", +filter.Reconciled == null ? "null" : "\'" + filter.Reconciled + "\'");
}
Open a terminal:
Check MySQL system pref panel, if it says something along the line "Warning, /usr/local/mysql/data is not owned by 'mysql' or '_mysql'
If yes, go to the mysql folder cd /usr/local/mysql
do a sudo chown -R _mysql data/
This will change ownership of the /usr/local/mysql/data and all of its content to own by user '_mysql'
Check MySQL system pref panel, it should be saying it's running now, auto-magically. If not start again.
Another way to confirm is to do a
netstat -na | grep 3306
It should say:
tcp46 0 0 *.3306 *.* LISTEN
To see the process owner and process id of the mysqld:
ps aux | grep mysql
Of course, it doesn't necessarily have to be transmitted over TCP. I implemented HTTP on top of UDP, for use in the Satellite TV Broadcasting industry.
/**
* Formats seconds (number) to H:i:s format.
* 00:12:00
*
* When "short" option is set to true, will return:
* 0:50
* 2:00
* 12:00
* 1:00:24
* 10:00:00
*/
export default function formatTimeHIS (seconds, { short = false } = {}) {
const pad = num => num < 10 ? `0${num}` : num
const H = pad(Math.floor(seconds / 3600))
const i = pad(Math.floor(seconds % 3600 / 60))
const s = pad(seconds % 60)
if (short) {
let result = ''
if (H > 0) result += `${+H}:`
result += `${H > 0 ? i : +i}:${s}`
return result
} else {
return `${H}:${i}:${s}`
}
}
c1.set(2017, 12 , 01); //Ex: 1999 jan 20 //System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -2); // substract 1 month
System.out.println
("Date minus 1 month : "
+ sdf.format(c1.getTime()));
I had a similar issue and could not "compromise" with background images. I came up with this.
<div class="container">
<img src="http://lorempixel.com/800x600/nature">
</div>
.container {
position: relative;
width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
border: 2px solid #fff; /* just to separate the images */
overflow: hidden; /* "crop" the image */
background: #000; /* incase the image is wider than tall/taller than wide */
}
.container img {
position: absolute;
display: block;
height: 100%; /* all images at least fill the height */
top: 50%; /* top, left, transform trick to vertically and horizontally center image */
left: 50%;
transform: translate3d(-50%,-50%,0);
}
//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});
Hope this helps!
Example: https://jsfiddle.net/cfbuwxmr/1/
In case you need this to write a .properties
file you can just add the Strings into a Properties object and then save it to a file. It will take care for the conversion.
Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.
angular.module('mymodule', [])
// Click to navigate
// similar to <a href="#/partial"> but hash is not required,
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
return {
link: function(scope, element, attrs) {
element.on('click', function() {
scope.$apply(function() {
$location.path(attrs.clickLink);
});
});
}
}
}]);
It has some useful features, but I'm new to Angular so there's probably room for improvement.
Give your form an id only, and your input a name only:
<form id="myform">
<input type="text" name="foo">
Then the most standards-compliant and least problematic way to access your input element is via:
document.getElementById("myform").elements["foo"]
using .elements["foo"]
instead of just .foo
is preferable because the latter might return a property of the form named "foo" rather than a HTML element!
The type initializer for CrystalDecisions.CrystalReports.Engine.ReportDocument
threw an exception.
I changed the target platform from x86
to Any CPU
and it resolved the issue.
Before you use DecimalFormat you need to use the following import or your code will not work:
import java.text.DecimalFormat;
The code for formatting is:
DecimalFormat precision = new DecimalFormat("0.00");
// dblVariable is a number variable and not a String in this case
txtTextField.setText(precision.format(dblVariable));
ProcessBuilder is the Java 5/6 way to run external processes.
Use:
grep -- -X
Related: What does a bare double dash mean? (thanks to nutty about natty).
Import this in to app.module.ts
import {HttpClientModule} from '@angular/common/http';
and add this one in imports
HttpClientModule
Use ObjectDataProvider:
<ObjectDataProvider x:Key="enumValues"
MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:ExampleEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
and then bind to static resource:
ItemsSource="{Binding Source={StaticResource enumValues}}"
based on this article
This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk
public void SavePicture()
{
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("tablename");
byte[] MyData = new byte[0];
da.Fill(ds, "tablename");
DataTable table = ds.Tables["tablename"];
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow myRow;
myRow = ds.Tables["tablename"].Rows[i];
MyData = (byte[])myRow["Picture"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();
}
}
please note: Directory with NewFolder name should exist in C:\