You can also use callto:########### replacing the email code mail with call, at least according to W3Cschool site but I haven't had an opportunity to test it out.
The :target
-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target
It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr
Here is a tab example with :target
-pseudo selector.
Like there is reported in earlier answer the UITextView is able to handle touches on links. This can easily be extended by making other parts of the text work as links. The AttributedTextView library is a UITextView subclass that makes it very easy to handle these. For more info see: https://github.com/evermeer/AttributedTextView
You can make any part of the text interact like this (where textView1 is a UITextView IBOutlet):
textView1.attributer =
"1. ".red
.append("This is the first test. ").green
.append("Click on ").black
.append("evict.nl").makeInteract { _ in
UIApplication.shared.open(URL(string: "http://evict.nl")!, options: [:], completionHandler: { completed in })
}.underline
.append(" for testing links. ").black
.append("Next test").underline.makeInteract { _ in
print("NEXT")
}
.all.font(UIFont(name: "SourceSansPro-Regular", size: 16))
.setLinkColor(UIColor.purple)
And for handling hashtags and mentions you can use code like this:
textView1.attributer = "@test: What #hashtags do we have in @evermeer #AtributedTextView library"
.matchHashtags.underline
.matchMentions
.makeInteract { link in
UIApplication.shared.open(URL(string: "https://twitter.com\(link.replacingOccurrences(of: "@", with: ""))")!, options: [:], completionHandler: { completed in })
}
I've just came across the same problem and found the chrome extension Open IE.
That's the only one what works for me (Chrome V46 & V52). The only disadvantefge is, that you need to install an additional program, means you need admin rights.
This creates a "See Also" heading containing the link, i.e.:
/**
* @see <a href="http://google.com">http://google.com</a>
*/
will render as:
See Also:
http://google.com
whereas this:
/**
* See <a href="http://google.com">http://google.com</a>
*/
will create an in-line link:
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
ul.nav li a, ul.nav li a:visited {
color: #anycolor !important;
}
ul.nav li a:hover, ul.nav li a:active {
color: #anycolor !important;
}
ul.nav li.active a {
color: #anycolor !important;
}
Change the styles as you wish.
Under the hood BeautifulSoup now uses lxml. Requests, lxml & list comprehensions makes a killer combo.
import requests
import lxml.html
dom = lxml.html.fromstring(requests.get('http://www.nytimes.com').content)
[x for x in dom.xpath('//a/@href') if '//' in x and 'nytimes.com' not in x]
In the list comp, the "if '//' and 'url.com' not in x" is a simple method to scrub the url list of the sites 'internal' navigation urls, etc.
The anchor tag (link) also has pseudo-classes such as visited, hover, link and active. Make sure your style is applied to the state(s) in question and that no other styles are conflicting.
For example:
a:hover, a:visited, a:link, a:active
{
text-decoration: none;
}
See W3.org for more information on user action pseudo-classes :hover, :active, and :focus.
I'm using only android:autoLink="web"
and it works fine. A click on the link opens the browser and shows the correct page.
One thing I could guess is that some other view is above the link. Something that is transparent fills the whole parent but don't displays anything above the link. In this case the click goes to this view instead of the link.
This one good also to view cachepage http://www.cachepage.net
Cache page view via google: webcache.googleusercontent.com/search?q=cache: Your url
Cache page view via archive.org: web.archive.org/web/*/Your url
Why don't you just do this
<a href="yoururl.html"><div>...</div></a>
That should work fine and will prompt the "clickable item" cursor change, which the aforementioned solution will not do.
Organize your files in hierarchical directories and then just use relative paths.
Demo:
HTML (index.html)
<a href='inner/file.html'>link</a>
Directory structure:
base/
base/index.html
base/inner/file.html
....
You can auto generate Image map from this website for selected area of image. https://www.image-map.net/
Easiest way to execute!
This might be the most simple way to make a whole <td>
cell an active hyperlink just using HTML.
I never had a satisfactory answer for this question, until about 10 minutes ago, so years in the making #humor.
Tested on Firefox 70, this is a bare-bones example where one full line-width of the cell is active:
<td><a href=""><div><br /></div></a></td>
Obviously the example just links to "this document," so fill in the href=""
and replace the <br />
with anything appropriate.
Previously I used a style and class pair that I cobbled together from the answers above (Thanks to you folks.)
Today, working on a different issue, I kept stripping it down until <div> </div>
was the only thing left, remove the <div></div>
and it stops linking beyond the text. I didn't like the short "_" the
displayed and found a single <br />
works without an "extra line" penalty.
If another <td></td>
in the <tr>
has multiple lines, and makes the row taller with word-wrap for instance, then use multiple <br />
to bring the <td>
you want to be active to the correct number of lines and active the full width of each line.
The only problem is it isn't dynamic, but usually the mouse is closer in height than width, so active everywhere on one line is better than just the width of the text.
I use this for every external link:
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
if (anchors[i].hostname != window.location.hostname) {
anchors[i].setAttribute('target', '_blank');
}
}
}
below example with target="_blank"
works for Safari and Mozilla
<a href="http://www.starfall.com" `target="_blank"`>
Using target="new"
worked for Chrome
<a href="http://www.starfall.com" `target="new"`>
You can remove click for link by following;
$('#link-id').unbind('click');
You can re-enable link by followings,
$('#link-id').bind('click');
You can not use 'disabled' property for links.
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
Just append a #
followed by the ID of the <a>
tag (or other HTML tag, like a <section>
) that you're trying to get to. For example, if you are trying to link to the header in this HTML:
<p>This is some content.</p>
<h2><a id="target">Some Header</a></h2>
<p>This is some more content.</p>
You could use the link <a href="http://url.to.site/index.html#target">Link</a>
.
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
I'm not sure about the issue for making the top level anchor element a clickable anchor but here's the simplest solution for making desktop views have the hover effect, and mobile views maintaining their click-ability.
// Medium screens and up only
@media only screen and (min-width: $screen-md-min) {
// Enable menu hover for bootstrap
// dropdown menus
.dropdown:hover .dropdown-menu {
display: block;
}
}
This way the mobile menu still behaves as it should, while the desktop menu will expand on hover instead of on a click.
I know I'm kinda late to the party but I made a little method others might find cool/useful.
public static JLabel linkify(final String text, String URL, String toolTip)
{
URI temp = null;
try
{
temp = new URI(URL);
}
catch (Exception e)
{
e.printStackTrace();
}
final URI uri = temp;
final JLabel link = new JLabel();
link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
if(!toolTip.equals(""))
link.setToolTipText(toolTip);
link.setCursor(new Cursor(Cursor.HAND_CURSOR));
link.addMouseListener(new MouseListener()
{
public void mouseExited(MouseEvent arg0)
{
link.setText("<HTML><FONT color=\"#000099\">"+text+"</FONT></HTML>");
}
public void mouseEntered(MouseEvent arg0)
{
link.setText("<HTML><FONT color=\"#000099\"><U>"+text+"</U></FONT></HTML>");
}
public void mouseClicked(MouseEvent arg0)
{
if (Desktop.isDesktopSupported())
{
try
{
Desktop.getDesktop().browse(uri);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
JOptionPane pane = new JOptionPane("Could not open link.");
JDialog dialog = pane.createDialog(new JFrame(), "");
dialog.setVisible(true);
}
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
});
return link;
}
It'll give you a JLabel that acts like a proper link.
In action:
public static void main(String[] args)
{
JFrame frame = new JFrame("Linkify Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setLocationRelativeTo(null);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
container.add(new JLabel("Click "));
container.add(linkify("this", "http://facebook.com", "Facebook"));
container.add(new JLabel(" link to open Facebook."));
frame.setVisible(true);
}
If you'd like no tooltip just send a null.
Hope someone finds this useful! (If you do, be sure to let me know, I'd be happy to hear.)
Like said in docs, use
<meta property="og:url" content="http://www.your-domain.com/your-page.html" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Your Website Title" />
<meta property="og:description" content="Your description" />
<meta property="og:image" content="http://www.your-domain.com/path/image.jpg" />
image size recommended: 1 200 x 630
Easy with onclick-function and a javascript link:
<td onclick="location.href='yourpage.html'">go to yourpage</td>
From W3 Schools HTML DOM Changes: If you look at the 3rd example it shows how you can change the text in your link, "click here". Example:
<a id="a_tbnotesverbergen" href="#nothing">click here</a>
JS:
var element=document.getElementById("a_tbnotesverbergen");
element.innerHTML="New Text";
This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm
Sub hyper()
Dim cl As Range
Dim nS As String
Set MyRange = Sheets("Sheet1").Range("B16")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each cl In MyRange
nS = cl.Value
cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
Next
End Sub
It's a link that links to nowhere essentially (it just adds "#" onto the URL). It's used for a number of different reasons. For instance, if you're using some sort of JavaScript/jQuery and don't want the actual HTML to link anywhere.
It's also used for page anchors, which is used to redirect to a different part of the page.
(Just a little bit of topic), but maybe if you searched you could stumble here... In markdown (tested with parsedown and on iOS / android) you could do :
[Link](sms:phone_number,?&body=URL_encoded_body_text)
//[send sms](sms:1234567890;?&body=my%20very%20interesting%20text)
I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.
There's a HTML element called base
which allows you to:
Specify a default URL and a default target for all links on a page:
<base target="_blank" />
By specifying _blank
you make sure all links inside the iframe will be opened outside.
The usual way is to assign some JavaScript to the onClick
attribute of the TR
element.
If you can't use JavaScript, then you must use a trick:
Add the same link to each TD
of the same row (the link must be the outermost element in the cell).
Turn links into block elements: a { display: block; width: 100%; height: 100%; }
The latter will force the link to fill the whole cell so clicking anywhere will invoke the link.
Do you want to open a shared folder in Windows Explorer? You need to use a file:
link, but there are caveats:
file://server/share/folder/
).file://///server/share/folder
) and the user has disabled the security restriction on file:
links in a page served over HTTP. Thankfully IE also accepts the mangled link form.file:
link in a page served over HTTP.:hover
is a selector, and not a style. What you're doing in your example is adding inline styles to an element, and a selector equivalent for that obviously doesn't make much sense.
You can add a class to your link: hlRow.CssClass = 'abc';
And define your class as such:
a.abc:hover {
...
}
Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page:
$('a').click(function() {
// do stuff
return false;
});
I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID
attribute. To support older browsers, you'll need to change:
<div id="timeline" name="timeline" ...>
To the old format:
<a name="timeline" />
You'll then be able to navigate to /academics/page.html#timeline
and jump right to that section.
Also, check out this similar question.
Use the attr
method on your lookup. You can switch out any attribute with a new value.
$("a.mylink").attr("href", "http://cupcream.com");
I had similar issue. try this $('#myAnchor').get(0).click();
this works for me
most simple answer
<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>
it will work
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
Here is a practical example of Anchor tag with different
I liked Arthur's idea of a reusable handler, but I think there's a simpler way to do it:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (sender.GetType() != typeof (Hyperlink))
return;
string link = ((Hyperlink) sender).NavigateUri.ToString();
Process.Start(link);
}
Obviously there could be security risks with starting any kind of process, so be carefull.
I found a solution to my problem. You could go to this site:
https://developers.facebook.com/tools/debug
...then put in the URL of the page you want to share, and click "debug". It will automatically extract all the info on your meta tags and also clear the cache.
I shocked Excel didn't do this automatically so here is my solution I hope would be useful for others,
data:text/html,<button onclick="document.write(document.body.querySelector('textarea').value.split('\n').map(x => '<a href=\'' + x + '\'>' + x + '</a>').join('<br>'))">Linkify</button><br><textarea></textarea>
Instead step two, you can use the below page, first, click on "Run code snippet" then paste the column on it
<button onclick="document.write(document.body.querySelector('textarea').value.split('\n').map(x => '<a href=\'' + x + '\'>' + x + '</a>').join('<br>'))">Linkify</button><br><textarea></textarea>
_x000D_
I use Router and < Button/>. No < Link/>
<Button onClick={()=> {this.props.history.replace('/mypage')}}>
HERE
</Button>
There is a middle way. If you want a HTML control but you need to access it server side you can simply add the runat="server"
attribute:
<a runat="server" Id="lnkBack">Back</a>
You can then alter the href
server side using Attributes
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lnkBack.Attributes.Add("href", url);
}
}
resulting in:
<a id="ctl00_ctl00_mainContentPlaceHolder_contentPlaceHolder_lnkBack"
href="url.aspx">Back</a>
This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:
var i_will_target_self = document.querySelectorAll("ul.menu li a#example")
this example uses css to target links in a menu with id = "example"
that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):
for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}
That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."
read more here: http://xahlee.info/js/js_get_elements.html
I think you want to put a
, in front of a:link
(a
, a:link
) in your CSS file. The only way I could get rid of that awful default blue link color. I'm not sure if this was necessary for earlier version of the browsers we have, because it's supposed to work without a
I did something like that:
HTML:
<p class='parent'>text text text</p>
<img class='child' src='idk.png'>
CSS:
.child {
visibility: hidden;
}
.parent:hover .child {
visibility: visible;
}
You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the
tag (that you are looking for). The corresponding example from the documentation is as follows
For example, here is a comment that refers to the getComponentAt(int, int) method:
Use the {@link #getComponentAt(int, int) getComponentAt} method.
The package.class
part can be ommited if the referred method is in the current class.
Other useful links about JavaDoc are:
http://maps.google.com/maps?q=<?php echo urlencode($address); ?>
the encode ur conver and adds all the extra elements like for spaces and all. so u can easily fetch plane text code from db and use it without worring about the special characters to be added
The answer given works but disables outgoing links. Below a version with an added bonus ease out (swing) and respects outgoing links.
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
Dynamically create a hyperlink with raw JavaScript:
var anchorElem = document.createElement('a');
anchorElem.setAttribute("href", yourLink);
anchorElem.innerHTML = yourLinkText;
document.body.appendChild(anchorElem); // append your new link to the body
This seems to work (for now):
https://mail.google.com/mail/?view=cm&fs=1&[email protected]&su=SUBJECT&body=BODY&[email protected]
Use following code to show menu instead go to href addres
function show_more_menu(e) {_x000D_
if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
As of HTML5, buttons support the formaction
attribute. Best of all, no Javascript or trickery is needed.
<form>_x000D_
<button formaction="http://stackoverflow.com">Go to Stack Overflow!</button>_x000D_
</form>
_x000D_
Caveats
<form>
tags.<button>
type must be "submit" (or unspecified), I couldn't get it working with type "button." Which brings up point below.Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction Browser Support: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Browser_compatibility
Unfortunately, no. This feature is not available for facebook albums.
Inline Javascript:
<button onclick="window.location='http://www.example.com';">Visit Page Now</button>
Defining a function in Javascript:
<script>
function visitPage(){
window.location='http://www.example.com';
}
</script>
<button onclick="visitPage();">Visit Page Now</button>
or in Jquery
<button id="some_id">Visit Page Now</button>
$('#some_id').click(function() {
window.location='http://www.example.com';
});
My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!
import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
curpos = test.find("href")
if curpos >= 0:
testlen = len(test)
test = test[curpos:testlen]
curpos = test.find('"')
testlen = len(test)
test = test[curpos+1:testlen]
curpos = test.find('"')
needle = test[0:curpos]
if needle.startswith("http" or "www"):
needlestack.append(needle)
else:
sane = 1
for item in needlestack:
print item
I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )
You can achieve this using simple css as shown in below example
button {_x000D_
overflow: visible;_x000D_
width: auto;_x000D_
}_x000D_
button.link {_x000D_
font-family: "Verdana" sans-serif;_x000D_
font-size: 1em;_x000D_
text-align: left;_x000D_
color: blue;_x000D_
background: none;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: none;_x000D_
cursor: pointer;_x000D_
_x000D_
-moz-user-select: text;_x000D_
_x000D_
/* override all your button styles here if there are any others */_x000D_
}_x000D_
button.link span {_x000D_
text-decoration: underline;_x000D_
}_x000D_
button.link:hover span,_x000D_
button.link:focus span {_x000D_
color: black;_x000D_
}
_x000D_
<button type="submit" class="link"><span>Button as Link</span></button>
_x000D_
Not sure if you still need this, but in http://www.appbrain.com/ , you look up the app and the package name is in the url. For example: http://www.appbrain.com/app/fruit-ninja/com.halfbrick.fruitninja is the link for fruit ninja. Notice the bold
Just Try in button.
<button onclick="location.reload();location.href='url_name'"
id="myButton" class="btn request-callback" >Explore More</button>
Using href
<a href="#" class="know_how" onclick="location.reload();location.href='url_name'">Know More</a>
Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;"
.
Set the 'target' attribute of the link to _blank
:
<a href="#" target="_blank" rel="noopener noreferrer">Link</a>
Edit: for other examples, see here: http://www.w3schools.com/tags/att_a_target.asp
(Note: I previously suggested blank
instead of _blank
because, if used, it'll open a new tab and then use the same tab if the link is clicked again. However, this is only because, as GolezTrol pointed out, it refers to the name a of a frame/window, which would be set and used when the link is pressed again to open it in the same tab).
Security Consideration!
The rel="noopener noreferrer"
is to prevent the newly opened tab from being able to modify the original tab maliciously.
For more information about this vulnerability see these resources:
There is the only better way is AJAX as everyone is suggest in their posts. The alternative is using IFrames like below:
<iframe name="f1" id="f1"> </iframe>
<a href='yourpage.php' target='f1'>Click </a>
Now you will get the output in IFrame (you can place IFrame wherever you need in the page or event hide it and the result from the script).
Hope for non Ajax solution this is better.
Completely idempotent url that preserves path, parameters, and anchor.
<a href="javascript:"> click me </a>
it only uses a little tiny bit of JS.
EDIT: this does not reload the page. It is a link that does nothing.
This is my working implementation
private void showMessage()
{
lblMessage.setText("");
List<String> messages = db.getAllGCMMessages();
for (int k = messages.size() - 1; k >= 0; --k)
{
String message = messages.get(k).toString();
lblMessage.append(message + "\n\n");
}
Linkify.addLinks(lblMessage, Linkify.ALL);
}
and to change color of hyperlinks , i editted my xml for textview -
android:textColorLink="#69463d"
Wrap your div with
<a name="sushi">
<div id="sushi">
</div>
</a>
and link to it by
<a href="#sushi">Sushi</a>
It is OK, but at the same time can cause some browsers to become slow.
http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/
My advice is use <a href="#"></a>
If you're using JQuery remember to also use:
.click(function(event){
event.preventDefault();
// Click code here...
});
Try this
To Remove Hand Cursor
a.link {
cursor: default;
}
With Markdown-2.5.2, you can use this:
[link](url){:target="_blank"}
Simple:
if(pll_current_language() == 'en'){
//do your work here
}
Just write <a href="#"></a>
.
If that's what you want, you don't need a server-side control.
Paste following link to directly under link button click event, otherwise use javascript to call code behind function
Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Diagnostics.Process.Start(FilePath)
End Sub
I found this really useful but I needed to do it in quite a few places so I've wrapped my approach up in a simple extension to NSMutableAttributedString
:
Swift 3
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(.link, value: linkURL, range: foundRange)
return true
}
return false
}
}
Swift 2
import Foundation
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.rangeOfString(textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
return true
}
return false
}
}
Example usage:
let attributedString = NSMutableAttributedString(string:"I love stackoverflow!")
let linkWasSet = attributedString.setAsLink("stackoverflow", linkURL: "http://stackoverflow.com")
if linkWasSet {
// adjust more attributedString properties
}
Objective-C
I've just hit a requirement to do the same in a pure Objective-C project, so here's the Objective-C category.
@interface NSMutableAttributedString (SetAsLinkSupport)
- (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL;
@end
@implementation NSMutableAttributedString (SetAsLinkSupport)
- (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL {
NSRange foundRange = [self.mutableString rangeOfString:textToFind];
if (foundRange.location != NSNotFound) {
[self addAttribute:NSLinkAttributeName value:linkURL range:foundRange];
return YES;
}
return NO;
}
@end
Example usage:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:"I love stackoverflow!"];
BOOL linkWasSet = [attributedString setAsLink:@"stackoverflow" linkURL:@"http://stackoverflow.com"];
if (linkWasSet) {
// adjust more attributedString properties
}
Make Sure that the NSTextField's Behavior attribute is set as Selectable.
Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
And another way:
<a href="javascript:history.back()">Go Back</a>
_x000D_
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
Try this link format: https://t.me/[YourUserName]
I was looking for such a thing, BUT with text in (like the one that WhatsApp got)
In addition to romkyns's great answer.. here is some relevant documentation/examples.
DOM Elements have a native .click()
method.
The
HTMLElement.click()
method simulates a mouse click on an element.When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an
<a>
element to initiate navigation as if a real mouse-click had been received. (mdn reference)
Relevant W3 documentation.
A few examples..
You can access a specific DOM element from a jQuery object: (example)
$('a')[0].click();
You can use the .get()
method to retrieve a DOM element from a jQuery object: (example)
$('a').get(0).click();
As expected, you can select the DOM element and call the .click()
method. (example)
document.querySelector('a').click();
It's worth pointing out that jQuery is not required to trigger a native .click()
event.
this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>
It worked for me. No problems on using javascript:history.go(-1)
on Google Chrome.
javascript:history.go(-1)
on the enter URL space.<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>
this did the work for me
This is how change the cursor from an arrow to a hand when you hover over a given object
(myObject).
myObject.style.cursor = 'pointer';
Alternative (Insert tooltip to user):
<style>
a.tooltips {
position: relative;
display: inline;
}
a.tooltips span {
position: absolute;
width: 240px;
color: #FFFFFF;
background: #000000;
height: 30px;
line-height: 30px;
text-align: center;
visibility: hidden;
border-radius: 6px;
}
a.tooltips span:after {
content: '';
position: absolute;
top: 100%;
left: 50%;
margin-left: -8px;
width: 0;
height: 0;
border-top: 8px solid #000000;
border-right: 8px solid transparent;
border-left: 8px solid transparent;
}
a:hover.tooltips span {
visibility: visible;
opacity: 0.8;
bottom: 30px;
left: 50%;
margin-left: -76px;
z-index: 999;
}
</style>
<a class="tooltips" href="#">\\server\share\docs<span>Copy link and open in Explorer</span></a>
To hide Page url .
use media="print"
in style tage example :
<style type="text/css" media="print">
@page {
size: auto; /* auto is the initial value */
margin: 0; /* this affects the margin in the printer settings */
}
@page { size: portrait; }
</style>
If you want to remove links :
@media print {
a[href]:after {
visibility: hidden !important;
}
}
If you only want to change the current page address, you can do that by simply doing this in Javascript :
location.href = "http://www.example.com/test";
The Gist I found and works for me:
const DummyLink = ({onClick, children, props}) => (
<a href="#" onClick={evt => {
evt.preventDefault();
onClick && onClick();
}} {...props}>
{children}
</a>
);
Credit for srph https://gist.github.com/srph/020b5c02dd489f30bfc59138b7c39b53
Try
window.location = url;
Also use
window.open(url);
if you want to open in a new window.
Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.
public static boolean openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
public static boolean openWebpage(URL url) {
try {
return openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
return false;
}
You should add the target="_blank"
and rel="noopener noreferrer"
in the anchor tag.
For example:
<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>
Adding rel="noopener noreferrer"
is not mandatory, but it's a recommended security measure. More information can be found in the links below.
Source:
You can build a small UI that does the job like this :
function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
var app = UiApp.createApplication().setHeight(50).setWidth(200);
app.setTitle("Show URL");
var link = app.createAnchor('open ', href).setId("link");
app.add(link);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
If you want to 'show' the URL, just change this line like this :
var link = app.createAnchor(href, href).setId("link");
EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).
EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!
EDIT : below is an implementation using html service.
function testNew(){
showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}
function showAnchor(name,url) {
var html = '<html><body><a href="'+url+'" target="blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
Simple:
Use <section>
.
and use <a href="page.html#tips">Visit the Useful Tips Section</a>
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)
Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.
Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080
What you get as a result is the standalone 1080p video but not in the Tube environment.
You shouldn’t use <h1><a name="foo"/>Foo Title</h1>
in any flavor of HTML served as text/html
, because the XML empty element syntax isn’t supported in text/html
. However, <h1><a name="foo">Foo Title</a></h1>
is OK in HTML4. It is not valid in HTML5 as currently drafted.
<h1 id="foo">Foo Title</h1>
is OK in both HTML4 and HTML5. This won’t work in Netscape 4, but you’ll probably use a dozen other features that don’t work in Netscape 4.
Just try like this:
HTML in PHP :
$link_address1 = 'index.php';
echo "<a href='".$link_address1."'>Index Page</a>";
$link_address2 = 'page2.php';
echo "<a href='".$link_address2."'>Page 2</a>";
Easiest way
$link_address1 = 'index.php';
echo "<a href='$link_address1'>Index Page</a>";
$link_address2 = 'page2.php';
echo "<a href='$link_address2'>Page 2</a>";
[What you need for interviews] A Node class is the sufficient data structure to represent a binary tree.
(While other answers are mostly correct, they are not required for a binary tree: no need to extend object class, no need to be a BST, no need to import deque).
class Node:
def __init__(self, value = None):
self.left = None
self.right = None
self.value = value
Here is an example of a tree:
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
In this example n1 is the root of the tree having n2, n3 as its children.
Sounds a bit familiar with my problem: aapt not found under the right path
I needed to clean all open projects to get it working again...
in build.gradle , the version of bellow line should be same
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0'
Steps to perform the task:
First, download and install the compiler.
Then, type the C/C++ program and save it.
Then, open the command line and change directory to the particular one where the source file is stored, using cd
like so:
cd C:\Documents and Settings\...
Then, to compile, type in the command prompt:
gcc sourcefile_name.c -o outputfile.exe
Finally, to run the code, type:
outputfile.exe
In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:
my_list = [1,2,4,6,7]
del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list
In your case the appropriate method to use is pop, because it takes the index to be removed:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.
For those using nginx with unicorn and rails, most likely the timeout is in your unicorn.rb
file
put a large timeout in unicorn.rb
timeout 500
if you're still facing issues, try having fail_timeout=0 in your upstream in nginx and see if this fixes your issue. This is for debugging purposes and might be dangerous in a production environment.
upstream foo_server {
server 127.0.0.1:3000 fail_timeout=0;
}
Install Nuget for Oracle.ManagedDataAccess
Make sure you are using header for Oracle:
using Oracle.ManagedDataAccess.Client;
This Worked for me.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
Yes, you can.
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
YMMV.
It works because only Safari Mobile implements -webkit-touch-callout
: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout
Please note that @supports
does not work in IE. IE will skip both of the above @support
blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not
because of this.
What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.
Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling
but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".
Such behavior is described in Migrating from PHP 7.0.x to PHP 7.1.x/
The empty index operator is not supported for strings anymore Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.
In my case it was a mere initialization. I fixed it by replacing $foo=''
with $foo=[]
.
$foo='';
$foo[]='test';
print_r($foo);
Its working for me...
from selenium import webdriver
PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://%s' % PROXY)
chrome = webdriver.Chrome(chrome_options=chrome_options)
chrome.get("http://whatismyipaddress.com")
$array = 1..5 | foreach { $false }
Combination from itertools
import itertools
col_names = ["aa","bb", "cc", "dd"]
all_combinations = itertools.chain(*[itertools.combinations(col_names,i+1) for i,_ in enumerate(col_names)])
print(list(all_combinations))
I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file
tr:nth-of-type(odd)
{
background-color: red;
}
tr:nth-of-type(even)
{
background-color: blue;
}
The bootstrap table-striped class will over ride your selectors.
In my case, it took some digging, but found it.
My Context
I'm looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.
During a website attack, I noticed that some xmls weren't parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character.
exception.
NON-RESOLUTION: I converted the document to a byte[]
and sanitized it of 0x00, but it found none.
When I scanned the xml document, I found the following:
...
<form>
...
<item name="SomeField">
<value
string="C:\boot.ini�.htm" />
</item>
...
There was the nul byte encoded as an html entity �
!!!
RESOLUTION: To fix the encoding, I replaced the �
value before loading it into my XmlDocument
, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here's my entire process:
XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("�", "[0x00]"); // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);
string formattedXml = null;
// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars = "\t",
NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
xml.Save(writer);
formattedXml = sb.ToString();
}
LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.
Google’s Gradle Plugin recommended way for configuring your gradle files to build multiple projects has some shortcomings If you have multiple projects depending upon one library project, this post briefly explain Google’s recommended configuration, its shortcomings, and recommend a different way to configure your gradle files to support multi-project setups in Android Studio:
An alternative multiproject setup for android studio
A Different Way :
It turns out there’s a better way to manage multiple projects in Android Studio. The trick is to create separate Android Studio projects for your libraries and to tell gradle that the module for the library that your app depends on is located in the library’s project directory. If you wanted to use this method with the project structure I’ve described above, you would do the following:
The 4th step is the hard part, so that’s the only step that I’ll describe in detail. You can reference modules that are external to your project’s directory by adding a project statement in your settings.gradle file and by setting the projectDir property on the ProjectDescriptor object that’s returned by that project statement:
The code one has to put in settings.gradle
:
include ':library1'
project(':library1').projectDir = new File('../StickyListHeader/library1')
If you’ve done this correctly, you’ll notice that the modules referenced by your project will show up in the project navigator, even if those modules are external to the project directory:
This allows you to work on library code and app code simultaneously. Version control integration also works just fine when you reference modules externally this way. You can commit and push your modifications to the library code just like you can commit and push modifications to your app code.
This way of setting up multiple projects avoids the difficulties that plague Google’s recommended configuration. Because we are referencing a module that is outside of the project directory we don’t have to make extra copies of the library module for every app that depends on it and we can version our libraries without any sort of git submodule nonsense.
Unfortunately, this other way of setting up multiple projects is very difficult to find. Obviously, its not something you’ll figure out from looking at Google’s guide, and at this point, there’s no way to configure your projects in this way by using the UI of Android Studio.
In the new version of Go 1.16 we can use package embed to read the file contents as shown below.
package main
import _"embed"
func main() {
//go:embed "hello.txt"
var s string
print(s)
//go:embed "hello.txt"
var b []byte
print(string(b))
//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))
}
For more details go through https://tip.golang.org/pkg/embed/ And https://golangtutorial.dev/tips/embed-files-in-go/
Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.
Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?
Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:
this is line 1
this is line 2
the result would be 'this is line 1this is line 2'
... is that what you really want?
A greater solution would include:
onlyascii
recognition that a filter function merely needs to return a truthy value if the argument is to be retained:
def filter_func(char):
return char == '\n' or 32 <= ord(char) <= 126
# and later:
filtered_data = filter(filter_func, data).lower()
I have same problem. I solved install this setup. (I use vs 2015 (4.6))
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.
Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.
Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
There are CSS options for the audio tag.
Like: html 5 audio tag width
But if you play around with it you'll see results can be unexpected - as of August 2012.
I have some hacky answers that are likely to be terrible... but I have very little experience at this point.
a way:
class myClass():
myInstances = []
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
self.__class__.myInstances.append(self)
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
for thisObj in myClass.myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
A hack way to get this done:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
thisStep += 1
if "myClass object at" in thisLocalsLine:
print(thisLocalsLine)
print(myLocals[(thisStep - 2)])
#myInstances.append(myLocals[(thisStep - 2)])
print(myInstances)
myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
Another more 'clever' hack:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myInstances = []
myClasses = {
"myObj01": ["Foo", "Bar"],
"myObj02": ["FooBar", "Baz"]
}
for thisClass in myClasses.keys():
exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
myInstances.append(getattr(sys.modules[__name__], thisClass))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
Just type
gcc --version
in any terminal near you.. ;-)
If this is in SQL Server, your syntax is correct; however, you need to reference the COUNT(*) as the Total Count from your nested query. This should give you what you need:
SELECT CASE WHEN TotalCount >0 THEN 'TRUE' ELSE 'FALSE' END FROM
(
SELECT [Some Column], COUNT(*) TotalCount
FROM INCIDENTS
WHERE [Some Column] = 'Target Data'
GROUP BY [Some Column]
) DerivedTable
Using this, you could assign TotalCount to a variable and then use an IF ELSE statement to execute your INSERT statements:
DECLARE @TotalCount int
SELECT @TotalCount = TotalCount FROM
(
SELECT [Some Column], COUNT(*) TotalCount
FROM INCIDENTS
WHERE [Some Column] = 'Target Data'
GROUP BY [Some Column]
) DerivedTable
IF @TotalCount > 0
-- INSERT STATEMENT 1 GOES HERE
ELSE
-- INSERT STATEMENT 2 GOES HERE
Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.
Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End Sub
I simplification for Science_Fiction's answer I think is to use the exclusive or function so you can just have:
if(checkbox1.checked ^ checkbox2.checked)
{
//do stuff
}
That is assuming you want to do the same thing for both situations.
I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.
import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii")))
For array to string
Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.
For string to array
First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.
Use KeyboardView
:
KeyboardView kbd = new KeyboardView(context);
kbd.setKeyboard(new Keyboard(this, R.xml.custom));
kbd.setOnKeyboardActionListener(new OnKeyboardActionListener() {
....
}
now you have kbd
which is a normal view.
The nice thing about this is that R.xml.custom
refers to /res/xml/custom.xml
, which defines in xml the layout of the keyboard. For more information on this file, look here: Keyboard, Keyboard.Row, Keyboard.Key.
Please make your life easier (don't use join into group):
var query = from ug in UserGroups
from ugp in UserGroupPrices.Where(x => x.UserGroupId == ug.Id).DefaultIfEmpty()
select new
{
UserGroupID = ug.UserGroupID,
UserGroupName = ug.UserGroupName,
Price = ugp != null ? ugp.Price : 0 //this is to handle nulls as even when Price is non-nullable prop it may come as null from SQL (result of Left Outer Join)
};
Simply you can use the following SQL Script to delete the index in MySQL:
alter table fuinfo drop index email;
$ git branch -D <branch-name>
[NOTE]:
-D
is a shortcut for --delete --force
.
Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')
In fact as long as the Axes3D import is present the line
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')
as used by the OP also works. (checked with matplotlib version 1.3.1)
In ST2 there's a package you can install called Default FileType which does just that.
More info here.
There is no installation required. Just add jQuery to your application folder and give a reference to the js file.
<script type="text/javascript" src="jQuery.js"></script>
if jQuery is in the same folder of your referenced file.
If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.
SELECT *
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40))
FROM DATABASE')
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:
External
option in Unity ? Preferences ? Packages ? Repository
Hidden Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
File
menuNote that the only folders you need to keep under source control are Assets
and ProjectSettigns
.
More information about keeping Unity Project under source control you can find in this post.
This actually works:
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.custom_actionbar);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity = Gravity.CENTER;
You have to define custom_actionbar.xml layout which is as per your requirement e.g. :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#2e2e2e"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/top_banner"
android:layout_gravity="center"
/>
</LinearLayout>
I found this simple method to work the best. It does not rewrite history and all previous check-ins of branch will be appended to the master. Nothing is lost, and you can clearly see what transpired in the commit log.
Objective: Make current state of "branch" the "master"
Working on a branch, commit and push your changes to make sure your local and remote repositories are up to date:
git checkout master # Set local repository to master
git reset --hard branch # Force working tree and index to branch
git push origin master # Update remote repository
After this, your master will be the exact state of your last commit of branch and your master commit log will show all check-ins of the branch.
public
means you can access the class from anywhere in the class/object or outside of the package or classstatic
means constant in which block of statement used only 1 timevoid
means no return typeA lot of these solutions work. However, if all you want is to be able to set the margin between items the simplest method I have come up with is to wrap your item - in your case the CheckedTextView - in a LinearLayout and put your margin formatting for the item in that, not the root-layout. Be sure to give this wrapping layout an id and create it along with your CheckedTextView in your adapter.
That's it. In effect, you are instantiating the margin at the item level for the ListView. Because the ListView does not know about any item layout - only your adapter does. This basically inflates the part of the item layout that was being ignored before.
df=df.filter(df["columnname"]>='2020-01-13')
Sure. Just put composer.phar somewhere like C:\php\composer.phar
, then make a batch file somewhere within the PATH called composer.bat
which does the following:
@ECHO OFF
php "%~dp0composer.phar" %*
The "%*" repeats all of the arguments passed to the shell script.
Then you can run around doing composer update
all ya want!
Answering the question in your title, you can query sys.tables
or sys.objects
where type = 'U'
to check for the existence of a table. You can also use OBJECT_ID('table_name', 'U'). If it returns a non-null value then the table exists:
IF (OBJECT_ID('dbo.My_Table', 'U') IS NULL)
BEGIN
CREATE TABLE dbo.My_Table (...)
END
You can do the same for databases with DB_ID():
IF (DB_ID('My_Database') IS NULL)
BEGIN
CREATE DATABASE My_Database
END
If you want to create the database and then start using it, that needs to be done in separate batches. I don't know the specifics of your case, but there shouldn't be many cases where this isn't possible. In a SQL script you can use GO
statements. In an application it's easy enough to send across a new command after the database is created.
The only place that you might have an issue is if you were trying to do this in a stored procedure and creating databases on the fly like that is usually a bad idea.
If you really need to do this in one batch, you can get around the issue by using EXEC to get around the parsing error of the database not existing:
CREATE DATABASE Test_DB2
IF (OBJECT_ID('Test_DB2.dbo.My_Table', 'U') IS NULL)
BEGIN
EXEC('CREATE TABLE Test_DB2.dbo.My_Table (my_id INT)')
END
EDIT: As others have suggested, the INFORMATION_SCHEMA.TABLES
system view is probably preferable since it is supposedly a standard going forward and possibly between RDBMSs.
In Swift 4.2 the notification names have moved to a different namespace. So now it's
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyboardListeners()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
func addKeyboardListeners() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc private extension WhateverTheClassNameIs {
func keyboardWillShow(_ notification: Notification) {
// Do something here.
}
func keyboardWillHide(_ notification: Notification) {
// Do something here.
}
}
Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.
You can create a new alias in Terminal:
nano ~/.bash_profile
Copy this line and paste it into the editor:
alias subl='open -a "Sublime Text"'
Hit control + x, then y, then enter to save and close it.
Close all Terminal windows and open it up again.
That's it, you can now use subl filename
or subl .
Instagram developer console has provided the solution for it. https://www.instagram.com/developer/endpoints/
To use this in PHP, here is the code snippet,
/**
**
** Add this code snippet after your first curl call
** assume the response of the first call is stored in $userdata
** $access_token have your access token
*/
$maximumNumberOfPost = 33; // it can be 20, depends on your instagram application
$no_of_images = 50 // Enter the number of images you want
if ($no_of_images > $maximumNumberOfPost) {
$ImageArray = [];
$next_url = $userdata->pagination->next_url;
while ($no_of_images > $maximumNumberOfPost) {
$originalNumbersOfImage = $no_of_images;
$no_of_images = $no_of_images - $maximumNumberOfPost;
$next_url = str_replace("count=" . $originalNumbersOfImage, "count=" . $no_of_images, $next_url);
$chRepeat = curl_init();
curl_setopt_array($chRepeat, [
CURLOPT_URL => $next_url,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $access_token"
],
CURLOPT_RETURNTRANSFER => true
]);
$userRepeatdata = curl_exec($chRepeat);
curl_close($chRepeat);
if ($userRepeatdata) {
$userRepeatdata = json_decode($userRepeatdata);
$next_url = $userRepeatdata->pagination->next_url;
if (isset($userRepeatdata->data) && $userRepeatdata->data) {
$ImageArray = $userRepeatdata->data;
}
}
}
}
My Net 5 solution that also handles null characters at the end:
hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );
static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
int realLength = 0;
for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
{
byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
if ( b != 0 ) //not NULL character
{
realLength = i + 2;
break;
}
}
var bytes = new byte[realLength / 2];
for ( var i = 0; i < bytes.Length; i++ )
{
bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
}
return encoding.GetString( bytes );
}
Your printf
needs a format string:
printf("%d\n", x);
This reference page gives details on how to use printf
and related functions.
I realise that there are many answers, but I found a solution that may be helpful to some. I ran into the same problem, I am running oracle sql develop on my local computer and I have a bunch of users. I happen to remember the password for one of my users and I used it to reset the password of other users.
Steps:
connect to a database using a valid user and password, in my case all my users expired except "system" and I remember that password
find the "Other_users" node within the tree as the image below displays
3.within the "Other_users" tree find your users that you would like to reset password of and right click the note and select "Edit Users"
4.fill out the new password in edit user dialog and click "Apply". Make sure that you have unchecked "Password expired (user must change next login)".
And that worked for me, It is not as good as other solution because you need to be able to login to at least one account but it does work.
You can also drop the column and its constraint(s) in a single statement rather than individually.
CREATE TABLE #T
(
Col1 INT CONSTRAINT UQ UNIQUE CONSTRAINT CK CHECK (Col1 > 5),
Col2 INT
)
ALTER TABLE #T DROP CONSTRAINT UQ ,
CONSTRAINT CK,
COLUMN Col1
DROP TABLE #T
(but not other possible column dependencies such as foreign keys, unique and primary key constraints, computed columns, indexes)
CREATE TABLE [dbo].[TestTable]
(
A INT DEFAULT '1' CHECK (A=1),
B INT,
CHECK (A > B)
)
GO
DECLARE @TwoPartTableNameQuoted nvarchar(500) = '[dbo].[TestTable]',
@ColumnNameUnQuoted sysname = 'A',
@DynSQL NVARCHAR(MAX);
SELECT @DynSQL =
'ALTER TABLE ' + @TwoPartTableNameQuoted + ' DROP' +
ISNULL(' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(c.default_object_id)) + ',','') +
ISNULL(check_constraints,'') +
' COLUMN ' + QUOTENAME(@ColumnNameUnQuoted)
FROM sys.columns c
CROSS APPLY (SELECT ' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(referencing_id)) + ','
FROM sys.sql_expression_dependencies
WHERE referenced_id = c.object_id
AND referenced_minor_id = c.column_id
AND OBJECTPROPERTYEX(referencing_id, 'BaseType') = 'C'
FOR XML PATH('')) ck(check_constraints)
WHERE c.object_id = object_id(@TwoPartTableNameQuoted)
AND c.name = @ColumnNameUnQuoted;
PRINT @DynSQL;
EXEC (@DynSQL);
In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.
Question: How can I open the href in the new window or tab with jQuery?
var url = $(this).attr('href').attr('target','_blank');
On Windows 10 Anniversary Update, it's even easier to run shell commands in/with bash on ubuntu on windows
I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on
ssh [email protected] < /mnt/c/ccode-eu.sh
I've got the same problem, and what worked for me is in THIS OTHER ANSWER.
I didn't replicated it here because it is NOT A CORRECT THING TO DO.
Basically is a re-install being sure to delete everything very well and using 32 bit versions.
For simplicity and well structured sake, use SpringMVC. It's just so simple.
@RequestMapping("/carlist.json")
public @ResponseBody List<String> getCarList() {
return carService.getAllCars();
}
Reference and credit: https://github.com/xvitcoder/spring-mvc-angularjs
Specifying android:onClick
attribute results in Button
instance calling setOnClickListener
internally. Hence there is absolutely no difference.
To have clear understanding, let us see how XML onClick
attribute is handled by the framework.
When a layout file is inflated, all Views specified in it are instantiated. In this specific case, the Button
instance is created using public Button (Context context, AttributeSet attrs, int defStyle)
constructor. All of the attributes in the XML tag are read from the resource bundle and passed as AttributeSet
to the constructor.
Button
class is inherited from View
class which results in View
constructor being called, which takes care of setting the click call back handler via setOnClickListener
.
The onClick attribute defined in attrs.xml, is referred in View.java as R.styleable.View_onClick
.
Here is the code of View.java
that does most of the work for you by calling setOnClickListener
by itself.
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
As you can see, setOnClickListener
is called to register the callback, as we do in our code. Only difference is it uses Java Reflection
to invoke the callback method defined in our Activity.
Here are the reason for issues mentioned in other answers:
Java Class getMethod
is used, only functions with public access specifier are searched for. Otherwise be ready to handle IllegalAccessException
exception.getContext().getClass().getMethod()
call restricts the method search to the current context, which is Activity in case of Fragment. Hence method is searched within Activity class and not Fragment class.Java Class getMethod
searches for method which accepts View.class
as parameter.I have written code that sniffs IE4 or greater and is currently functioning perfectly in sites for my company's clients, as well as my own personal sites.
Include the following enumerated constant and function variables into a javascript include file on your page...
//methods
var BrowserTypes = {
Unknown: 0,
FireFox: 1,
Chrome: 2,
Safari: 3,
IE: 4,
IE7: 5,
IE8: 6,
IE9: 7,
IE10: 8,
IE11: 8,
IE12: 8
};
var Browser = function () {
try {
//declares
var type;
var version;
var sVersion;
//process
switch (navigator.appName.toLowerCase()) {
case "microsoft internet explorer":
type = BrowserTypes.IE;
sVersion = navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE') + 5, navigator.appVersion.length);
version = parseFloat(sVersion.split(";")[0]);
switch (parseInt(version)) {
case 7:
type = BrowserTypes.IE7;
break;
case 8:
type = BrowserTypes.IE8;
break;
case 9:
type = BrowserTypes.IE9;
break;
case 10:
type = BrowserTypes.IE10;
break;
case 11:
type = BrowserTypes.IE11;
break;
case 12:
type = BrowserTypes.IE12;
break;
}
break;
case "netscape":
if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) { type = BrowserTypes.Chrome; }
else { if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { type = BrowserTypes.FireFox } };
break;
default:
type = BrowserTypes.Unknown;
break;
}
//returns
return type;
} catch (ex) {
}
};
Then all you have to do is use any conditional functionality such as...
ie. value = (Browser() >= BrowserTypes.IE) ? node.text : node.textContent;
or WindowWidth = (((Browser() >= BrowserTypes.IE9) || (Browser() < BrowserTypes.IE)) ? window.innerWidth : document.documentElement.clientWidth);
or sJSON = (Browser() >= BrowserTypes.IE) ? xmlElement.text : xmlElement.textContent;
Get the idea? Hope this helps.
Oh, you might want to keep it in mind to QA the Browser() function after IE10 is released, just to verify they didn't change the rules.
Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);
Here's a LINQ solution which is virtually the same but more scalable:
new[] { "a", "b", "c" }.Any(c => s.Contains(c))
use flask 0.9 instead
use the following commands
sudo pip uninstall flask
sudo pip install flask==0.9
Just use Instant
of java.time
.
System.out.println(Instant.now());
This just printed:
2018-01-27T09:35:23.179612Z
Instant.toString
always gives UTC time.
The output is usually sortable, but there are unfortunate exceptions. toString
gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of Instant.now()
seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).
Instant
is one of the classes in java.time
, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date
class. java.time
is built into Java 8 and later and has also been backported to Java 6 and 7.
If it says:
The term 'gradlew' is not recognized
Then using following command
npm start -- --reset-cache
worked for me. cheers!
You have two options; either handle the exception or test the length:
if len(dlist) > 1:
newlist.append(dlist[1])
continue
or
try:
newlist.append(dlist[1])
except IndexError:
pass
continue
Use the first if there often is no second item, the second if there sometimes is no second item.
You can implement your work method as follows:
private static void Work(CancellationToken cancelToken)
{
while (true)
{
if(cancelToken.IsCancellationRequested)
{
return;
}
Console.Write("345");
}
}
That's it. You always need to handle cancellation by yourself - exit from method when it is appropriate time to exit (so that your work and data is in consistent state)
UPDATE: I prefer not writing while (!cancelToken.IsCancellationRequested)
because often there are few exit points where you can stop executing safely across loop body, and loop usually have some logical condition to exit (iterate over all items in collection etc.). So I believe it's better not to mix that conditions as they have different intention.
Cautionary note about avoiding CancellationToken.ThrowIfCancellationRequested()
:
Comment in question by Eamon Nerbonne:
... replacing
ThrowIfCancellationRequested
with a bunch of checks forIsCancellationRequested
exits gracefully, as this answer says. But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, but inRanToCompletion
. And that can affect not just explicit state checks, but also, more subtly, task chaining with e.g.ContinueWith
, depending on theTaskContinuationOptions
used. I'd say that avoidingThrowIfCancellationRequested
is dangerous advice.
we can change the icon of markers, i did it on right click event. Lets see if it works for you...
// Create a Marker
var marker = new google.maps.Marker({
position: location,
map: map,
title:'Sample Tool Tip'
});
// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
marker.setIcon('blank.png'); // set image path here...
});
I found a solution that adds columns at runtime, and binds to a DataTable
.
Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me. Any suggestions?
xaml
<DataGrid
Name="dataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding}">
</DataGrid>
xaml.cs using System.Windows.Data;
if (table != null) // table is a DataTable
{
foreach (DataColumn col in table.Columns)
{
dataGrid.Columns.Add(
new DataGridTextColumn
{
Header = col.ColumnName,
Binding = new Binding(string.Format("[{0}]", col.ColumnName))
});
}
dataGrid.DataContext = table;
}
Use Control.ControlCollection.Find.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
EDIT for asker:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
tbxs[0].Text = "Found!";
}
Try this example:
Tooltips must be initialized with jQuery
: select the specified element and call the tooltip()
method in JavaScript
:
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
Add CSS
:
.tool-tip {
display: inline-block;
}
.tool-tip [disabled] {
pointer-events: none;
}
And your html:
<span class="tool-tip" data-toggle="tooltip" data-placement="bottom" title="I am Tooltip">
<button disabled="disabled">I am disabled</button>
</span>
This simple problem can cause a real headache!
I can see your controller EDIT
(PUT
) method expects 2 parameters: a) an int id, and b) a department object.
It is the default code when you generate this from VS > add controller with read/write options. However, you have to remember to consume this service using the two parameters, otherwise you will get the error 405.
In my case, I did not need the id parameter for PUT
, so I just dropped it from the header... after a few hours of not noticing it there! If you keep it there, then the name must also be retained as id, unless you go on to make necessary changes to your configurations.
Here is my full solution to this based on the accepted answer.
Usage example:
include("./assets/php/db.php");
$data = array('field1' => 'data1', 'field2'=> 'data2');
insertArr("databaseName.tableName", $data);
<?PHP
/**
* Class to initiate a new MySQL connection based on $dbInfo settings found in dbSettings.php
*
* @example
* $db = new database(); // Initiate a new database connection
* mysql_close($db->get_link());
*/
class database{
protected $databaseLink;
function __construct(){
include "dbSettings.php";
$this->database = $dbInfo['host'];
$this->mysql_user = $dbInfo['user'];
$this->mysql_pass = $dbInfo['pass'];
$this->openConnection();
return $this->get_link();
}
function openConnection(){
$this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
}
function get_link(){
return $this->databaseLink;
}
}
/**
* Insert an associative array into a MySQL database
*
* @example
* $data = array('field1' => 'data1', 'field2'=> 'data2');
* insertArr("databaseName.tableName", $data);
*/
function insertArr($tableName, $insData){
$db = new database();
$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
foreach ($escaped_values as $idx=>$data) $escaped_values[$idx] = "'".$data."'";
$values = implode(", ", $escaped_values);
$query = "INSERT INTO $tableName ($columns) VALUES ($values)";
mysql_query($query) or die(mysql_error());
mysql_close($db->get_link());
}
?>
<?PHP
$dbInfo = array(
'host' => "localhost",
'user' => "root",
'pass' => "password"
);
?>
In addition to the anwser of Bill the Lizard:
Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST
in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded"
:
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")
Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA"
.
Very simple:
Use COUNT_BIG(*) AS NumStreams
private static T[] prepareArray<T>(T[] arrayToCopy, T value)
{
Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
arrayToCopy[arrayToCopy.Length - 1] = value;
return (T[])arrayToCopy;
}
I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
If you installed mongodb with homebrew, there's an easier way:
List mongo job with launchctl:
launchctl list | grep mongo
Stop mongo job:
launchctl stop <job label>
(For me this is launchctl stop homebrew.mxcl.mongodb
)
Start mongo job:
launchctl start <job label>
If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:
DataSource source,source2,source3,source4, ...;
source = new FileDataSource(myfile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile);
multipart.addBodyPart(messageBodyPart);
source2 = new FileDataSource(myfile2);
messageBodyPart.setDataHandler(new DataHandler(source2));
messageBodyPart.setFileName(myfile2);
multipart.addBodyPart(messageBodyPart);
source3 = new FileDataSource(myfile3);
messageBodyPart.setDataHandler(new DataHandler(source3));
messageBodyPart.setFileName(myfile3);
multipart.addBodyPart(messageBodyPart);
source4 = new FileDataSource(myfile4);
messageBodyPart.setDataHandler(new DataHandler(source4));
messageBodyPart.setFileName(myfile4);
multipart.addBodyPart(messageBodyPart);
...
message.setContent(multipart);
The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.
If you cannot detach the production db you should use backup and restore.
You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.
You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.
This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
This will work fine I think, though you might need to reset "top:200px;" according to your needs:
#main_content {
top: 160px;
left: 160px;
width: 800px;
min-height: 500px;
height: auto;
background-color: #2185C5;
position: relative;
border: 2px solid #CCCCCC;
}
#container {
width: 100px;
height: 20px;;
margin: 0 auto;
padding-top: 10px;
position: relative;
top: 200px;
border: 2px solid #CCCCCC;
}
if (in_array('strawberry', $array))
{
unset($array[array_search('strawberry',$array)]);
}
without disabling the selected value on submitting..
$('#selectID option:not(:selected)').prop('disabled', true);
If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);
It works for me..
I suppose this depends on your architecture and whatever else you may need to consider, but you could also take the object-oriented approach and use a class.
class ClassName {
private $site_url;
function __construct( $url ) {
$this->site_url = $url;
}
public function parts( string $part ) {
echo 'http://' . $this->site_url . 'content/' . $part . '.php';
}
# You could build a bunch of other things here
# too and still have access to $this->site_url.
}
Then you can create and use the object wherever you'd like.
$obj = new ClassName($site_url);
$obj->parts('part_argument');
This could be overkill for what OP was specifically trying to achieve, but it's at least an option I wanted to put on the table for newcomers since nobody mentioned it yet.
The advantage here is scalability and containment. For example, if you find yourself needing to pass the same variables as references to multiple functions for the sake of a common task, that could be an indicator that a class is in order.
Portable Document Format (PDF).
Any Browser « Use _Embeddable Google Document Viewer to embed the PDF file in iframe
.
<iframe src="http://docs.google.com/gview?
url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0">
</iframe>
Only for chrome browser « Chrome PDF viewer using plugin. pluginspage=http://www.adobe.com/products/acrobat/readstep2.html
.
<embed type="application/pdf"
src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf"
width="100%" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html"
background-color="0xFF525659" top-toolbar-height="56" full-frame="" internalinstanceid="21"
title="CHROME">
Example Sippet:
<html>_x000D_
<head></head>_x000D_
<body style=" height: 100%;">_x000D_
<div style=" position: relative;">_x000D_
<div style="width: 100%; /*overflow: auto;*/ position: relative;height: auto; margin-top: 70px;">_x000D_
<p>An _x000D_
<a href="https://en.wikipedia.org/wiki/Image_file_formats" >image</a> is an artifact that depicts visual perception_x000D_
</p>_x000D_
<!-- To make div with scroll data [max-height: 500;]-->_x000D_
<div style="/* overflow: scroll; */ max-height: 500; float: left; width: 49%; height: 100%; ">_x000D_
<img width="" height="400" src="https://peach.blender.org/wp-content/uploads/poster_bunny_bunnysize.jpg?x11217" title="Google" style="-webkit-user-select: none;background-position: 0px 0px, 10px 10px;background-size: 20px 20px;background-image:linear-gradient(45deg, #eee 25%, transparent 25%, transparent 75%, #eee 75%, #eee 100%),linear-gradient(45deg, #eee 25%, white 25%, white 75%, #eee 75%, #eee 100%);cursor: zoom-in;" />_x000D_
<p>Streaming an Image form Response Stream (binary data) « This buffers the output in smaller chunks of data rather than sending the entire image as a single block. _x000D_
<a href="http://www.chestysoft.com/imagefile/streaming.asp" >StreamToBrowser</a>_x000D_
</p>_x000D_
</div>_x000D_
<div style="float: left; width: 10%; background-color: red;"></div>_x000D_
<div style="float: left;width: 49%; ">_x000D_
<img width="" height="400" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot"/>_x000D_
<p>Streaming an Image form Base64 String « embedding images directly into your HTML._x000D_
<a href="https://en.wikipedia.org/wiki/Data_URI_scheme">_x000D_
<sup>Data URI scheme</sup>_x000D_
</a>_x000D_
<a href="https://codebeautify.org/image-to-base64-converter">_x000D_
<sup>, Convert Your Image to Base64</sup>_x000D_
</a>_x000D_
<pre>data:[<media type>][;base64],<data></pre>_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
<div style="width: 100%;overflow: auto;position: relative;height: auto; margin-top: 70px;">_x000D_
<video style="height: 500px;width: 100%;" name="media" controls="controls">_x000D_
<!-- autoplay -->_x000D_
<source src="http://download.blender.org/peach/trailer/trailer_400p.ogg" type="video/mp4">_x000D_
<source src="http://download.blender.org/peach/trailer/trailer_400p.ogg" type="video/ogg">_x000D_
</video>_x000D_
<p>Video courtesy of _x000D_
<a href="https://www.bigbuckbunny.org/" >Big Buck Bunny</a>._x000D_
</p>_x000D_
<div>_x000D_
<div style="width: 100%;overflow: auto;position: relative;height: auto; margin-top: 70px;">_x000D_
<p>Portable Document Format _x000D_
<a href="https://acrobat.adobe.com/us/en/acrobat/about-adobe-pdf.html?promoid=CW7625ZK&mv=other" >(PDF)</a>._x000D_
</p>_x000D_
<div style="float: left;width: 49%; overflow: auto;position: relative;height: auto;">_x000D_
<embed type="application/pdf" src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf" width="100%" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html" background-color="0xFF525659" top-toolbar-height="56" full-frame="" internalinstanceid="21" title="CHROME">_x000D_
<p>Chrome PDF viewer _x000D_
<a href="https://productforums.google.com/forum/#!topic/chrome/MP_1qzVgemo">_x000D_
<sup>extension</sup>_x000D_
</a>_x000D_
<a href="https://chrome.google.com/webstore/detail/surfingkeys/gfbliohnnapiefjpjlpjnehglfpaknnc">_x000D_
<sup> (surfingkeys)</sup>_x000D_
</a>_x000D_
</p>_x000D_
</div>_x000D_
<div style="float: left; width: 10%; background-color: red;"></div>_x000D_
<div style="float: left;width: 49%; ">_x000D_
<iframe src="https://docs.google.com/gview?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true#:page.7" style="" width="100%" height="500px" allowfullscreen="" webkitallowfullscreen=""></iframe>_x000D_
<p>Embeddable _x000D_
<a href="https://googlesystem.blogspot.in/2009/09/embeddable-google-document-viewer.html" >Google</a> Document Viewer. Here's the code I used to embed the PDF file: _x000D_
<pre>_x000D_
<iframe _x000D_
src="http://docs.google.com/gview?_x000D_
url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" _x000D_
style="width:600px; height:500px;" frameborder="0"></iframe>_x000D_
</pre>_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Running the risk of getting another Necromancer badge, I would like to add one very good use for uintptr_t (or even intptr_t) and that is writing testable embedded code. I write mostly embedded code targeted at various arm and currently tensilica processors. These have various native bus width and the tensilica is actually a Harvard architecture with separate code and data buses that can be different widths. I use a test driven development style for much of my code which means I do unit tests for all the code units I write. Unit testing on actual target hardware is a hassle so I typically write everything on an Intel based PC either in Windows or Linux using Ceedling and GCC. That being said, a lot of embedded code involves bit twiddling and address manipulations. Most of my Intel machines are 64 bit. So if you are going to test address manipulation code you need a generalized object to do math on. Thus the uintptr_t give you a machine independent way of debugging your code before you try deploying to target hardware. Another issue is for the some machines or even memory models on some compilers, function pointers and data pointers are different widths. On those machines the compiler may not even allow casting between the two classes, but uintptr_t should be able to hold either. -- Edit -- Was pointed out by @chux, this is not part of the standard and functions are not objects in C. However it usually works and since many people don't even know about these types I usually leave a comment explaining the trickery. Other searches in SO on uintptr_t will provide further explanation. Also we do things in unit testing that we would never do in production because breaking things is good.
It hides the intention of the code.
It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.
Some use it as a faster alternative to Math.floor
, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.
With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~
instead of Math.floor
is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.
See: tilde vs floor
You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:
process(b0,b1,b2,b3)
variable bcat : std_logic_vector(0 to 3);
begin
bcat := b0 & b1 & b2 & b3;
case bcat is
when "0000" => x <= 1;
when others => x <= 2;
end case;
end process;
For Single valued associations, i.e.-One-to-One and Many-to-One:-
Default Lazy=proxy
Proxy lazy loading:- This implies a proxy object of your associated entity is loaded. This means that only the id connecting the two entities is loaded for the proxy object of associated entity.
Eg: A and B are two entities with Many to one association. ie: There may be multiple A's for every B. Every object of A will contain a reference of B.
`
public class A{
int aid;
//some other A parameters;
B b;
}
public class B{
int bid;
//some other B parameters;
}
`
The relation A will contain columns(aid,bid,...other columns of entity A).
The relation B will contain columns(bid,...other columns of entity B)
Proxy implies when A is fetched, only id is fetched for B and stored into a proxy object of B which contains only id.
Proxy object of B is a an object of a proxy-class which is a subclass of B with only minimal fields.
Since bid is already part of relation A, it is not necessary to fire a query to get bid from the relation B.
Other attributes of entity B are lazily loaded only when a field other than bid is accessed.
For Collections, i.e.-Many-to-Many and One-to-Many:-
Default Lazy=true
Please also note that the fetch strategy(select,join etc) can override lazy.
ie: If lazy='true' and fetch='join', fetching of A will also fetch B or Bs(In case of collections). You can get the reason if you think about it.
Default fetch for single valued association is "join".
Default fetch for collections is "select".
Please verify the last two lines. I have deduced that logically.
I move the whole directory from my Windows installation to a unix production server and I got the same error. To fix it, I just ran these two lines in unix and everything started to run fine
rm -rf app/cache/*
rm -rf app/logs/*
The sql query sample like this
LEFT JOIN bookings
ON rooms.id = bookings.room_type_id
AND (bookings.arrival = ?
OR bookings.departure = ?)
Laravel join with multiple conditions
->leftJoin('bookings', function($join) use ($param1, $param2) {
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on(function($query) use ($param1, $param2) {
$query->on('bookings.arrival', '=', $param1);
$query->orOn('departure', '=',$param2);
});
})
You could also put your JSON content in a file and pass it to curl using the --upload-file
option via standard input, like this:
echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -
To retrieve the height of the ActionBar in XML, just use
?android:attr/actionBarSize
or if you're an ActionBarSherlock or AppCompat user, use this
?attr/actionBarSize
If you need this value at runtime, use this
final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
If you need to understand where this is defined:
Just for future needs.
In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window
to make it work.
<Grid Name="myGrid" Height="437.274">
<TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>
If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:
columns = ['Y'+str(i) for year in range(1967, 2011)]
df.groupby('Country')[columns].agg('sum')
In my case, I found that I set the post method as private mistakenly. after changing private to public.
[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}
change to
[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}
Now works fine.
For French Locale (France) ONLY, be careful because /
appears in the date :
echo %DATE%
08/09/2013
For our problem of log file, here is my proposal for French Locale ONLY:
SETLOCAL
set LOGFILE_DATE=%DATE:~6,4%.%DATE:~3,2%.%DATE:~0,2%
set LOGFILE_TIME=%TIME:~0,2%.%TIME:~3,2%
set LOGFILE=log-%LOGFILE_DATE%-%LOGFILE_TIME%.txt
rem log-2014.05.19-22.18.txt
command > %LOGFILE%
DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed
You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
You can also use .replaceWith()
, like this:
$("b").replaceWith(function() { return $(this).contents(); });
Or if you know it's just a string:
$("b").replaceWith(function() { return this.innerHTML; });
This can make a big difference if you're unwrapping a lot of elements since either approach above is significantly faster than the cost of .unwrap()
.
I ran into the same problem as you. I wanted to make a DIV
as background, why, because its easy to manipulate div through javascript. Anyways three things I did in the css for that div.
CSS:
{
position:absolute;
display:block;
height:100%;
width:100%;
top:0px;
left:0px;
z-index:-1;
}
Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.
Created an angular directive called modal and used in html. Explanation:-
HTML
<div ng-controller="MainCtrl" class="container">
<button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
<button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
<button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
<button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
<modal visible="showModal">
Any additional data / buttons
</modal>
</div>
On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.
JS
var mymodal = angular.module('mymodal', []);
mymodal.controller('MainCtrl', function ($scope) {
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function(btnClicked){
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
UPDATE
<!doctype html>
<html ng-app="mymodal">
<body>
<div ng-controller="MainCtrl" class="container">
<button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
<button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
<button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
<button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
<modal visible="showModal">
Any additional data / buttons
</modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<!-- App -->
<script>
var mymodal = angular.module('mymodal', []);
mymodal.controller('MainCtrl', function ($scope) {
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function(btnClicked){
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
</script>
</body>
</html>
UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is
<modal>
Other values are 'A' for attribute
<div modal>
'C' for class (not preferable in our case because modal is already a class in bootstrap.css)
<div class="modal">
I have an histogram with the variable : group
Here how I calculate my median :
int[] group = new int[nbr];
// -- Fill the group with values---
// sum all data in median
int median = 0;
for (int i =0;i<nbr;i++) median += group[i];
// then divide by 2
median = median / 2;
// find 50% first part
for (int i = 0; i < nbr; i++)
{
median -= group[i];
if (median <= 0)
{
median = i;
break;
}
}
median is the group index of median
select T.TABLE_NAME, T.TABLESPACE_NAME, t.avg_row_len*t.num_rows from dba_tables t
order by T.TABLE_NAME asc
See e.g. http://www.dba-oracle.com/t_script_oracle_table_size.htm for more options
You can solve your issue by using the 'contains' function within your Xpath query, as below:
var allElementsWithClassFloat =
_doc.DocumentNode.SelectNodes("//*[contains(@class,'float')]")
To reuse this in a function do something similar to the following:
string classToFind = "float";
var allElementsWithClassFloat =
_doc.DocumentNode.SelectNodes(string.Format("//*[contains(@class,'{0}')]", classToFind));
PowerShell features a Restart-Service
cmdlet, which either starts or restarts the service as appropriate.
The
Restart-Service
cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error.You can specify the services by their service names or display names, or you can use the
InputObject
parameter to pass an object that represents each service that you want to restart.
It is a little more foolproof than running two separate commands.
The easiest way to use it just pass either the service name or the display name directly:
Restart-Service 'Service Name'
It can be used directly from the standard cmd prompt with a command like:
powershell -command "Restart-Service 'Service Name'"
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
Use git log
to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787
and b410ad4619d296f9d37f0db3d0ff5b9066838b39
). To view the difference between two different commits, use git diff
with the first few characters of the revision specifiers of both commits, like so:
# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b
If you want to get an overview over all the differences that happened from commit to commit, use git log
or git whatchanged
with the patch option:
# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d
I followed an example in another repository and wrapped the directory structure within a pair of triple backticks (```
):
```
project
¦ README.md
¦ file001.txt
¦
+---folder1
¦ ¦ file011.txt
¦ ¦ file012.txt
¦ ¦
¦ +---subfolder1
¦ ¦ file111.txt
¦ ¦ file112.txt
¦ ¦ ...
¦
+---folder2
¦ file021.txt
¦ file022.txt
```
This worked for me: (notice that java 8 is required)
String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);
UserJsonParse is a class that shows gson how to parse the json formant.
class is like that:
public class UserJsonParser {
private String username;
private String name;
private String lastname;
private String mail;
private String pass1;
//then put setters and getters
}
the json string that is parsed is like that:
$jsonData: { "username": "testuser", "pass1": "clave1234" }
The rest of values (mail, lastname, name) are set to null
I like this one:
very slick with only this as HTML and the rest CSS3 that is backwards compatible (although it will have less eyecandy)
Edit Added code below, but taken directly from the page above, all credit to that author
.meter {_x000D_
height: 20px;_x000D_
/* Can be anything */_x000D_
position: relative;_x000D_
background: #555;_x000D_
-moz-border-radius: 25px;_x000D_
-webkit-border-radius: 25px;_x000D_
border-radius: 25px;_x000D_
padding: 10px;_x000D_
-webkit-box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
-moz-box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
}_x000D_
_x000D_
.meter>span {_x000D_
display: block;_x000D_
height: 100%;_x000D_
-webkit-border-top-right-radius: 8px;_x000D_
-webkit-border-bottom-right-radius: 8px;_x000D_
-moz-border-radius-topright: 8px;_x000D_
-moz-border-radius-bottomright: 8px;_x000D_
border-top-right-radius: 8px;_x000D_
border-bottom-right-radius: 8px;_x000D_
-webkit-border-top-left-radius: 20px;_x000D_
-webkit-border-bottom-left-radius: 20px;_x000D_
-moz-border-radius-topleft: 20px;_x000D_
-moz-border-radius-bottomleft: 20px;_x000D_
border-top-left-radius: 20px;_x000D_
border-bottom-left-radius: 20px;_x000D_
background-color: #f1a165;_x000D_
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #f1a165), color-stop(1, #f36d0a));_x000D_
background-image: -webkit-linear-gradient(top, #f1a165, #f36d0a);_x000D_
background-image: -moz-linear-gradient(top, #f1a165, #f36d0a);_x000D_
background-image: -ms-linear-gradient(top, #f1a165, #f36d0a);_x000D_
background-image: -o-linear-gradient(top, #f1a165, #f36d0a);_x000D_
-webkit-box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);_x000D_
-moz-box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="meter">_x000D_
<span style="width: 33%"></span>_x000D_
<!-- I use my viewmodel in MVC to calculate the progress and then use @Model.progress to place it in my HTML with Razor -->_x000D_
</div>
_x000D_
In my case, the tomcat directory was owned by root, and I was not running eclipse as root.
So I had to
sudo chown -R $USER apache-tomcat-VERSION/
To add to the above correct answer :-
For my case in shell, this code worked (working on sqoop
)
ROOT_PATH="path/to/the/folder"
--options-file $ROOT_PATH/query.txt
If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.
However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.
You can do:
t1<- t1[-4:-6,-7:-9]
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
From Python documentation. Using the built in format() function you can specify hexadecimal base using an 'x' or 'X' Example:
x= 255 print('the number is {:x}'.format(x))
Output:
the number is ff
Here are the base options
Type
'b' Binary format. Outputs the number in base 2.
'c' Character. Converts the integer to the corresponding unicode character before printing.
'd' Decimal Integer. Outputs the number in base 10.
'o' Octal format. Outputs the number in base 8.
'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9.
'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9.
'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
None The same as 'd'.
.ico
, or is it just named ".ico"?The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.
If you must have it in a subdirectory, use:
<link rel="shortcut icon" href="/img/favicon.ico" />
Note the /
before img
to ensure it is anchored to the root folder.
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
I have adopted your script for my situation Jotne.
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{print $1}')
;;
esac
While I was testing, I ran into a problem..
I started 3 extra process's of oscam1 with this line:
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1
which left me with 8 process for oscam1. the problem is this..
When I run the script, It only kills 2 process's at a time, so I would have to run it 3 times to get it down to 2 process..
Other than killall -9 oscam1
followed by /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1
, in *)
is there any better way to killall apart from the original process? So there would be zero downtime?
function toggleCheck(employeeId) {
var data = 'referenceid= '+ employeeId +'&referencestatus=' 1;
console.log(data);
$.ajax({
type : 'POST',
url : 'edit',
data : data,
cache: false,
async : false,
success : function(employeeId) {
alert("Success");
window.redirect = "Users.jsp";
}
});
}
Your question implies that you're building the INSERT statement up by concatenating strings together. I suggest that this is a poor choice as it leaves you open to SQL injection attacks if the strings are derived from user input. A better choice is to use parameter markers and to bind the values to the markers. If you search for Oracle parameter markers
you'll probably find some information for your specific implementation technology (e.g. C# and ADO, Java and JDBC, Ruby and RubyDBI, etc).
Share and enjoy.
To remove all child elements from your div:
$('#mysweetdiv').empty();
.removeData()
and the corresponding .data()
function are used to attach data behind an element, say if you wanted to note that a specific list element referred to user ID 25 in your database:
var $li = $('<li>Joe</li>').data('id', 25);
A missing intermediate certificate might be the problem.
You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.
No idea why Chrome (possibly) sometimes has problems validating these certs.
explain: 1.the first one declare the variable in array.
2.the second array_push method is used to push the string in the array variable.
3.finally it will print the result.
4.the second method is directly store the string in the array.
5.the data is printed in the array values in using print_r method.
this two are same
bool _visible = false;
void _toggle() {
setState(() {
_visible = !_visible;
});
}
onPressed: _toggle,
Visibility(
visible:_visible,
child: new Container(
child: new Container(
padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 10.0),
child: new Material(
elevation: 10.0,
borderRadius: BorderRadius.circular(25.0),
child: new ListTile(
leading: new Icon(Icons.search),
title: new TextField(
controller: controller,
decoration: new InputDecoration(
hintText: 'Search for brands and products', border: InputBorder.none,),
onChanged: onSearchTextChanged,
),
trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
controller.clear();
onSearchTextChanged('');
},),
),
),
),
),
),
To initialize 2d array with zero use the below method:
int arr[n][m] = {};
NOTE : The above method will only work to initialize with 0;
Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.
var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);
I just want to add to the answers that if you want to display a field that is nested in another object, you can use the following syntax
db.collection.find( {}, {{'object.key': true}})
Here key is present inside the object named object
{ "_id" : ObjectId("5d2ef0702385"), "object" : { "key" : "value" } }
To avoid string conversions comparisons, use COLLATE SQL_Latin1_General_CP1_CI_AS.
EXAMPLE:
SELECT UserName FROM Users
WHERE UserName **COLLATE SQL_Latin1_General_CP1_CI_AS** = 'Angel'
That will return any usernames, whether ANGEL, angel, or Angel, etc.
(This was a comment to dilettante's answer but it got too long...hehe)
Of course a static is not needed here. You could use SharedPreferences to save, instead of static. Either way, the reason is to save the current progress so that its not too slow for complicated layouts. Because, in fact, after its used once, it will be rather fast later. However, I dont feel this is a good way to do it because if you have to rebuild your screen again (say onCreate
gets called again), then you probably want to start over from the beginning anyhow, eliminating the need for static. Therefore, just make it an instance variable instead of static.
Here is a smaller version that runs a bit faster and might be easier to read:
int fID = 0;
public int findUnusedId() {
while( findViewById(++fID) != null );
return fID;
}
This above function should be sufficient. Because, as far as I can tell, android-generated IDs are in the billions, so this will probably return 1
the first time and always be quite fast.
Because, it wont actually be looping past the used IDs to find an unused one. However, the loop is there should it actually find a used ID.
However, if you still want the progress saved between subsequent recreations of your app, and want to avoid using static. Here is the SharedPreferences version:
SharedPreferences sp = getSharedPreferences("your_pref_name", MODE_PRIVATE);
public int findUnusedId() {
int fID = sp.getInt("find_unused_id", 0);
while( findViewById(++fID) != null );
SharedPreferences.Editor spe = sp.edit();
spe.putInt("find_unused_id", fID);
spe.commit();
return fID;
}
This answer to a similar question should tell you everything you need to know about IDs with android: https://stackoverflow.com/a/13241629/693927
EDIT/FIX: Just realized I totally goofed up the save. I must have been drunk.
Upon downloading Bootstrap 3.x, you'll get bootstrap.css and bootstrap-theme.css (not to mention the minified versions of these files that are also present).
bootstrap.css
is completely styled and ready to use, if such is your desire. It is perhaps a bit plain but it is ready and it is there.
You do not need to use bootstrap-theme.css if you don't want to and things will be just fine.
bootstrap-theme.css
is just what the name of the file is trying to suggest: it is a theme for bootstrap that is creatively considered 'THE bootstrap theme'. The name of the file confuses things just a bit since the base bootstrap.css
already has styling applied and I, for one, would consider those styles to be the default. But that conclusion is apparently incorrect in light of things said in the Bootstrap documentation's examples section in regard to this bootstrap-theme.css
file:
"Load the optional Bootstrap theme for a visually enhanced experience."
The above quote is found here http://getbootstrap.com/getting-started/#examples on a thumbnail that links to this example page http://getbootstrap.com/examples/theme/. The idea is that bootstrap-theme.css
is THE bootstrap theme AND it's optional.
About the themes at BootSwatch.com: These themes are not implemented like bootstrap-theme.css
. The BootSwatch themes are modified versions of the original bootstrap.css
. So, you should definitely NOT use a theme from BootSwatch AND the bootstrap-theme.css
file at the same time.
About Your Own Custom Theme: You might choose to modify bootstrap-theme.css
when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.
First you need to import the angular router :
import {Router} from "@angular/router"
Then inject it in your component constructor :
constructor(private router: Router) { }
And finally call the .navigate
method anywhere you need to "redirect" :
this.router.navigate(['/your-path'])
You can also put some parameters on your route, like user/5
:
this.router.navigate(['/user', 5])
Documentation: Angular official documentaiton
Run package declaration and body separately.
for react-router V5 and above use below syntax for multiple paths
<Route
exact
path={[path1, path2]}
component={component}
/>
For anyone returning to this question. The correct "Angular Way" to remove items from an array is with $filter. Just inject $filter into your controller and do the following:
$scope.items = $filter('filter')($scope.items, {name: '!ted'})
You don't need to load any additional libraries or resort to Javascript primitives.
Step 1
Go to S:\MAMP
enter code here
\bin\apache\conf\
open httpd.conf
file and change
#Include conf/extra/httpd-vhosts.conf
to
Include conf/extra/httpd-vhosts.conf
i.e. uncomment the line so that it can includes the virtual hosts file.
Step 2
Go to S:\MAMP\bin\apache\conf\extra
and open httpd-vhosts.conf
file and add the following code
<VirtualHost myWebsite.local>
DocumentRoot "S:\MAMP\htdocs/myWebsite/"
ServerName myWebsite.local
ServerAlias myWebsite.local
<Directory "S:\MAMP\htdocsmyWebsite/">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
change myWebsite.local
and S:\MAMP\htdocs/myWebsite/
as per your requirements.
Step 3
Open hosts
file in C:/Windows/System32/drivers/etc/
and add the following line ( Don't delete anything )
127.0.0.1 myWebsite.local
change myWebsite.local
as per your name requirements
Step 4
restart your server. That's it
$query->num_rows()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
It's a shame that we need multiple ARG too, it results in multiple layers and slows down the build because of that, and for anyone also wondering that, currently there is no way to set multiple ARGs.
mkdir -p
-p, --parents no error if existing, make parent directories as needed
Or.... Call your main .bat file from another .bat file and output the result to a result file i.e.
runner.bat > mainresults.txt
Where runner.bat calls the main .bat file
You should see all the actions performed in the main .bat file now
It is the two step process:
Delete all data from that table using:
Delete from TableName
Then:
DELETE FROM SQLITE_SEQUENCE WHERE name='TableName';
jQuery has a toggleClass function:
<button class="switch">Click me</button>
<div class="text-block collapsed pressed">some text</div>
<script>
$('.switch').on('click', function(e) {
$('.text-block').toggleClass("collapsed pressed"); //you can list several class names
e.preventDefault();
});
</script>
Try this instead in the end:
exec (@query)
If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.
OR
EXECUTE sp_executesql @query
And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.
Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.
On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?
you can't get the expiration date of a cookie through javascript because when you try to read the cookie from javascript the document.cookie return just the name and the value of the cookie as pairs
I am currently responsible for an Excel application with a lot of legacy code. One of the slowest pieces of this code was looping through 500 Rows in 6 Columns, setting conditional formatting formulae for each. The formulae are to identify where the cell contents are non-blank but do not form part of a Named Range, therefore referring twice to the cell itself, originally written as:
=AND(COUNTIF(<rangename>,<cellref>)=0,<cellref><>"")
Obviously the overheads would be much reduced by updating all Cells in each Column (Range) at once. However, as noted above, using ADDRESS(ROW(),COLUMN(),n) does not work in this circumstance, i.e. this does not work:
=AND(COUNTIF(<rangename>,ADDRESS(ROW(),COLUMN(),1))=0,ADDRESS(ROW(),COLUMN(),1)<>"")
I experimented extensively with a blank workbook and could find no way around this, using various alternatives such as ISBLANK. In the end, to get around this, I created two User-Defined Functions (using a tip I found elsewhere on this site):
Public Function returnCellContent() As Variant
returnCellContent = Application.Caller.Value
End Function
Public Function Cell_HasContent() As Boolean
If Application.Caller.Value = "" Then
Cell_HasContent = False
Else
Cell_HasContent = True
End If
End Function
The conditional formula is now:
=AND(COUNTIF(<rangename>,returnCellContent()=0,Cell_HasContent())
which works fine.
This has sped the code up, in Excel 2010, from 5s to 1s. Because this code is run whenever data is loaded into the application, this saving is significant and noticeable to the user. It's also a lot cleaner and reusable.
I've taken the time to post this because I could not find any answers on this site or elsewhere that cover all of the circumstances, whilst I'm sure that there are others who could benefit from the above approach, potentially with much larger numbers of cells to update.
My Method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String path = request.getRealPath("/WEB-INF/conf.properties");
Properties p = new Properties();
p.load(new FileInputStream(path));
String StringConexion=p.getProperty("StringConexion");
String User=p.getProperty("User");
String Password=p.getProperty("Password");
}
catch(Exception e){
String msg = "Excepcion " + e;
}
}
Running the below command solved the problem for me.
git config --global credential.helper wincred
Please refer the below github documentation:
https://help.github.com/articles/caching-your-github-password-in-git/
Yes its possible Here the code is
const fs = require('fs')
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => {
// In case of a error throw err.
if (err) throw err;
})
_x000D_
TinyXML can be best for simple XML work but if you need more features then try Xerces from the apache project. Go to the following page to read more about its features.
I do it the following way:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
StringBuilder result = new StringBuilder();
for(Object item:this) {
result.append(item.toString());
result.append("\n"); //optional
}
return result.toString();
}
As bmargulies mentioned:
Preferences>Java>Editor>Templates>New...
Now, type psvm then Ctrl + Space
on Mac or Windows.
Is the size of C “int” 2 bytes or 4 bytes?
Does an Integer variable in C occupy 2 bytes or 4 bytes?
C allows "bytes" to be something other than 8 bits per "byte".
CHAR_BIT
number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1
A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT
rather than 8. The size of an int
in bits in C is sizeof(int) * CHAR_BIT
.
#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);
What are the factors that it depends on?
The int
bit size is commonly 32 or 16 bits. C specified minimum ranges:
minimum value for an object of type
int
INT_MIN
-32767
maximum value for an object of typeint
INT_MAX
+32767
C11dr §5.2.4.2.1 1
The minimum range for int
forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int
bit sizes.
The computer's processor and architecture drive the int
bit size selection.
Yet even with 64-bit processors, the compiler's int
size may be 32-bit for compatibility reasons as large code bases depend on int
being 32-bit (or 32/16).
What is Stroke
:
The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.
https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html
Note that the Stroke
setting:
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));
is setting the line width,since BasicStroke(float width)
:
Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.
And, it also effects other methods like Graphics2D.drawLine(int x1, int y1, int x2, int y2)
and Graphics2D.drawRect(int x, int y, int width, int height)
:
The methods of the Graphics2D interface that use the outline Shape returned by a Stroke object include draw and any other methods that are implemented in terms of that method, such as drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, and drawPolygon.
You can use:
$("#tagscloud span").text("Your text here");
The same code will also work for the second case. You could also use:
$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");
What means about isKindOfClass in Apple Documentation
Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected. If you call a method that returns a class cluster, the exact type returned by the method is the best indicator of what you can do with that object. For example, if a method returns a pointer to an NSArray object, you should not use this method to see if the array is mutable, as shown in the following code:
// DO NOT DO THIS!
if ([myArray isKindOfClass:[NSMutableArray class]])
{
// Modify the object
}
If you use such constructs in your code, you might think it is alright to modify an object that in reality should not be modified. Doing so might then create problems for other code that expected the object to remain unchanged.
I would advise, it is slightly better practise to use string model references for ForeignKey
relationships if utilising an app based approach to seperation of logical concerns .
So, expanding on Martijn Pieters' answer:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
'app_label.Anniversary', on_delete=models.CASCADE)
address = models.ForeignKey(
'app_label.Address', on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Try using double quotes if it's a char variable:
DEFINE stupidvar = "'stupidvarcontent'";
or
DEFINE stupidvar = 'stupidvarcontent';
SELECT stupiddata
FROM stupidtable
WHERE stupidcolumn = '&stupidvar'
upd:
SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old 1: select code from product where code = &var
new 1: select code from product where code = 'FL-208'
CODE
---------------
FL-208
SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old 1: select code from product where code = &var
new 1: select code from product where code = FL-208
select code from product where code = FL-208
*
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined
Firstly install ffmpeg-php
project (http://ffmpeg-php.sourceforge.net/)
And then you can use of this simple code:
<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';
$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
$gd_image = $frame->toGDImage();
if ($gd_image) {
imagepng($gd_image, $thumbnail);
imagedestroy($gd_image);
echo '<img src="'.$thumbnail.'">';
}
}
?>
Description: This project use binary extension .so
file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg
or PHP
.
Firstly install PHP-FFMpeg
project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg
)
And then you can use of this simple code:
<?php
require 'vendor/autoload.php';
$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';
Description: It's newer and more modern project and works with latest version of FFMpeg
and PHP
. Note that it's required to proc_open()
PHP function.
I actually just overwrite anything I want to change in the site.css, you should load the site.css after bootstrap so it will overwrite the classes. What I have done now is just made my own classes with my own little bootstrap theme. Little things like this
.navbar-nav li a{
color: #fff;
font-size: 15px;
margin-top: 9px;
}
.navbar-nav li a:hover{
background-color: #18678E;
height: 61px;
}
I also changed the likes of the validations errors the same way.
It is surprisingly simple...
Code behind:
// Here's your object that you'll create a list of
private class Products
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
}
// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{
// The the LIST as the DataSource
this.rptItemsInCart.DataSource = ListOfSelectedProducts;
// Then bind the repeater
// The public properties become the columns of your repeater
this.rptItemsInCart.DataBind();
}
ASPX code:
<asp:Repeater ID="rptItemsInCart" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("ProductName") %></td>
<td><%# Eval("ProductDescription")%></td>
<td><%# Eval("ProductPrice")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
I hope this helps!
If you face this issue only in Chrome and in IE, for instance, everything is fine, then just enable checkbutton "Disable cache" in Dev Tools (F12 -> "Network" tab) and clear history in the last hour.
I had this problem and above solution worked for me.
This should solve it:
git config --unset core.bare
Just use com.google.common.io.Resources class. Example:
URL url = Resources.getResource("file name")
After that you have methods like: .getContent(), .getFile(), .getPath() etc
In function post():
todo.author = users.get_current_user()
So, to get str(todo.author), you need str(users.get_current_user()). What is returned by get_current_user() function ?
If it is an object, check does it contain a str()" function?
I think the error lies there.
Like samplebias answer, again if Javascript is an acceptable answer, I made a jQuery plugin specifically for this purpose: https://github.com/marcogrcr/jquery-tableoverflow
To use the plugin just type
$('selector').tableoverflow();
Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/
Edits:
I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my very similar problem. I know some of the other solutions look shorter but they seem to use SUBSTRING_INDEX() way more than necessary. Here I try to just use LOCATE() just once per delimiter.
-- *****************************************************************************
-- test_PVreplace
DROP FUNCTION IF EXISTS test_PVreplace;
delimiter //
CREATE FUNCTION test_PVreplace (
str TEXT, -- String to do search'n'replace on
pv TEXT -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
)
RETURNS TEXT
-- Replace specific tags with specific values.
sproc:BEGIN
DECLARE idx INT;
DECLARE idx0 INT DEFAULT 1; -- 1-origined, not 0-origined
DECLARE len INT;
DECLARE sPV TEXT;
DECLARE iPV INT;
DECLARE sP TEXT;
DECLARE sV TEXT;
-- P/V string *must* end with a delimiter.
IF (RIGHT (pv, 1) <> '|') THEN
SET pv = CONCAT (pv, '|');
END IF;
-- Find all the P/V pairs.
SELECT LOCATE ('|', pv, idx0) INTO idx;
WHILE (idx > 0) DO
SET len = idx - idx0;
SELECT SUBSTRING(pv, idx0, len) INTO sPV;
-- Found a P/V pair. Break it up.
SELECT LOCATE ('=', sPV) INTO iPV;
IF (iPV = 0) THEN
SET sP = sPV;
SET sV = '';
ELSE
SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
SELECT SUBSTRING(sPV, iPV+1) INTO sV;
END IF;
-- Do the substitution(s).
SELECT REPLACE (str, sP, sV) INTO str;
-- Do next P/V pair.
SET idx0 = idx + 1;
SELECT LOCATE ('|', pv, idx0) INTO idx;
END WHILE;
RETURN (str);
END//
delimiter ;
SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');
You can use find()
>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s[:s.find('&')]
'http://www.domain.com/?s=some'
Of course, if there is a chance that the searched for text will not be present then you need to write more lengthy code:
pos = s.find('&')
if pos != -1:
s = s[:pos]
Whilst you can make some progress using code like this, more complex situations demand a true URL parser.
In my case, I have added the same custom component as a prop instead of actual prob
import AddAddress from '../../components/Manager/AddAddress';
class Add extends React.PureComponent {
render() {
const {
history,
addressFormData,
formErrors,
addressChange,
addAddress,
isDefault,
defaultChange
} = this.props;
Error:
return (
<AddAddress
addressFormData={addressFormData}
formErrors={formErrors}
addressChange={addressChange}
addAddress={AddAddress} // here i have used the Component name as probs in same component itself instead of prob
isDefault={isDefault}
defaultChange={defaultChange}
/>
</SubPage>
Solution:
return (
<AddAddress
addressFormData={addressFormData}
formErrors={formErrors}
addressChange={addressChange}
addAddress={addAddress} // removed the component name and give prob name
isDefault={isDefault}
defaultChange={defaultChange}
/>
</SubPage>
It simply means that the time needed for this task grows with log(n) (example : 2s for n = 10, 4s for n = 100, ...). Read the Wikipedia articles on Binary Search Algorithm and Big O Notation for more precisions.
StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());
If you are using RxJS 6.0.0:
import { from } from 'rxjs';
const observable = from(promise);
soup = BeautifulSoup(html)
for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
hit = hit.text.strip()
print hit
This will print: THIS IS MY TEXT Try this..
list multiplication works.
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Try this:
Dim text As String = ""
Dim files() As String = IO.Directory.GetFiles(sFolder)
For Each sFile As String In files
text &= IO.File.ReadAllText(sFile)
Next
You can use
try {
user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
// do something if you want
}
The Method Works Properly For me:
var lanopt = $(".language-option");
lanopt.on("show.bs.collapse",".collapse", function(){
lanopt.find(".collapse.in").collapse("hide");
});
And here is a simple Send-MailMessage
example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
I'm unable to find an scenario where a global var
is the best option, of course you can have one, but take a look at these examples and you may find a better way to accomplish the same:
You need some value that it's the same across the application, but it changes depending on the environment (production, dev or test), the mailer type as example, you'd need:
// File: config/environments/production.json
{
"mailerType": "SMTP",
"mailerConfig": {
"service": "Gmail",
....
}
and
// File: config/environments/test.json
{
"mailerType": "Stub",
"mailerConfig": {
"error": false
}
}
(make a similar config for dev too)
To decide which config will be loaded make a main config file (this will be used all over the application)
// File: config/config.js
var _ = require('underscore');
module.exports = _.extend(
require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});
And now you can get the data like this:
// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));
// File: constants.js
module.exports = {
appName: 'My neat app',
currentAPIVersion: 3
};
And use it this way
// File: config/routes.js
var constants = require('../constants');
module.exports = function(app, passport, auth) {
var apiroot = '/api/v' + constants.currentAPIVersion;
...
app.post(apiroot + '/users', users.create);
...
Not a big fan of this one, but at least you can track the use of the 'name' (citing the OP's example) and put validations in place.
// File: helpers/nameHelper.js
var _name = 'I shall not be null'
exports.getName = function() {
return _name;
};
exports.setName = function(name) {
//validate the name...
_name = name;
};
And use it
// File: controllers/users.js
var nameHelper = require('../helpers/nameHelper.js');
exports.create = function(req, res, next) {
var user = new User();
user.name = req.body.name || nameHelper.getName();
...
There could be a use case when there is no other solution than having a global var
, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.
This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python
with open('words.txt') as fp:
contents = fp.read()
for entry in contents:
# do something with entry
Here is my solution in a recent project.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Sample</title>_x000D_
</head>_x000D_
<body>_x000D_
<h1 id="hello_world">Sample</h1>_x000D_
<script type="text/javascript">_x000D_
var div = document.createElement("div");_x000D_
var t = document.createElement('template');_x000D_
t.innerHTML = "Check Console tab for javascript output: Hello world!!!<br/><script type='text/javascript' >console.log('Hello world!!!');<\/script>";_x000D_
_x000D_
for (var i=0; i < t.content.childNodes.length; i++){_x000D_
var node = document.importNode(t.content.childNodes[i], true);_x000D_
div.appendChild(node);_x000D_
}_x000D_
document.body.appendChild(div);_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The other answers involving RTTI (typeid) are probably what you want, as long as:
The alternative, (similar to Greg Hewgill's answer), is to build a compile-time table of traits.
template <typename T> struct type_as_string;
// declare your Wibble type (probably with definition of Wibble)
template <>
struct type_as_string<Wibble>
{
static const char* const value = "Wibble";
};
Be aware that if you wrap the declarations in a macro, you'll have trouble declaring names for template types taking more than one parameter (e.g. std::map), due to the comma.
To access the name of the type of a variable, all you need is
template <typename T>
const char* get_type_as_string(const T&)
{
return type_as_string<T>::value;
}
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
If you want to set cookie and get it outside of request, Laravel is not your friend.
Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.
Non-algorithmic answer, yet "efficient" when I do it:
step 1) discard all your existing socks
step 2) go to Walmart and buy them by packets of 10 - n packet of white and m packets of black. No need for other colors in everyday's life.
Yet times to times, I have to do this again (lost socks, damaged socks, etc.), and I hate to discard perfectly good socks too often (and I wished they kept selling the same socks reference!), so I recently took a different approach.
Algorithmic answer:
Consider than if you draw only one sock for the second stack of socks, as you are doing, your odds of finding the matching sock in a naive search is quite low.
Why five? Usually humans are good are remembering between five and seven different elements in the working memory - a bit like the human equivalent of a RPN stack - five is a safe default.
Pick up one from the stack of 2n-5.
Now look for a match (visual pattern matching - humans are good at that with a small stack) inside the five you drew, if you don't find one, then add that to your five.
Keep randomly picking socks from the stack and compare to your 5+1 socks for a match. As your stack grows, it will reduce your performance but raise your odds. Much faster.
Feel free to write down the formula to calculate how many samples you have to draw for a 50% odds of a match. IIRC it's an hypergeometric law.
I do that every morning and rarely need more than three draws - but I have n
similar pairs (around 10, give or take the lost ones) of m
shaped white socks. Now you can estimate the size of my stack of stocks :-)
BTW, I found that the sum of the transaction costs of sorting all the socks every time I needed a pair were far less than doing it once and binding the socks. A just-in-time works better because then you don't have to bind the socks, and there's also a diminishing marginal return (that is, you keep looking for that two or three socks that when somewhere in the laundry and that you need to finish matching your socks and you lose time on that).
Get the version of Boost that you require. This is for 1.55 but feel free to change or manually download yourself (Boost download page):
wget -O boost_1_55_0.tar.gz https://sourceforge.net/projects/boost/files/boost/1.55.0/boost_1_55_0.tar.gz/download tar xzvf boost_1_55_0.tar.gz cd boost_1_55_0/
Get the required libraries, main ones are icu for boost::regex support:
sudo apt-get update sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev libbz2-dev
Boost's bootstrap setup:
./bootstrap.sh --prefix=/usr/local
If we want MPI then we need to set the flag in the user-config.jam file:
user_configFile=`find $PWD -name user-config.jam` echo "using mpi ;" >> $user_configFile
Find the maximum number of physical cores:
n=`cat /proc/cpuinfo | grep "cpu cores" | uniq | awk '{print $NF}'`
Install boost in parallel:
sudo ./b2 --with=all -j $n install
Assumes you have /usr/local/lib setup already. if not, you can add it to your LD LIBRARY PATH:
sudo sh -c 'echo "/usr/local/lib" >> /etc/ld.so.conf.d/local.conf'
Reset the ldconfig:
sudo ldconfig
I have a struct KeyValuePairSerializable
:
[Serializable]
public struct KeyValuePairSerializable<K, V>
{
public KeyValuePairSerializable(KeyValuePair<K, V> pair)
{
Key = pair.Key;
Value = pair.Value;
}
[XmlAttribute]
public K Key { get; set; }
[XmlText]
public V Value { get; set; }
public override string ToString()
{
return "[" + StringHelper.ToString(Key, "") + ", " + StringHelper.ToString(Value, "") + "]";
}
}
Then, the XML serialization of a Dictionary
property is by:
[XmlIgnore]
public Dictionary<string, string> Parameters { get; set; }
[XmlArray("Parameters")]
[XmlArrayItem("Pair")]
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // not necessary
public KeyValuePairSerializable<string, string>[] ParametersXml
{
get
{
return Parameters?.Select(p => new KeyValuePairSerializable<string, string>(p)).ToArray();
}
set
{
Parameters = value?.ToDictionary(i => i.Key, i => i.Value);
}
}
Just the property must be the array, not the List.
Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.
You can use the following code snippet:
myTextBox.SelectionStart = myTextBox.Text.Length;
myTextBox.ScrollToCaret();
which will automatically scroll to the end.
Per above, a dataset or typed dataset might be a good temorary structure which you could use to do your filtering. A SqlDataReader is meant to read the data very quickly. While you are in the while() loop you are still connected to the DB and it is waiting for you to do whatever you are doing in order to read/process the next result before it moves on. In this case you might get better performance if you pull in all of the data, close the connection to the DB and process the results "offline".
People seem to hate datasets, so the above could be done wiht a collection of strongly typed objects as well.
1 - Close CMD Window
2 - Add C:\Program Files\nodejs
to PATH variable
3 - Open new CMD, type: npm -v
and enjoy ;)
In addition to some of the other answers, you could also access the HTML element via:
var htmlEl = document.body.parentNode;
Then you could get the inner HTML content:
var inner = htmlEl.innerHTML;
Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode
seems to be quite a bit faster.
After you have the HTML element, you can mess with the attributes with the getAttribute
and setAttribute
methods.
For the DOCTYPE, you could use document.doctype
, which was elaborated upon in this question.
There's something overly verbose to me about the if ((x & y) == y)...
construct, especially if x
AND y
are both compound sets of flags and you only want to know if there's any overlap.
In this case, all you really need to know is if there's a non-zero value[1] after you've bitmasked.
[1] See Jaime's comment. If we were authentically bitmasking, we'd only need to check that the result was positive. But since
enum
s can be negative, even, strangely, when combined with the[Flags]
attribute, it's defensive to code for!= 0
rather than> 0
.
Building off of @andnil's setup...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BitFlagPlay
{
class Program
{
[Flags]
public enum MyColor
{
Yellow = 0x01,
Green = 0x02,
Red = 0x04,
Blue = 0x08
}
static void Main(string[] args)
{
var myColor = MyColor.Yellow | MyColor.Blue;
var acceptableColors = MyColor.Yellow | MyColor.Red;
Console.WriteLine((myColor & MyColor.Blue) != 0); // True
Console.WriteLine((myColor & MyColor.Red) != 0); // False
Console.WriteLine((myColor & acceptableColors) != 0); // True
// ... though only Yellow is shared.
Console.WriteLine((myColor & MyColor.Green) != 0); // Wait a minute... ;^D
Console.Read();
}
}
}
Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
If the indices match then:
df['B'] = df1['E']
should work otherwise:
df['B'] = df1['E'].values
will work so long as the length of the elements matches
The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this
For Ubuntu users, an answer can be found here. I also quote it:
The most probable cause, is that you have not installed the appropriate dependencies. Your Ubuntu system has to have some packages installed regarding conversion of LaTeX and XeTeX files, in order to save your notebook as PDF. You can install them by:
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc
Also,
nbconvert
is another dependency that is usually automatically installed with jupyter. But you can install it just to be sure, while having your virtual environment activated:pip install -U nbconvert
I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.
and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.
GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.
Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...
I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.
The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.