I think the best way to do this is to use event.preventDefault()
because if some exception is raised in the handler, then the return false
statement will be skipped and the behavior will be opposite to what you want.
But if you are sure that the code won't trigger any exceptions, then you can go with any of the method you wish.
If you still want to go with the return false
, then you can put your entire handler code in a try catch block like below:
$('a').click(function (e) {
try{
your code here.........
}
catch(e){}
return false;
});
$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));
$('#checkbox1').change(function() {
$('#textbox1').val($(this).is(':checked'));
});
$('#checkbox1').click(function() {
if (!$(this).is(':checked')) {
if(!confirm("Are you sure?"))
{
$("#checkbox1").prop("checked", true);
$('#textbox1').val($(this).is(':checked'));
}
}
});
});
As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.
Consider the use case where your lambdas instead of being apply, is stored in some place and run later.
I remember that in Smalltalk you would get an illegal store raised when you do such modification.
FYI, sender
and e
are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
I came accross very intuitive explanation at this webpage http://doandroids.com/blogs/tag/codeexample/. Taken from there:
- boolean onTouchEvent(MotionEvent ev) - called whenever a touch event with this View as target is detected
- boolean onInterceptTouchEvent(MotionEvent ev) - called whenever a touch event is detected with this ViewGroup or a child of it as target. If this function returns true, the MotionEvent will be intercepted, meaning it will be not be passed on to the child, but rather to the onTouchEvent of this View.
The event must be cancelable
. Adding an if
statement solves this issue.
if (e.cancelable) {
e.preventDefault();
}
In your code you should put it here:
if (this.isSwipe(swipeThreshold) && e.cancelable) {
e.preventDefault();
e.stopPropagation();
swiping = true;
}
I just needed a simple testing button for react.js. Here is what I did and it worked.
function Testing(){
var f=function testing(){
console.log("Testing Mode activated");
UserData.authenticated=true;
UserData.userId='123';
};
console.log("Testing Mode");
return (<div><button onClick={f}>testing</button></div>);
}
You can call the btnTest_Click just like any other function.
The most basic form would be this:
btnTest_Click(this, null);
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
pause();
return 0;
}
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
What if onclick event is not directly on element, but from parent element? This should work:
$(".noclick").attr('onclick','').unbind('click');
$(".noclick").click(function(e){
e.preventDefault();
e.stopPropagation();
return false;
});
I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange=""
attribute to the input tag:
<input type='file' onchange='getFilename(this)'/>
function getFileName(elm) {
var fn = $(elm).val();
....
}
EDIT:
function getFileName(elm) {
var fn = $(elm).val();
var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
alert(filename);
}
Let's start by describing DOM elements' event handling.
First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element
interface. For the purpose of assigning event handlers, Element.addListener
and Element.on
(these are equivalent) were created. So, for example, if we have html:
<div id="test_node"></div>
and we want add click
event handler.
Let's retrieve Element
:
var el = Ext.get('test_node');
Now let's check docs for click
event. It's handler may have three parameters:
click( Ext.EventObject e, HTMLElement t, Object eOpts )
Knowing all this stuff we can assign handler:
// event name event handler
el.on( 'click' , function(e, t, eOpts){
// handling event here
});
Widgets event handling is pretty much similar to DOM nodes event handling.
First of all, widgets event handling is realized by utilizing Ext.util.Observable
mixin. In order to handle events properly your widget must containg Ext.util.Observable
as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable
as a mixin by default.
For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener
). Let's for example create Button
widget and assign click
event to it. First of all you should check event's docs for handler's arguments:
click( Ext.button.Button this, Event e, Object eOpts )
Now let's use on
:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
});
The second way is to use widget's listeners config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
listeners : {
click: function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
}
});
Notice that Button
widget is a special kind of widgets. Click event can be assigned to this widget by using handler
config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
handler : function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
});
First of all you need to register an event using addEvents method:
myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
Using the addEvents
method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.
To fire your event use fireEvent method:
myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);
arg1, arg2, arg3, /* ... */
will be passed into handler. Now we can handle your event:
myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
// event handling here
console.log(arg1, arg2, arg3, /* ... */);
});
It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent
method when you are defining new widget:
Ext.define('MyCustomButton', {
extend: 'Ext.button.Button',
// ... other configs,
initComponent: function(){
this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
// ...
this.callParent(arguments);
}
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });
To prevent bubbling you can return false
or use Ext.EventObject.preventDefault()
. In order to prevent browser's default action use Ext.EventObject.stopPropagation()
.
For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:
myButton.on('click', function(btn, e){
if (e.button !== 0)
e.preventDefault();
});
In Chrome, window.onload is different from <body onload="">
, whereas they are the same in both Firefox(version 35.0) and IE (version 11).
You could explore that by the following snippet:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--import css here-->
<!--import js scripts here-->
<script language="javascript">
function bodyOnloadHandler() {
console.log("body onload");
}
window.onload = function(e) {
console.log("window loaded");
};
</script>
</head>
<body onload="bodyOnloadHandler()">
Page contents go here.
</body>
</html>
And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()
" in the consoles of IE & FF, you will see:
"function onload(event) { bodyOnloadHandler() }"
which means that the assignment "window.onload = function(e)..." is overwritten.
I recommand the following article : Hit Region Detection For HTML5 Canvas And How To Listen To Click Events On Canvas Shapes which goes through various situations.
However, it does not cover the addHitRegion
API, which must be the best way (using math functions and/or comparisons is quite error prone). This approach is detailed on developer.mozilla
XenElement's answer is spot on.
The above can be done in interface builder too by right-clicking on the UITextField and dragging the "Editing Changed" send event to your subclass unit.
Suppose that you have two handlers, f and g, and want to make sure that they are executed in a known and fixed order, then just encapsulate them:
$("...").click(function(event){
f(event);
g(event);
});
In this way there is (from the perspective of jQuery) only one handler, which calls f and g in the specified order.
element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();
HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};
HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
for (var i = 0; i < this.myListeners.length; i++) {
this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
};
delete this.myListeners;
};
};
in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:
<item
android:id="@+id/OK_MENU_ITEM"
android:onClick="showMsgDirectMenuXml" />
And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:
private void showMsgDirectMenuXml(MenuItem item) {
Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
toast.show();
}
NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)
You may have a look at pymitter (pypi). Its a small single-file (~250 loc) approach "providing namespaces, wildcards and TTL".
Here's a basic example:
from pymitter import EventEmitter
ee = EventEmitter()
# decorator usage
@ee.on("myevent")
def handler1(arg):
print "handler1 called with", arg
# callback usage
def handler2(arg):
print "handler2 called with", arg
ee.on("myotherevent", handler2)
# emit
ee.emit("myevent", "foo")
# -> "handler1 called with foo"
ee.emit("myotherevent", "bar")
# -> "handler2 called with bar"
The easier one for newbies:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.
When clicking Button1
on the UserControl, i'll fire Button1_Click
which triggers UserControl_ButtonClick
on the form:
User control:
[Browsable(true)] [Category("Action")]
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;
protected void Button1_Click(object sender, EventArgs e)
{
//bubble the event up to the parent
if (this.ButtonClick!= null)
this.ButtonClick(this, e);
}
Form:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);
protected void UserControl_ButtonClick(object sender, EventArgs e)
{
//handle the event
}
Notes:
Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e);
you can use ButtonClick?.Invoke(this, e);
, which does essentially the same, but is shorter.
The Browsable
attribute makes the event visible in Visual Studio's designer (events view), Category
shows it in the "Action" category, and Description
provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.
Between the deprecation of mutation events and the emergence of MutationObserver
, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.
To quote the blog post:
Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for.
I used a relatively benign and little used css property, clipI used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.
So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.
Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.
function setUserID(myValue) {
$('#userid').val(myValue)
.trigger('change');
}
Once that's the case,
$('#userid').change(function(){
//fire your ajax call
})
should work as expected.
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
There's a couple of ways you can do this. If the onchange
listener is a function set via the element.onchange
property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:
element.onchange();
If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener
/attachEvent
, you need to do a bit of feature detection to correctly fire the event:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
Best and most generic way to control the music is to create a mother Activity in which you override startActivity(Intent intent)
- in it you put shouldPlay=true
,
and onBackPressed()
- in it you put shouldPlay = true
.
onStop
- in it you put a conditional mediaPlayer.stop with shouldPlay as condition
Then, just extend the mother activity to all other activities, and no code duplicating is needed.
Try the below code:
<script type="text/javascript">
$(document).ready(function () {
$(".ratingButtons").buttonset();
});
</script>
<asp:RadioButtonList ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server"
AutoPostBack="True" DataSourceID="SqlDataSourceSizes" DataTextField="ProdSize"
CssClass="ratingButtons" DataValueField="_ProdSizeID" Font-Size="X-Small"
ForeColor="#666666">
</asp:RadioButtonList>
I spent few hours resolving the problem of detecting autofill inputs on first page load (without any user action taken) and found ideal solution that works on Chrome, Opera, Edge and on FF too!!
by searching elements with pseudoclass input:-webkit-autofill
and doing desired actions (in my case i was changing input wrapper class to change label positions with float label pattern).
becouse FF does not have such pseudoclass or similar class (as many suggest ":-moz-autofill") that is visible by simply searching DOM. You also can't find the yellow background of input. The only cause is that browser adds this yellow color by changing filter property:
input:-moz-autofill, input:-moz-autofill-preview { filter: grayscale(21%) brightness(88%) contrast(161%) invert(10%) sepia(40%) saturate(206%); }
So in case of Firefox You must first search all inputs and get its computed style and then compare to this filter style hardcoded in browser settings. I really dunno why they didnt use simply background color but that strange filter!? They making lifes harder ;)
Here is my code working like a charm at my website (https://my.oodo.pl/en/modules/register/login.php):
<script type="text/javascript">
/*
* this is my main function
*/
var checkAutoFill = function(){
/*first we detect if we have FF or other browsers*/
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (!isFirefox) {
$('input:-webkit-autofill').each(function(){
/*here i have code that adds "focused" class to my input wrapper and changes
info instatus div. U can do what u want*/
$(this).closest('.field-wrapper').addClass('focused');
document.getElementById("status").innerHTML = "Your browser autofilled form";
});
}
if (isFirefox) {
$('input').each(function(){
var bckgrnd = window.getComputedStyle(document.getElementById(this.id), null).getPropertyValue("filter");
if (bckgrnd === 'grayscale(0.21) brightness(0.88) contrast(1.61) invert(0.1) sepia(0.4) saturate(2.06)') {
/*if our input has that filter property customized by browserr with yellow background i do as above (change input wrapper class and change status info. U can add your code here)*/
$(this).closest('.field-wrapper').addClass('focused');
document.getElementById("status").innerHTML = "Your Browser autofilled form";
}
})
}
}
/*im runing that function at load time and two times more at 0.5s and 1s delay because not all browsers apply that style imediately (Opera does after ~300ms and so Edge, Chrome is fastest and do it at first function run)*/
checkAutoFill();
setTimeout(function(){
checkAutoFill();
}, 500);
setTimeout(function(){
checkAutoFill();
}, 1000);
})
</script>
I edited above code manually here to throw out some trash not important for You. If its not working for u, than paste into Your IDE and double check the syntax ;) Of course add some debuging alerts or console logs and customize.
Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.
Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.
// sample C#
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 50; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(50);
foo.Width = sizeValue;
foo.Height = sizeValue;
foo.Name = "button" + i;
xPos = ranNum.Next(300);
yPos = ranNum.Next(200);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}
$( "button" ).on( "click", function(event) {_x000D_
_x000D_
alert( $( this ).html() );_x000D_
console.log( event.target );_x000D_
_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<button>test 1</button>_x000D_
<button>test 2</button>
_x000D_
Try this one:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
return false;
});
Since inline events are executed as functions you can simply use arguments.
<p id="p" onclick="doSomething.apply(this, arguments)">
and
function doSomething(e) {
if (!e) e = window.event;
// 'e' is the event.
// 'this' is the P element
}
The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.
I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").
I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:
public class SeleccionListener implements ActionListener, FocusListener {}
So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
System.out.println("Aceptar pressed");
}
In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).
public void focusGained(FocusEvent focusEvent) {
if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
System.out.println("Data radio button");
}
In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)
Check this code. It awesome code for hide div using select item.
HTML
<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
<option value="1">YES</option>
<option value="2">NO</option>
</select>
<div id="div1" style="display:block;">
<input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
<input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
<input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
<input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
<datalist id="cars">
<option>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
<option>Value 4</option>
</datalist>
</div>
JS
<script>
function showDiv(prefix,chooser)
{
for(var i=0;i<chooser.options.length;i++)
{
var div = document.getElementById(prefix+chooser.options[i].value);
div.style.display = 'none';
}
var selectedOption = (chooser.options[chooser.selectedIndex].value);
if(selectedOption == "1")
{
displayDiv(prefix,"1");
}
if(selectedOption == "2")
{
displayDiv(prefix,"2");
}
}
function displayDiv(prefix,suffix)
{
var div = document.getElementById(prefix+suffix);
div.style.display = 'block';
}
</script>
Timer.Elapsed
expects method of specific signature (with arguments object
and EventArgs
). If you want to use your PlayMusicEvent
method with additional argument evaluated during event registration, you can use lambda expression as an adapter:
myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));
Edit: you can also use shorter version:
myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);
You need MouseClick
instead of Click
event handler, reference.
switch (e.Button) {
case MouseButtons.Left:
// Left click
break;
case MouseButtons.Right:
// Right click
break;
...
}
Wrap the textbox inside asp:Panel
tags
Hide a Button that has a click event that does what you want done and give the <asp:panel>
a DefaultButton
Attribute with the ID of the Hidden Button.
<asp:Panel runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" OnClick="Button1_Click" />
</asp:Panel>
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
This will give you some control over the clicking, and looks tidy
<script>
var timeOut = 0;
function onClick(but)
{
//code
clearTimeout(timeOut);
timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>
See How to find event listeners on a DOM node.
In a nutshell, assuming at some point an event handler is attached to your element (eg): $('#foo').click(function() { console.log('clicked!') });
You inspect it like so:
jQuery 1.3.x
var clickEvents = $('#foo').data("events").click;
jQuery.each(clickEvents, function(key, value) {
console.log(value) // prints "function() { console.log('clicked!') }"
})
jQuery 1.4.x
var clickEvents = $('#foo').data("events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
})
See jQuery.fn.data
(where jQuery stores your handler internally).
jQuery 1.8.x
var clickEvents = $._data($('#foo')[0], "events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
})
If you're using JQuery you can do:
$('#elementid').click();
this
inside of doThings
is the window object. Try this instead:
var doThings = function (element) {
var eventHandler = function(ev, func){
if (element[ev] == undefined) {
return;
}
element[ev] = function(e){
func(e, element);
}
};
return {
eventHandler: eventHandler
};
};
A simple method involves using the get and set functions on the variable
using System;
public string Name{
get{
return name;
}
set{
name= value;
OnVarChange?.Invoke();
}
}
private string name;
public event System.Action OnVarChange;
If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.
you can use key to reload child component using key
<component :is="child1" :filter="filter" :key="componentKey"></component>
If you want to reload component with new filter, if button click filter the child component
reloadData() {
this.filter = ['filter1','filter2']
this.componentKey += 1;
},
and use the filter to trigger the function
Try this "html-approach" which is acceptable for small JS projects
function msg(animal,is) {
console.log(animal, is.checked); // Do stuff
}
_x000D_
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
_x000D_
I recently made an example of how to use events in c#, and posted it on my blog. I tried to make it as clear as possible, with a very simple example. In case it might help anyone, here it is: http://www.konsfik.com/using-events-in-csharp/
It includes description and source code (with lots of comments), and it mainly focuses on a proper (template - like) usage of events and event handlers.
Some key points are:
Events are like "sub - types of delegates", only more constrained (in a good way). In fact an event's declaration always includes a delegate (EventHandlers are a type of delegate).
Event Handlers are specific types of delegates (you may think of them as a template), which force the user to create events which have a specific "signature". The signature is of the format: (object sender, EventArgs eventarguments).
You may create your own sub-class of EventArgs, in order to include any type of information the event needs to convey. It is not necessary to use EventHandlers when using events. You may completely skip them and use your own kind of delegate in their place.
One key difference between using events and delegates, is that events can only be invoked from within the class that they were declared in, even though they may be declared as public. This is a very important distinction, because it allows your events to be exposed so that they are "connected" to external methods, while at the same time they are protected from "external misuse".
I just tried out your build.gradle
and it worked fine for me to import GMS, so that's not the issue.
This was with Google Play services (rev 13)
and Google Repository (rev 4)
. Check out those are installed one more time :)
As Get-Date
returns a DateTime object you are able to compare them directly. An example:
(get-date 2010-01-02) -lt (get-date 2010-01-01)
will return false.
If you'd like to do it for all dialogs throughout the site try the following code...
$.extend( $.ui.dialog.prototype.options, {
open: function() {
var dialog = this;
$('.ui-widget-overlay').bind('click', function() {
$(dialog).dialog('close');
});
}
});
I feel like all that was wrong here was the order, Selçuklu wanted the app to wait for a second before filling in the grid, so the Sleep command should have come before the fill command.
System.Threading.Thread.Sleep(1000);
dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
To make sure you're always on the safe side, without getting all kinds of unwanted code insertion use FILTERS:
echo filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);
More reading on php.net function filter_input, or check out the description of the different filters
I wrote the following Bash script to get a table of IP addresses from all containers running under docker-compose
.
function docker_container_names() {
docker ps -a --format "{{.Names}}" | xargs
}
# Get the IP address of a particular container
dip() {
local network
network='YOUR-NETWORK-HERE'
docker inspect --format "{{ .NetworkSettings.Networks.$network.IPAddress }}" "$@"
}
dipall() {
for container_name in $(docker_container_names);
do
local container_ip=$(dip $container_name)
if [[ -n "$container_ip" ]]; then
echo $(dip $container_name) " $container_name"
fi
done | sort -t . -k 3,3n -k 4,4n
}
You should change the variable network to your own network name.
You can use span
elements instead of the br
if you want the white space method to work, as it depends on pseudo-elements which are "not defined" for replaced elements.
HTML
<p>
To break lines<span class="line-break">in a paragraph,</span><span>don't use</span><span>the 'br' element.</span>
</p>
CSS
span {white-space: pre;}
span:after {content: ' ';}
span.line-break {display: block;}
span.line-break:after {content: none;}
The line break is simply achieved by setting the appropriate span element to display:block
.
By using IDs and/ or Classes in your HTML markup you can easily target every single or combination of span elements by CSS or use CSS selectors like nth-child()
.
So you can e.g. define different break points by using media queries for a responsive layout.
And you can also simply add/ remove/ toggle classes by Javascript (jQuery).
The "advantage" of this method is its robustness - works in every browser that supports pseudo-elements (see: Can I use - CSS Generated content).
As an alternative it is also possible to add a line break via pseudo-elements:
span.break:before {
content: "\A";
white-space: pre;
}
I had a similar problem which was caused by a simple mistake in CSS comments.
I had written a comment using the JavaScript // way instead of /* */ which made the subsequent css-class to break but all other CSS work as expected.
Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.
On the server side: -
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
Using Javascript
var ip = $get("uip").innerHTML;
I am using ASP.Net Ajax, but you can use getElementById instead of $get().
What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.
This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).
Cheers!
Just return any kind of list. ArrayList will be fine, its not static.
ArrayList<yourClass> list = new ArrayList<yourClass>();
for (yourClass item : yourArray)
{
list.add(item);
}
GitHub help page for this issue: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/
i have this error when using "--ui tdd". remove this or using "--ui bdd" fix problem.
Your url String needs variable markers for the map you pass to work, like:
String url = "https://app.example.com/hr/email?{email}";
Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:
String url = "https://app.example.com/hr/[email protected]";
You can go to app/Providers/AppServiceProvider.php
and import this
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
also in boot function add this
Schema::defaultStringLength(191);
There is some confusion when using pip install
in Windows. The instructions talk about a specific folder which has youtube-dl.exe
. There is no such folder if you use pip install
.
The solution is to:
bin
folder (there are three exe files) in any folder which is a path
in Windows. I personally use Ananconda, so I placed them in /Anaconda/Scripts
, but you could place it in any folder and add that folder to the path.At first, I designed it to split strings into substrings to parse string containing hex.
Today I turned it into complex, but still simple generator.
def chunker(iterable, size, reductor, condition):
it = iter(iterable)
def chunk_generator():
return (next(it) for _ in range(size))
chunk = reductor(chunk_generator())
while condition(chunk):
yield chunk
chunk = reductor(chunk_generator())
iterable
is any iterable / iterator / generator containg / generating / iterating over input data,size
is, of course, size of chunk you want get,reductor
is a callable, which receives generator iterating over content of chunk.
I'd expect it to return sequence or string, but I don't demand that.
You can pass as this argument for example list
, tuple
, set
, frozenset
,
or anything fancier. I'd pass this function, returning string
(provided that iterable
contains / generates / iterates over strings):
def concatenate(iterable):
return ''.join(iterable)
Note that reductor
can cause closing generator by raising exception.
condition
is a callable which receives anything what reductor
returned.
It decides to approve & yield it (by returning anything evaluating to True
),
or to decline it & finish generator's work (by returning anything other or raising exception).
When number of elements in iterable
is not divisible by size
, when it
gets exhausted, reductor
will receive generator generating less elements than size
.
Let's call these elements lasts elements.
I invited two functions to pass as this argument:
lambda x:x
- the lasts elements will be yielded.
lambda x: len(x)==<size>
- the lasts elements will be rejected.
replace <size>
using number equal to size
This code should work properly to get the current date from the calendar.
String today=getCurrentDay(); //function
driver.findElement(By.xpath("here xpath of textbox")).click();
Thread.sleep(5000);
WebElement dateWidgetForm= driver.findElement(By.xpath("here xpath of calender"));
List<WebElement> columns = dateWidgetForm.findElements(By.tagName("td"));
for (WebElement cell: columns) {
String z=cell.getAttribute("class").toString();
if(z.equalsIgnoreCase("day")){
if (cell.getText().equals(today)) {
cell.click();
break;
}
}
private String getCurrentDay() {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
//Get Current Day as a number
int todayInt = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("Today Int: " + todayInt +"\n");
//Integer to String Conversion
String todayStr = Integer.toString(todayInt);
return todayStr;
}
{{p.User['first_name'] or 'My default string'}}
I have created a JSFiddle with my bindHTML knockout binding handler here: https://jsfiddle.net/glaivier/9859uq8t/
First, save the binding handler into its own (or a common) file and include after Knockout.
If you use this switch your bindings to this:
<div data-bind="bindHTML: htmlValue"></div>
OR
<!-- ko bindHTML: htmlValue --><!-- /ko -->
Used implementation 'androidx.appcompat:appcompat:1.1.2' in App gradle fixed the issue for me
/usr/bin/
/usr/bin/wkhtmltopdf
wkhtmltopdf http://www.google.com test.pdf
hint: detail information from this linktry this solution for me its working
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext
(DBHelper.GetConnectionString()))
{
return (from pro in db.Projects
select new { query }.query).ToList();
}
}
I know this is really old, but if you are copying and pasting anyway, you can just use:
read.csv(readClipboard())
readClipboard() escapes the back-slashes for you. Just remember to make sure the ".csv" is included in your copy, perhaps with this:
read.csv(paste0(readClipboard(),'.csv'))
And if you really want to minimize your typing you can use some functions:
setWD <- function(){
setwd(readClipboard())
}
readCSV <- function(){
return(readr::read_csv(paste0(readClipboard(),'.csv')))
}
#copy directory path
setWD()
#copy file name
df <- readCSV()
Note: if you already in a thread, you have to make a new post thread, or it's not scroll new long height till the full end (for me). For ex:
void LogMe(final String s){
runOnUiThread(new Runnable() {
public void run() {
connectionLog.setText(connectionLog.getText() + "\n" + s);
final ScrollView sv = (ScrollView)connectLayout.findViewById(R.id.scrollView);
sv.post(new Runnable() {
public void run() {
sv.fullScroll(sv.FOCUS_DOWN);
/*
sv.scrollTo(0,sv.getBottom());
sv.scrollBy(0,sv.getHeight());*/
}
});
}
});
}
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
Have a look at override_function
to override the functions.
override_function — Overrides built-in functions
Example:
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
What you are describing is actually what FontAwesome is doing already. They apply the FontAwesome font-family to the ::before
pseudo element of any element that has a class that starts with "icon-".
[class^="icon-"]:before,
[class*=" icon-"]:before {
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
display: inline-block;
text-decoration: inherit;
}
Then they use the pseudo element ::before
to place the icon in the element with the class. I just went to http://fortawesome.github.com/Font-Awesome/ and inspected the code to find this:
.icon-cut:before {
content: "\f0c4";
}
So if you are looking to add the icon again, you could use the ::after
element to achieve this. Or for your second part of your question, you could use the ::after
pseudo element to insert the bullet character to look like a list item. Then use absolute positioning to place it to the left, or something similar.
i:after{ content: '\2022';}
If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date
constructor is not supported pre IE9:
var queryDate = '2009-11-01',
dateParts = queryDate.match(/(\d+)/g)
realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
// months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');
$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);
Check the above example here.
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
I was struggling with this - you can style the background of the dialog using android:alertDialogStyle="@style/AlertDialog"
in your theme, but it ignores any text settings you have. As @rflexor said above it cannot be done with the SDK prior to Honeycomb (well you could use Reflection
).
My solution, in a nutshell, was to style the background of the dialog using the above, then set a custom title and content view (using layouts that are the same as those in the SDK).
My wrapper:
import com.mypackage.R;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAlertDialogBuilder extends AlertDialog.Builder {
private final Context mContext;
private TextView mTitle;
private ImageView mIcon;
private TextView mMessage;
public CustomAlertDialogBuilder(Context context) {
super(context);
mContext = context;
View customTitle = View.inflate(mContext, R.layout.alert_dialog_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);
View customMessage = View.inflate(mContext, R.layout.alert_dialog_message, null);
mMessage = (TextView) customMessage.findViewById(R.id.message);
setView(customMessage);
}
@Override
public CustomAlertDialogBuilder setTitle(int textResId) {
mTitle.setText(textResId);
return this;
}
@Override
public CustomAlertDialogBuilder setTitle(CharSequence text) {
mTitle.setText(text);
return this;
}
@Override
public CustomAlertDialogBuilder setMessage(int textResId) {
mMessage.setText(textResId);
return this;
}
@Override
public CustomAlertDialogBuilder setMessage(CharSequence text) {
mMessage.setText(text);
return this;
}
@Override
public CustomAlertDialogBuilder setIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}
@Override
public CustomAlertDialogBuilder setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}
}
alert_dialog_title.xml (taken from the SDK)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/title_template"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dip"
android:layout_marginBottom="9dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">
<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="6dip"
android:paddingRight="10dip"
android:src="@drawable/ic_dialog_alert" />
<TextView android:id="@+id/alertTitle"
style="@style/?android:attr/textAppearanceLarge"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView android:id="@+id/titleDivider"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
android:src="@drawable/divider_horizontal_bright" />
</LinearLayout>
alert_dialog_message.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="12dip"
android:paddingLeft="14dip"
android:paddingRight="10dip">
<TextView android:id="@+id/message"
style="?android:attr/textAppearanceMedium"
android:textColor="@color/dark_grey"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" />
</ScrollView>
Then just use CustomAlertDialogBuilder
instead of AlertDialog.Builder
to create your dialogs, and just call setTitle
and setMessage
as usual.
Change
if [ -s "p1"]; #line 13
into
if [ -s "p1" ]; #line 13
note the space.
When using moment.js, use:
var tz = moment.tz.guess();
It will return an IANA time zone identifier, such as America/Los_Angeles
for the US Pacific time zone.
It is documented here.
Internally, it first tries to get the time zone from the browser using the following call:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.
If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date
object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
This is not possible, it will give you a compile time error,
You can use array for this type of requirement .
For your Reference :
http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx
Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)
Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:
public ActionResult Index()
{
var xyzComponent = Request.Headers["xyzComponent"];
var model = new MyModel
{
IsCustomHeaderSet = (xyzComponent != null)
}
return View(model);
}
Quote from the Python 3 Reference:
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
As said in the reference, in case of several nested functions only variable in the nearest enclosing function is modified:
def outer():
def inner():
def innermost():
nonlocal x
x = 3
x = 2
innermost()
if x == 3: print('Inner x has been modified')
x = 1
inner()
if x == 3: print('Outer x has been modified')
x = 0
outer()
if x == 3: print('Global x has been modified')
# Inner x has been modified
The "nearest" variable can be several levels away:
def outer():
def inner():
def innermost():
nonlocal x
x = 3
innermost()
x = 1
inner()
if x == 3: print('Outer x has been modified')
x = 0
outer()
if x == 3: print('Global x has been modified')
# Outer x has been modified
But it cannot be a global variable:
def outer():
def inner():
def innermost():
nonlocal x
x = 3
innermost()
inner()
x = 0
outer()
if x == 3: print('Global x has been modified')
# SyntaxError: no binding for nonlocal 'x' found
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
To expand on the top-voted answer, for reference, if the you want to add more complex items to the array:
@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");
etc.
Furthermore, if you want to pass the array as a parameter to your controller, you can stringify it first:
myArray = JSON.stringify({ 'myArray': myArray });
Try this if you have only one Fragment
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//TODO: Your Code Here
}
Easy done:
(?<=\[)(.*?)(?=\])
Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:
Alternatively you can just capture what's between the square brackets:
\[(.*?)\]
and return the first captured group instead of the entire match.
Another approach is to not have the secret on the device in the first place! See Mobile API Security Techniques (especially part 3).
Using the time honored tradition of indirection, share the secret between your API endpoint and an app authentication service.
When your client wants to make an API call, it asks the app auth service to authenticate it (using strong remote attestation techniques), and it receives a time limited (usually JWT) token signed by the secret.
The token is sent with each API call where the endpoint can verify its signature before acting on the request.
The actual secret is never present on the device; in fact, the app never has any idea if it is valid or not, it juts requests authentication and passes on the resulting token. As a nice benefit from indirection, if you ever want to change the secret, you can do so without requiring users to update their installed apps.
So if you want to protect your secret, not having it in your app in the first place is a pretty good way to go.
if files are not moving this could be due to several reasons
> find * -type d -print0 | xargs -0 chmod 0755 # for directories find * > -type f -print0 | xargs -0 chmod 0666 # for files
chown -R admin:admin public_html # will restore permission to admin for folder and files within it chown admin:admin public_html # will restore permission to admin for folder only will skip files
copy
function instead of move_uploaded_file
Since Flask 0.10 you can`t add multiple routes to one endpoint. But you can add fake endpoint
@user.route('/<userId>')
def show(userId):
return show_with_username(userId)
@user.route('/<userId>/<username>')
def show_with_username(userId,username=None):
pass
To avoid this warning, do not use:
async: false
in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.
The default is
async: true
 
is the numeric reference for the entity reference
— they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.
See the Wikipedia page for the non-breaking space.
date = new DateTime(date.year, date.month, date.day, HH, MM, SS);
You have installed the Java Runtime Environment(JRE) but it doesn't contain javac.
So on the terminal get access to the root user sudo -i
and enter the password.
Type yum install java-devel
, hence it will install packages of javac in fedora.
On my WebMatrix IIS Express install changing from "*:80:localhost"
to "*:80:custom.hostname"
didn't work ("Bad Hostname", even with proper etc\hosts mappings), but "*:80:"
did work--and with none of the additional steps required by the other answers here. Note that "*:80:*"
won't do it; leave off the second asterisk.
In my Notepad++ 7.2.2
, the Preferences
section it's a bit different.
The option is located at: Settings
/ Preferences
/ Language
/ Replace by space
as in the Screenshot.
I prefer Google Collections over Apache StringUtils for this particular problem:
Joiner.on(separator).join(array)
Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g. null
elements may be skipped or replaced by a placeholder. Also, Joiner
has a feature for joining maps with a separator between key and value.
Swift3
You can use subscript syntax to access the Character at a particular String index.
let greeting = "Guten Tag!"
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index] // a
or we can do a String Extension in Swift 4
extension String {
func getCharAtIndex(_ index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
}
USAGE:
let foo = "ABC123"
foo.getCharAtIndex(2) //C
I recieved a similar error:
AttributeError: module 'pandas' has no attribute 'DataFrame'
The cause of my error was that I ran pip install of pandas as root, and my user did not have permission to the directory.
My fix was to run:
sudo chmod -R 755 /usr/local/lib/python3.6/site-packages
Kafka ships with some tools you can use to accomplish this.
List topics:
# ./bin/kafka-topics.sh --list --zookeeper localhost:2181
test_topic_1
test_topic_2
...
List partitions and offsets:
# ./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --broker-info --group test_group --topic test_topic --zookeeper localhost:2181
Group Topic Pid Offset logSize Lag Owner
test_group test_topic 0 698020 698021 1 test_group-0
test_group test_topic 1 235699 235699 0 test_group-1
test_group test_topic 2 117189 117189 0 test_group-2
If you're using the new apis, there's a new tool you can use: kafka-consumer-groups.sh
.
./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group count_errors --describe
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG OWNER
count_errors logs 2 2908278 2908278 0 consumer-1_/10.8.0.55
count_errors logs 3 2907501 2907501 0 consumer-1_/10.8.0.43
count_errors logs 4 2907541 2907541 0 consumer-1_/10.8.0.177
count_errors logs 1 2907499 2907499 0 consumer-1_/10.8.0.115
count_errors logs 0 2907469 2907469 0 consumer-1_/10.8.0.126
Use pickle, like this: import pickle
Your code would look like this:
import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
pickle.dump(mybytes, mypicklefile)
To read the data back, use the pickle.load method
I found formatting with colors a bit trickier as Confluence (5.6.3) is very fussy about spaces around the {{monospace}} blocks.
You can also relax your CSP for styles by adding style-src 'self' 'unsafe-inline';
"content_security_policy": "default-src 'self' style-src 'self' 'unsafe-inline';"
This will allow you to keep using inline style in your extension.
As others have pointed out, this is not recommended, and you should put all your CSS in a dedicated file. See the OWASP explanation on why CSS can be a vector for attacks (kudos to @ KayakinKoder for the link).
You can also propagate your static pain with lambdas, so the whole thing looks readable:
s.filter(a -> propagate(a::isActive))
propagate
here receives java.util.concurrent.Callable
as a parameter and converts any exception caught during the call into RuntimeException
. There is a similar conversion method Throwables#propagate(Throwable) in Guava.
This method seems being essential for lambda method chaining, so I hope one day it will be added to one of the popular libs or this propagating behavior would be by default.
public class PropagateExceptionsSample {
// a simplified version of Throwables#propagate
public static RuntimeException runtime(Throwable e) {
if (e instanceof RuntimeException) {
return (RuntimeException)e;
}
return new RuntimeException(e);
}
// this is a new one, n/a in public libs
// Callable just suits as a functional interface in JDK throwing Exception
public static <V> V propagate(Callable<V> callable){
try {
return callable.call();
} catch (Exception e) {
throw runtime(e);
}
}
public static void main(String[] args) {
class Account{
String name;
Account(String name) { this.name = name;}
public boolean isActive() throws IOException {
return name.startsWith("a");
}
}
List<Account> accounts = new ArrayList<>(Arrays.asList(new Account("andrey"), new Account("angela"), new Account("pamela")));
Stream<Account> s = accounts.stream();
s
.filter(a -> propagate(a::isActive))
.map(a -> a.name)
.forEach(System.out::println);
}
}
Actually, you can process the find
command output in a copy command in two ways:
If the find
command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:
Syntax:
find <Path> <Conditions> | xargs cp -t <copy file path>
Example:
find -mtime -1 -type f | xargs cp -t inner/
But our production data files might contain spaces, so most of time this command is effective:
Syntax:
find <path> <condition> -exec cp '{}' <copy path> \;
Example
find -mtime -1 -type f -exec cp '{}' inner/ \;
In the second example, the last part, the semi-colon is also considered as part of the find
command, and should be escaped before pressing Enter. Otherwise you will get an error something like:
find: missing argument to `-exec'
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
Php will evaluate what you wrote between the [] brackets.
$foo = array('eins', 'zwei', 'apples', 'oranges');
var_dump($foo[3-1]);
Will produce string(6) "apples"
, because it returns $foo[2].
If you want that as a string, put inverted commas around it.
Inspired by another answer here, I came up with the following all-POSIX solution. The general idea is to create an intermediate process between the parent and the child, that has one purpose: Notice when the parent dies, and explicitly kill the child.
This type of solution is useful when the code in the child can't be modified.
int p[2];
pipe(p);
pid_t child = fork();
if (child == 0) {
close(p[1]); // close write end of pipe
setpgid(0, 0); // prevent ^C in parent from stopping this process
child = fork();
if (child == 0) {
close(p[0]); // close read end of pipe (don't need it here)
exec(...child process here...);
exit(1);
}
read(p[0], 1); // returns when parent exits for any reason
kill(child, 9);
exit(1);
}
There are two small caveats with this method:
As an aside, the actual code I'm using is in Python. Here it is for completeness:
def run(*args):
(r, w) = os.pipe()
child = os.fork()
if child == 0:
os.close(w)
os.setpgid(0, 0)
child = os.fork()
if child == 0:
os.close(r)
os.execl(args[0], *args)
os._exit(1)
os.read(r, 1)
os.kill(child, 9)
os._exit(1)
os.close(r)
In python, when you have an iterable, usually you iterate without an index:
letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
print(l)
If you need to traverse the iterable in reverse order, you would do:
for l in letters[::-1]:
print(l)
When for any reason you need the index, you can use enumerate
:
for i, l in enumerate(letters, start=1): #start is 0 by default
print(i,l)
You can enumerate in reverse order too...
for i, l in enumerate(letters[::-1])
print(i,l)
ON ANOTHER NOTE...
Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map
:
If we need to capitilize each letter:
map(str.upper, letters)
Or get the Unicode code of each letter:
map(ord, letters)
I would recomnend using box-sizing
.
*{
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-ms-box-sizing:border-box;
box-sizing:border-box;
}
#bar{
border: 10px solid green;
}
I wrote this snippet, that I've been using for handling this exact case.
It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.
<script type='text/javascript'>
window.onhashchange=hashTriggerTab;
window.onload=hashTriggerTab;
function hashTriggerTab(){
var current_hash=window.location.hash;
if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
if(current_hash!=''){
var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
if(trigger)trigger.click();
}
}
</script>
With that in place, you could link both on the same page, like:
<a href='#tabId'>Link Any Tab</a>
Or from external page like:
<a href='newpage.php#tabId'>Link From External</a>
I have this issue in SOAP-UI and no one solution above dont helped me.
Proper solution for me was to add
-Dsoapui.sslcontext.algorithm=TLSv1
in vmoptions file (in my case it was ...\SoapUI-5.4.0\bin\SoapUI-5.4.0.vmoptions)
I have a more useful version if you are interested. I lifted a bit of code from here a website where the link is no longer active. I modifyied it to allow for an array of tables into the stored procedure and it populates the drop, truncate, add statements before executing all of them. This gives you control to decide which tables need truncating.
/****** Object: UserDefinedTableType [util].[typ_objects_for_managing] Script Date: 03/04/2016 16:42:55 ******/
CREATE TYPE [util].[typ_objects_for_managing] AS TABLE(
[schema] [sysname] NOT NULL,
[object] [sysname] NOT NULL
)
GO
create procedure [util].[truncate_table_with_constraints]
@objects_for_managing util.typ_objects_for_managing readonly
--@schema sysname
--,@table sysname
as
--select
-- @table = 'TABLE',
-- @schema = 'SCHEMA'
declare @exec_table as table (ordinal int identity (1,1), statement nvarchar(4000), primary key (ordinal));
--print '/*Drop Foreign Key Statements for ['+@schema+'].['+@table+']*/'
insert into @exec_table (statement)
select
'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+ o.name+'] DROP CONSTRAINT ['+fk.name+']'
from sys.foreign_keys fk
inner join sys.objects o
on fk.parent_object_id = o.object_id
where
exists (
select * from @objects_for_managing chk
where
chk.[schema] = SCHEMA_NAME(o.schema_id)
and
chk.[object] = o.name
)
;
--o.name = @table and
--SCHEMA_NAME(o.schema_id) = @schema
insert into @exec_table (statement)
select
'TRUNCATE TABLE ' + src.[schema] + '.' + src.[object]
from @objects_for_managing src
;
--print '/*Create Foreign Key Statements for ['+@schema+'].['+@table+']*/'
insert into @exec_table (statement)
select 'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+o.name+'] ADD CONSTRAINT ['+fk.name+'] FOREIGN KEY (['+c.name+'])
REFERENCES ['+SCHEMA_NAME(refob.schema_id)+'].['+refob.name+'](['+refcol.name+'])'
from sys.foreign_key_columns fkc
inner join sys.foreign_keys fk
on fkc.constraint_object_id = fk.object_id
inner join sys.objects o
on fk.parent_object_id = o.object_id
inner join sys.columns c
on fkc.parent_column_id = c.column_id and
o.object_id = c.object_id
inner join sys.objects refob
on fkc.referenced_object_id = refob.object_id
inner join sys.columns refcol
on fkc.referenced_column_id = refcol.column_id and
fkc.referenced_object_id = refcol.object_id
where
exists (
select * from @objects_for_managing chk
where
chk.[schema] = SCHEMA_NAME(o.schema_id)
and
chk.[object] = o.name
)
;
--o.name = @table and
--SCHEMA_NAME(o.schema_id) = @schema
declare @looper int , @total_records int, @sql_exec nvarchar(4000)
select @looper = 1, @total_records = count(*) from @exec_table;
while @looper <= @total_records
begin
select @sql_exec = (select statement from @exec_table where ordinal =@looper)
exec sp_executesql @sql_exec
print @sql_exec
set @looper = @looper + 1
end
For mysql you have limit, you can fire query as :
SELECT * FROM table limit 100` -- get 1st 100 records
SELECT * FROM table limit 100, 200` -- get 200 records beginning with row 101
For Oracle you can use rownum
See mysql select syntax and usage for limit
here.
For SQLite, you have limit, offset
. I haven't used SQLite but I checked it on SQLite Documentation. Check example for SQLite here.
One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:
static String[] SENTENCE;
public static void main(String []args) throws Exception{
Scanner sentence = new Scanner(new File("assets/blah.txt"));
ArrayList<String> sentenceList = new ArrayList<String>();
while (sentence.hasNextLine())
{
sentenceList.add(sentence.nextLine());
}
sentence.close();
String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
// System.out.println(sentenceArray.length);
for (int r=0;r<sentenceArray.length;r++)
{
SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array
for (int i=0;i<SENTENCE.length;i++)
{
System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
}
}
}
I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:
action="javascript:checkout()"
You try this?
Don't forget include the script reference in the html head.
I don't know cause of that works in firefox. Regards.
It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);
The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).
For example, consider the set {30, 30, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.
the solution what I found to work in my case
$('#multiselect1').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
maxHeight: '300',
buttonWidth: '235',
onChange: function(element, checked) {
var brands = $('#multiselect1 option:selected');
var selected = [];
$(brands).each(function(index, brand){
selected.push([$(this).val()]);
});
console.log(selected);
}
});
It will become easy to store files after converting in string you just have to convert string in image in your frontend
convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder
"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")
to delete the file
let resultHandler = function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}
fs.unlink(req.file.path, resultHandler);
at your routes import multer
`multer const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });`
Add upload.single('img') in your request
router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]),
upload.single('img'), usersController.fellowsdetails);
OR
If you want save images in localstorage
and want save path in database you can try following approach
you have to install first the fs-extra which will create folder. I am creating separate folders by id's if you want to remove it you can remove it. and to save path of image where it is uploaded add this code in your api or controller you are using to save image and and add it in database with other data
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
create separate folder for multer
like multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.array('images', 100);
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
In your routes import multerhelper
file
const multerHelper = require("../helpers/multer_helper");
router.post(multerHelper. createUserImage , function(req, res, next) {
//Here accessing the body datas.
})
Note that if you want to comment out a single line of printing erb you should do like this
<%#= ["Buck", "Papandreou"].join(" you ") %>
1) It is the only difference in C++.
2) POD: plain old data Other classes -> not POD
Following is how you can do it using java client.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;
public class AmazonS3Service {
private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
private static final String S3_SECRET_KEY = "SECRET_KEY";
private static final String S3_ENDPOINT = "S3_URL";
private AmazonS3 amazonS3;
public AmazonS3Service() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProtocol(Protocol.HTTPS);
clientConfiguration.setSignerOverride("S3SignerType");
BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
.withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
}
public int countObjects(String bucketName) {
int count = 0;
ObjectListing objectListing = amazonS3.listObjects(bucketName);
int currentBatchCount = objectListing.getObjectSummaries().size();
while (currentBatchCount != 0) {
count += currentBatchCount;
objectListing = amazonS3.listNextBatchOfObjects(objectListing);
currentBatchCount = objectListing.getObjectSummaries().size();
}
return count;
}
}
I believe that a much more reliable way to detect mobile devices is to look at the navigator.userAgent string. For example, on my iPhone the user agent string is:
Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1
Note that this string contains two telltale keywords: iPhone and Mobile. Other user agent strings for devices that I don't have are provided at:
https://deviceatlas.com/blog/list-of-user-agent-strings
Using this string, I set a JavaScript Boolean variable bMobile on my website to either true or false using the following code:
var bMobile = // will be true if running on a mobile device
navigator.userAgent.indexOf( "Mobile" ) !== -1 ||
navigator.userAgent.indexOf( "iPhone" ) !== -1 ||
navigator.userAgent.indexOf( "Android" ) !== -1 ||
navigator.userAgent.indexOf( "Windows Phone" ) !== -1 ;
After going back into the installer & checking off "Management Tools", ssms.exe was available under "C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio" (thanks to everyone for pointing out where to find it).
I've got a simple method without splitting:
a = "Lorem Ipsum Darum Diesrum!"
while True:
count = a.find(" ")
if count > 0:
a = a.replace(" ", " ")
count = a.find(" ")
continue
else:
break
print(a)
Dart Object
type has a runtimeType
instance member (source is from dart-sdk
v1.14, don't know if it was available earlier)
class Object {
//...
external Type get runtimeType;
}
Usage:
Object o = 'foo';
assert(o.runtimeType == String);
Without any assumptions the answer is:
{% if var is null %}
But this will be true only if var
is exactly NULL
, and not any other value that evaluates to false
(such as zero, empty string and empty array). Besides, it will cause an error if var
is not defined. A safer way would be:
{% if var is not defined or var is null %}
which can be shortened to:
{% if var|default is null %}
If you don't provide an argument to the default
filter, it assumes NULL
(sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):
{% if var|default is empty %}
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;
You can try this
Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
IntPtr pFoundWindow = p.MainWindowHandle;
// Do something with the handle...
//
}
As Filburt says; but also note that it's usually better to write
test="not(Count = 'N/A')"
If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.
6 YEARS LATER
Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.
The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.
In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA")
returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA"
returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA")
is the appropriate formulation.
I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:
in html code:
<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>
The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.
in css code:
/* h6: set presentation of images */
h6
{
font-family: "Franklin Gothic Demi", serif;
font-size: 1.0em;
font-weight: normal;
line-height: 1.25em;
text-align: center;
}
The text items set the look of the caption text, and the text-align property centers both the images and the caption text.
Use a special character \b
, which matches empty string at the beginning or at the end of a word:
print re.sub(r'\b[uU]\b', 'you', text)
spaces are not a reliable solution because there are also plenty of other punctuation marks, so an abstract character \b
was invented to indicate a word's beginning or end.
I just had this issue.. I just added the MinGW\bin directory to the path environment variable, and it solved the issue.
Right click-> generate getters and setters does the job well but if you want to create a keyboard shortcut in eclipse in windows, you can follow the following steps:
Hope this helps!
If the variable is declared (either with the var
keyword, as a function argument, or as a global variable), I think the best way to do it is:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
Otherwise, you'll have to use typeof
to avoid a ReferenceError
.
If you expect undefined to be redefined, you could wrap your code like this:
(function(undefined){
// undefined is now what it's supposed to be
})();
Or obtain it via the void
operator:
const undefined = void 0;
// also safe
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
There are loads of ways to do this, but by far the neatest is surely using [NSPredicate predicateWithBlock:]
:
NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
return [object shouldIKeepYou]; // Return YES for each object you want in filteredArray.
}]];
I think that's about as concise as it gets.
For those working with NSArray
s in Swift, you may prefer this even more concise version:
let filteredArray = array.filter { $0.shouldIKeepYou() }
filter
is just a method on Array
(NSArray
is implicitly bridged to Swift’s Array
). It takes one argument: a closure that takes one object in the array and returns a Bool
. In your closure, just return true
for any objects you want in the filtered array.
Create a button with an id share and add the following code snippet.
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Your body here";
String shareSub = "Your subject here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
});
The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
I found too simple hack just do this add new element in AndroidManifest
as:-
<activity android:name=".activityName"
android:label="@string/app_name"
android:noHistory="true"/>
the android:noHistory
will clear your unwanted activity from Stack.
// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:
from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
TypeScript solution:
function pick<T extends object, U extends keyof T>(
obj: T,
paths: Array<U>
): Pick<T, U> {
const ret = Object.create(null);
for (const k of paths) {
ret[k] = obj[k];
}
return ret;
}
The typing information even allows for auto-completion:
Credit to DefinitelyTyped for U extends keyof T
trick!
Your array has default keys(0,1) which store object {'com':'some thing'}
use:
var obj = jQuery.parseJSON(response);
$.each(obj, function(key,value) {
alert(value.com);
});
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
document.getElementById("myBtn").style.display = "block";_x000D_
} else {_x000D_
document.getElementById("myBtn").style.display = "none";_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
_x000D_
$('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
font-size: 20px;_x000D_
}_x000D_
_x000D_
#myBtn {_x000D_
display: none;_x000D_
position: fixed;_x000D_
bottom: 20px;_x000D_
right: 30px;_x000D_
z-index: 99;_x000D_
font-size: 18px;_x000D_
border: none;_x000D_
outline: none;_x000D_
background-color: red;_x000D_
color: white;_x000D_
cursor: pointer;_x000D_
padding: 15px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
_x000D_
#myBtn:hover {_x000D_
background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
Is there a name to describe this idiom?
In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.
I am assuming it is to prevent the possibly large overhead of copying a big complex object?
No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const
, then the class can change the state of an object that lives outside of it.
Is this generally good practice? Are there any pitfalls to this approach?
It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.
I've had the same problems including jpegs in LaTeX. The engine isn't really built to gather all the necessary size and scale information from JPGs. It is often better to take the JPEG and convert it into a PDF (on a mac) or EPS (on a PC). GraphicsConvertor on a mac will do that for you easily. Whereas a PDF includes DPI and size, a JPEG has only a size in terms of pixels.
( I know this is not the answer you wanted, but it's probably better to give them EPS/PDF that they can use than to worry about what happens when they try to scale your JPG).
You can use the ng-class
tag. Have a look http://jsfiddle.net/4WK7R/3/
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
The basic technique (on most modern systems) is to subtract the two numbers and then to check the sign bit of the result, i.e. see if the result is greater than/equal to/less than zero. In the assembly code instead of getting the result directly (into a register), you normally just branch depending on the state:
; Compare r1 and r2
CMP $r1, $r2
JLT lessthan
greater_or_equal:
; print "r1 >= r2" somehow
JMP l1
lessthan:
; print "r1 < r2" somehow
l1:
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
The idea that you hope to achieve can be made possible if you tweak the requirement a little bit
The below code is possible if your runtime supports the ES6 specification.
More about async functions
async function myAsynchronousCall(param1) {
// logic for myAsynchronous call
return d;
}
function doSomething() {
var data = await myAsynchronousCall(param1); //'blocks' here until the async call is finished
return data;
}
import java.lang.*;
import java.io.*;
class d2b
{
public static void main(String args[]) throws IOException{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal value:");
String h = b.readLine();
int k = Integer.parseInt(h);
String out = Integer.toBinaryString(k);
System.out.println("Binary: " + out);
}
}
With UpdateData As
(
SELECT RS_NOM,
ROW_NUMBER() OVER (ORDER BY [RS_NOM] DESC) AS RN
FROM DESTINATAIRE_TEMP
)
UPDATE DESTINATAIRE_TEMP SET CODE_DEST = RN
FROM DESTINATAIRE_TEMP
INNER JOIN UpdateData ON DESTINATAIRE_TEMP.RS_NOM = UpdateData.RS_NOM
You can 'extract' the language from the current locale. You can extract the locale via the standard Java API, or by using the Android Context. For instance, the two lines below are equivalent:
String locale = context.getResources().getConfiguration().locale.getDisplayName();
String locale = java.util.Locale.getDefault().getDisplayName();
You need to put the text-align:center
on the containing div, not on the input itself.
Repurposing the pdf2txt.py code that comes with pdfminer; you can make a function that will take a path to the pdf; optionally, an outtype (txt|html|xml|tag) and opts like the commandline pdf2txt {'-o': '/path/to/outfile.txt' ...}. By default, you can call:
convert_pdf(path)
A text file will be created, a sibling on the filesystem to the original pdf.
def convert_pdf(path, outtype='txt', opts={}):
import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, process_pdf
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter, TagExtractor
from pdfminer.layout import LAParams
from pdfminer.pdfparser import PDFDocument, PDFParser
from pdfminer.pdfdevice import PDFDevice
from pdfminer.cmapdb import CMapDB
outfile = path[:-3] + outtype
outdir = '/'.join(path.split('/')[:-1])
debug = 0
# input option
password = ''
pagenos = set()
maxpages = 0
# output option
codec = 'utf-8'
pageno = 1
scale = 1
showpageno = True
laparams = LAParams()
for (k, v) in opts:
if k == '-d': debug += 1
elif k == '-p': pagenos.update( int(x)-1 for x in v.split(',') )
elif k == '-m': maxpages = int(v)
elif k == '-P': password = v
elif k == '-o': outfile = v
elif k == '-n': laparams = None
elif k == '-A': laparams.all_texts = True
elif k == '-D': laparams.writing_mode = v
elif k == '-M': laparams.char_margin = float(v)
elif k == '-L': laparams.line_margin = float(v)
elif k == '-W': laparams.word_margin = float(v)
elif k == '-O': outdir = v
elif k == '-t': outtype = v
elif k == '-c': codec = v
elif k == '-s': scale = float(v)
#
CMapDB.debug = debug
PDFResourceManager.debug = debug
PDFDocument.debug = debug
PDFParser.debug = debug
PDFPageInterpreter.debug = debug
PDFDevice.debug = debug
#
rsrcmgr = PDFResourceManager()
if not outtype:
outtype = 'txt'
if outfile:
if outfile.endswith('.htm') or outfile.endswith('.html'):
outtype = 'html'
elif outfile.endswith('.xml'):
outtype = 'xml'
elif outfile.endswith('.tag'):
outtype = 'tag'
if outfile:
outfp = file(outfile, 'w')
else:
outfp = sys.stdout
if outtype == 'txt':
device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)
elif outtype == 'xml':
device = XMLConverter(rsrcmgr, outfp, codec=codec, laparams=laparams, outdir=outdir)
elif outtype == 'html':
device = HTMLConverter(rsrcmgr, outfp, codec=codec, scale=scale, laparams=laparams, outdir=outdir)
elif outtype == 'tag':
device = TagExtractor(rsrcmgr, outfp, codec=codec)
else:
return usage()
fp = file(path, 'rb')
process_pdf(rsrcmgr, device, fp, pagenos, maxpages=maxpages, password=password)
fp.close()
device.close()
outfp.close()
return
Use ?'%*%'
to get the documentation.
%*%
is matrix multiplication. For matrix multiplication, you need an m x n
matrix times an n x p
matrix.
Use the below method for calculating the distance of two different locations.
public double getKilometers(double lat1, double long1, double lat2, double long2) {
double PI_RAD = Math.PI / 180.0;
double phi1 = lat1 * PI_RAD;
double phi2 = lat2 * PI_RAD;
double lam1 = long1 * PI_RAD;
double lam2 = long2 * PI_RAD;
return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));}
SELECT word FROM table WHERE word NOT LIKE '%a%'
AND word NOT LIKE '%b%'
AND word NOT LIKE '%c%';
iptables(8) has a statistic match module that can be used to match every nth packet. To drop this packet, just append -j DROP.
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
i also got the same error and i was uninstall vmware to fix that error.
Thre are 2 ways to run Action Query in MS Access VBA:
DoCmd.OpenQuery
statement. This allows you to control these warnings:BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs
Function RunActionQuery(QueryName As String)
On Error GoTo Hell 'Set Error Hanlder
DoCmd.SetWarnings True 'Turn On Warnings
DoCmd.OpenQuery QueryName 'Execute Action Query
DoCmd.SetWarnings False 'Turn On Warnings
Exit Function
Hell:
If Err.Number = 2501 Then 'If Query Was Canceled
MsgBox Err.Description, vbInformation
Else 'Everything else
MsgBox Err.Description, vbCritical
End If
End Function
CurrentDb.Execute
method. This alows you to keep Action Query failures
under control. The SetWarnings flag does not affect it. Query is executed always without warnings.Function RunActionQuery()
'To Catch the Query Error use dbFailOnError option
On Error GoTo Hell
CurrentDb.Execute "Query1", dbFailOnError
Exit Function
Hell:
Debug.Print Err.Description
End Function
It is worth noting that the dbFailOnError
option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified
In addition, you can use DoCmd.Hourglass True
and DoCmd.Hourglass False
to control the mouse pointer if your Query takes longer
<html>
<style>
.selectBox{
color:White;
}
.optionBox{
color:black;
}
</style>
<body>
<select class = "selectBox">
<option class = "optionBox">One</option>
<option class = "optionBox">Two</option>
<option class = "optionBox">Three</option>
</select>
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
Another way is that you can use bitmask for each optional field. and set those bits if values are set and reset those bits which values are not set
enum bitsV {
baz_present = 1; // 0x01
baz1_present = 2; // 0x02
}
message Foo {
uint32 bitMask;
required int32 bar = 1;
optional int32 baz = 2;
optional int32 baz1 = 3;
}
On parsing check for value of bitMask.
if (bitMask & baz_present)
baz is present
if (bitMask & baz1_present)
baz1 is present
console.log("my object: %o", myObj)
Otherwise you'll end up with a string representation sometimes displaying:
[object Object]
or some such.
$.ajax({
url:href,
type:'get',
success: function(data){
console.log($(data));
}
});
This console log gets an array like object: [meta, title, ,], very strange
You can use JavaScript:
var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))
A dummy answer :-
I think explanation is given in above answer, so i am just gonna tell you where to use STRONG
and where to use WEAK
:
Use of Weak
:-
1. Delegates
2. Outlets
3. Subviews
4. Controls, etc.
Use of Strong
:-
Remaining everywhere which is not included in WEAK
.
Just add these lines in your styles.xml file
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- This is used for statusbar color. -->
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<!-- This is used for statusbar content color. If statusbarColor is light, use "true" otherwise use "false"-->
<item name="android:windowLightStatusBar">false</item>
</style>
This example:Views Collection, CommandText Property Example (VB) Shows how to use ADOX to maintain VIEWS by changing COMMAND related to VIEW. But instead using it like this:
Set cmd = cat.Views("AllCustomers").Command
' Update the CommandText of the command.
cmd.CommandText = _
"Select CustomerId, CompanyName, ContactName From Customers"
just try to use this way:
Set CommandText = cat.Views("AllCustomers").Command.CommandText
MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.
for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php
to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/
Kotlin
do this instead:For Example,
// * The Method I Mentioned Above
private fun parseTheValue(@NonNull valueYouWantToParse: String)
{
val intent = Intent(this, AnotherActivity::class.java)
intent.putExtra("value", valueYouWantToParse)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent)
this.finish()
}
Then just call parseTheValue("the String that you want to parse")
e.g,
val theValue: String
parseTheValue(theValue)
then in the other activity,
val value: Bundle = intent.extras!!
// * enter the `name` from the `@param`
val str: String = value.getString("value").toString()
// * For testing
println(str)
Hope This Help, Happy Coding!
~ Kotlin Code Added By John Melody~
I would like to add a solution, that have helpt me to solve this problem in entity framework:
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => x.DateTimeStart.Year == currentDateTime.Year &&
x.DateTimeStart.Month== currentDateTime.Month &&
x.DateTimeStart.Day == currentDateTime.Day
);
I hope that it helps.
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
I kept having problems with this, the only solution was to add an image and label as subviews to the uibutton. Then I discovered that the main problem was that I was using a UIButton with title: Attributed. When I changed it to Plain, just setting the titleLabel.text did the trick!
With numpy, you can pass a slice for each component of the index - so, your x[0:2,0:2]
example above works.
If you just want to evenly skip columns or rows, you can pass slices with three components (i.e. start, stop, step).
Again, for your example above:
>>> x[1:4:2, 1:4:2]
array([[ 5, 7],
[13, 15]])
Which is basically: slice in the first dimension, with start at index 1, stop when index is equal or greater than 4, and add 2 to the index in each pass. The same for the second dimension. Again: this only works for constant steps.
The syntax you got to do something quite different internally - what x[[1,3]][:,[1,3]]
actually does is create a new array including only rows 1 and 3 from the original array (done with the x[[1,3]]
part), and then re-slice that - creating a third array - including only columns 1 and 3 of the previous array.
For it is fixed by using below statement in app.web.scss
$fa-font-path: "../../node_modules/font-awesome/fonts/" !default;
@import "../../node_modules/font-awesome/scss/font-awesome";
While I agree with what everyone has said above. I have a different take on this code. Basically you're assigning the new list to the local variable myList not the global. if you change the signature of ChangeList(List myList) to private void ChangeList() you'll see the output of 3, 4.
Here's my reasoning... Even though list is passed by reference, think of it as passing a pointer variable by value When you call ChangeList(myList) you're passing the pointer to (Global)myList. Now this is stored in the (local)myList variable. So now your (local)myList and (global)myList are pointing to the same list. Now you do a sort => it works because (local)myList is referencing the original (global)myList Next you create a new list and assign the pointer to that your (local)myList. But as soon as the function exits the (local)myList variable is destroyed. HTH
class Test
{
List<int> myList = new List<int>();
public void TestMethod()
{
myList.Add(100);
myList.Add(50);
myList.Add(10);
ChangeList();
foreach (int i in myList)
{
Console.WriteLine(i);
}
}
private void ChangeList()
{
myList.Sort();
List<int> myList2 = new List<int>();
myList2.Add(3);
myList2.Add(4);
myList = myList2;
}
}
You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:
AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.
As of 2018, the accepted answer is out-of-date:
Sweetalert is maintained, and you can solve the original question's issue with use of the content option.
from ctypes import *
pthread = cdll.LoadLibrary("libpthread-2.15.so")
pthread.pthread_cancel(c_ulong(t.ident))
t is your Thread
object.
Read the python source (Modules/threadmodule.c
and Python/thread_pthread.h
) you can see the Thread.ident
is an pthread_t
type, so you can do anything pthread
can do in python use libpthread
.
If you go to your android-sdk/tools
folder I think you'll find a message :
The adb tool has moved to platform-tools/
If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"
Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.
So you should also add C:/android-sdk/platform-tools
to you environment path. Also after you modify the PATH
variable make sure that you start a new CommandPrompt
window.
You can also use btoa instead of base64.encode().
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
Try using these theme: Theme.AppCompat.Light.NoActionBar
Mi Style XML file looks like these and works just fine:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
I know this might be coming very late, but it may prove useful to someone. So for appending key value pairs to dictionaries in swift, you can use updateValue(value: , forKey: ) method as follows :
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
Jenkins is the new Hudson. It really is more like a rename, not a fork, since the whole development community moved to Jenkins. (Oracle is left sitting in a corner holding their old ball "Hudson", but it's just a soul-less project now.)
C.f. Ethereal -> WireShark
You can clean up a zombie process by killing its parent process with the following command:
kill -HUP $(ps -A -ostat,ppid | awk '{/[zZ]/{ print $2 }')
You can get width and height of image with BufferedImage object using java.
public void setWidthAndHeightImage(FileUploadEvent event){
byte[] imageTest = event.getFile().getContents();
baiStream = new ByteArrayInputStream(imageTest );
BufferedImage bi = ImageIO.read(baiStream);
//get width and height of image
int imageWidth = bi.getWidth();
int imageHeight = bi.getHeight();
}
Two options for runtime type checking with generics:
Option 1 - Corrupt your constructor
Let's assume you are overriding indexOf(...), and you want to check the type just for performance, to save yourself iterating the entire collection.
Make a filthy constructor like this:
public MyCollection<T>(Class<T> t) {
this.t = t;
}
Then you can use isAssignableFrom to check the type.
public int indexOf(Object o) {
if (
o != null &&
!t.isAssignableFrom(o.getClass())
) return -1;
//...
Each time you instantiate your object you would have to repeat yourself:
new MyCollection<Apples>(Apples.class);
You might decide it isn't worth it. In the implementation of ArrayList.indexOf(...), they do not check that the type matches.
Option 2 - Let it fail
If you need to use an abstract method that requires your unknown type, then all you really want is for the compiler to stop crying about instanceof. If you have a method like this:
protected abstract void abstractMethod(T element);
You can use it like this:
public int indexOf(Object o) {
try {
abstractMethod((T) o);
} catch (ClassCastException e) {
//...
You are casting the object to T (your generic type), just to fool the compiler. Your cast does nothing at runtime, but you will still get a ClassCastException when you try to pass the wrong type of object into your abstract method.
NOTE 1: If you are doing additional unchecked casts in your abstract method, your ClassCastExceptions will get caught here. That could be good or bad, so think it through.
NOTE 2: You get a free null check when you use instanceof. Since you can't use it, you may need to check for null with your bare hands.
You are passing hello()
as a string, also hello()
means execute hello
immediately.
try
onClick={hello}
For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).
Work with:
ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL;
There's also the DateTime class which implements a function for comparison operators.
// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');
if ( $dtA > $dtB ) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}
import java.awt.MouseInfo;
import java.util.concurrent.TimeUnit;
public class Cords {
public static void main(String[] args) throws InterruptedException {
//get cords of mouse code, outputs to console every 1/2 second
//make sure to import and include the "throws in the main method"
while(true == true)
{
TimeUnit.SECONDS.sleep(1/2);
double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
System.out.println("X:" + mouseX);
System.out.println("Y:" + mouseY);
//make sure to import
}
}
}
git submodule foreach --recursive git checkout .
This didn't do the trick for me but it gave me a list of files (in my case only one) that had been changed in the submodule (without me doing anything there).
So I could head over to the submodule and git status showed me that my HEAD was detached -> git checkout master, git status to see the modified file once again, git checkout >filename<, git pull and everything fine again.
Chris Chilvers' advice should be the first course of action but sometimes we're dealing with third party libraries that makes this challenging and requires us to do naughty things... which this is. IMO it's a crime of presumption similar to using !important in CSS.
Having said that, building on Anurag's answer, here are a few additions. These methods allow for multiple events (e.g. "keydown keyup paste"), arbitrary positioning of the handler and reordering after the fact.
$.fn.bindFirst = function (name, fn) {
this.bindNth(name, fn, 0);
}
$.fn.bindNth(name, fn, index) {
// Bind event normally.
this.bind(name, fn);
// Move to nth position.
this.changeEventOrder(name, index);
};
$.fn.changeEventOrder = function (names, newIndex) {
var that = this;
// Allow for multiple events.
$.each(names.split(' '), function (idx, name) {
that.each(function () {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// Validate requested position.
newIndex = Math.min(newIndex, handlers.length - 1);
handlers.splice(newIndex, 0, handlers.pop());
});
});
};
One could extrapolate on this with methods that would place a given handler before or after some other given handler.
First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).
For the method-level stuff, there is [MethodImpl]
:
[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}
This can also be used on accessors (properties and events):
private int i;
public int SomeProperty
{
[MethodImpl(MethodImplOptions.Synchronized)]
get { return i; }
[MethodImpl(MethodImplOptions.Synchronized)]
set { i = value; }
}
Note that field-like events are synchronized by default, while auto-implemented properties are not:
public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized
Personally, I don't like the implementation of MethodImpl
as it locks this
or typeof(Foo)
- which is against best practice. The preferred option is to use your own locks:
private readonly object syncLock = new object();
public void SomeMethod() {
lock(syncLock) { /* code */ }
}
Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this)
/ lock(Type)
- however, in more recent compilers it uses Interlocked
updates - so thread-safe without the nasty parts.
This allows more granular usage, and allows use of Monitor.Wait
/Monitor.Pulse
etc to communicate between threads.
A related blog entry (later revisited).
You can access to the properties you want passing an argument to your callback function (like evt
), and then accessing the files with it (evt.target.files[0].name
) :
$("document").ready(function(){
$("main").append('<input type="file" name="photo" id="upload-photo"/>');
$('#upload-photo').on('change',function(evt) {
alert(evt.target.files[0].name);
});
});
Naturally, I would not rest until I have the most convenient solution of all. Combining the very many answers and topics on the vast internet, here is what you can have.
cmd
DOSKEY
for aliasesls=ls --color=auto $*
Note that this is largely based on Argyll's answer and comments, definitely read it to understand the concepts.
mac
macro file with the aliasesbat
/cmd
file to also run other stuff (similar to .bashrc
in linux)cmd
%userprofile%/cmd/aliases.mac
;==============================================================================
;= This file is registered via registry to auto load with each instance of cmd.
;================================ general info ================================
;= https://stackoverflow.com/a/59978163/985454 - how to set it up?
;= https://gist.github.com/postcog/5c8c13f7f66330b493b8 - example doskey macrofile
;========================= loading with cmd shortcut ==========================
;= create a shortcut with the following target :
;= %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"
alias=subl %USERPROFILE%\cmd\aliases.mac
hosts=runas /noprofile /savecred /user:QWERTY-XPS9370\administrator "subl C:\Windows\System32\drivers\etc\hosts" > NUL
p=@echo "~~ powercfg -devicequery wake_armed ~~" && powercfg -devicequery wake_armed && @echo "~~ powercfg -requests ~~ " && powercfg -requests && @echo "~~ powercfg -waketimers ~~"p && powercfg -waketimers
ls=ls --color=auto $*
ll=ls -l --color=auto $*
la=ls -la --color=auto $*
grep=grep --color $*
~=cd %USERPROFILE%
cdr=cd C:\repos
cde=cd C:\repos\esquire
cdd=cd C:\repos\dixons
cds=cd C:\repos\stekkie
cdu=cd C:\repos\uplus
cduo=cd C:\repos\uplus\oxbridge-fe
cdus=cd C:\repos\uplus\stratus
npx=npx --no-install $*
npxi=npx $*
npr=npm run $*
now=vercel $*
;=only in bash
;=alias whereget='_whereget() { A=$1; B=$2; shift 2; eval \"$(where $B | head -$A | tail -1)\" $@; }; _whereget'
history=doskey /history
;= h [SHOW | SAVE | TSAVE ]
h=IF ".$*." == ".." (echo "usage: h [ SHOW | SAVE | TSAVE ]" && doskey/history) ELSE (IF /I "$1" == "SAVE" (doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "TSAVE" (echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "SHOW" (type %USERPROFILE%\cmd\history.log) ELSE (doskey/history))))
loghistory=doskey /history >> %USERPROFILE%\cmd\history.log
;=exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved, exiting & timeout 1 & exit $*
exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & exit $*
;============================= :end ============================
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line. It clears out the ';'
;= rem * macro. We're using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=
Now you have three options:
a) load manually with shortcut
create a shortcut to
cmd.exe
with the following target :
%comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"
b) register just the aliases.mac
macrofile
c) register a regular cmd/bat
file to also run arbitrary commands
see example cmdrc.cmd
file at the bottom
note: Below, Autorun_
is just a placeholder key which will not do anything. Pick one and rename the other.
Manually edit registry at this path:
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
Autorun REG_SZ doskey /macrofile=%userprofile%\cmd\aliases.mac
Autorun_ REG_SZ %USERPROFILE%\cmd\cmdrc.cmd
Or import reg file:
%userprofile%/cmd/cmd-aliases.reg
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="doskey /macrofile=%userprofile%\\cmd\\aliases.mac"
"Autorun_"="%USERPROFILE%\\cmd\\cmdrc.cmd"
%userprofile%/cmd/cmdrc.cmd
you don't need this file if you decided for b) above
:: This file is registered via registry to auto load with each instance of cmd.
:: https://stackoverflow.com/a/59978163/985454
@echo off
doskey /macrofile=%userprofile%\cmd\aliases.mac
:: put other commands here
I added the ISAPI/CGI paths for .Net 4. Which didn't fix the issue. So I then ran a repair on the .Net V4 (Client and Extended) installation. Which asked for a reboot. This fixed it for me.
The POST/GET with 204 seems fine in the first sight and will also work.
Documentation says, 2xx -- This class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully. whereas 4xx -- The 4xx class of status code is intended for situations in which the client seems to have erred.
Since, the request was successfully received, understood and processed on server. The result was that the resource was not found. So, in this case this was not an error on the client side or the client has not erred.
Hence this should be a series 2xx code and not 4xx. Sending 204 (No Content) in this case will be better than a 404 or 410 response.
In your html you can pass in an array for the name i.e
<input type="text" name="address[]" />
This way php will receive an array of addresses.
Verify(a).aFunc(eq(b))
In pseudocode:
When in the instance
a
- a function namedaFunc
is called.Verify this call got an argument which is equal to
b
.
For only digits input use android:inputType="numberPassword"
along with editText.setTransformationMethod(null);
to remove auto-hiding of the number.
OR
android:inputType="phone"
For only digits input, I feel these couple ways are better than android:inputType="number"
. The limitation of mentioning "number" as inputType is that the keyboard allows to switch over to characters and also lets other special characters be entered. "numberPassword" inputType doesn't have those issues as the keyboard only shows digits. Even "phone" inputType works as the keyboard doesnt allow you to switch over to characters. But you can still enter couple special characters like +, /, N, etc.
android:inputType="numberPassword" with editText.setTransformationMethod(null);
inputType="phone"
inputType="number"
$('#check1').prop('checked', true).uniform();
$('#check1').prop('checked', false).uniform();
This worked for me.
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
It goes like ng-bind-html-unsafe="opt.text"
:
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
Or you can define a function in scope:
$scope.getContent = function(obj){
return obj.value + " " + obj.text;
}
And use it this way:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
{{ opt.value }}
</li>
Note that you can not do it with an option
tag: Can I use HTML tags in the options for select elements?
Well here is a nice script to TRIM all varchar columns on a table dynamically:
--Just change table name
declare @MyTable varchar(100)
set @MyTable = 'MyTable'
--temp table to get column names and a row id
select column_name, ROW_NUMBER() OVER(ORDER BY column_name) as id into #tempcols from INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('varchar', 'nvarchar') and TABLE_NAME = @MyTable
declare @tri int
select @tri = count(*) from #tempcols
declare @i int
select @i = 0
declare @trimmer nvarchar(max)
declare @comma varchar(1)
set @comma = ', '
--Build Update query
select @trimmer = 'UPDATE [dbo].[' + @MyTable + '] SET '
WHILE @i <= @tri
BEGIN
IF (@i = @tri)
BEGIN
set @comma = ''
END
SELECT @trimmer = @trimmer + CHAR(10)+ '[' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + ']))'+@comma
FROM #tempcols
where id = @i
select @i = @i+1
END
--execute the entire query
EXEC sp_executesql @trimmer
drop table #tempcols
process.on('warning', function(e) {
'use strict';
console.warn(e.stack);
});
process.on('uncaughtException', function(e) {
'use strict';
console.warn(e.stack);
});
add this lines to at the starting point of your file
We have just uploaded AmbilWarna color picker to Maven:
https://github.com/yukuku/ambilwarna
It can be used either as a dialog or as a Preference entry.
Do you want something like in LINQ skip 5 and take 10?
SELECT TOP(10) * FROM MY_TABLE
WHERE ID not in (SELECT TOP(5) ID From My_TABLE);
This approach will work in any SQL version.
PHP is not what you are looking for, check out mod_rewrite
simple is the best and works in every version.
if a>10:
value="b"
else:
value="c"
matplotlib.pyplot.vlines
vs. matplotlib.pyplot.axvline
vlines
accepts 1 or more locations for x
, while axvline
permits one location.
x=37
x=[37, 38, 39]
vlines
takes ymin
and ymax
as a position on the y-axis, while axvline
takes ymin
and ymax
as a percentage of the y-axis range.
vlines
, pass a list
to ymin
and ymax
.fig, ax = plt.subplots()
, then replace plt.vlines
or plt.axvline
with ax.vlines
or ax.axvline
, respectively.import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()
The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:
1) null, meaning that no request has been sent yet
2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.
In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)
Is of course a Bug.
Probably somewhere in your code you use table.estimatedRowHeight = value
(for example 100). Replace this value by the highest value you think a row height could get, for example 500..
This should solve the problem in combination with following code:
//auto scroll down example
let delay = 0.1 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
self.table.scrollToRowAtIndexPath(NSIndexPath(forRow: self.Messages.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
})
–npm install --save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give the desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.
npm install --save
Here is the most clear & intuitive way i know to allocate a dynamic 2d array in C++. Templated in this example covers all cases.
template<typename T> T** matrixAllocate(int rows, int cols, T **M)
{
M = new T*[rows];
for (int i = 0; i < rows; i++){
M[i] = new T[cols];
}
return M;
}
...
int main()
{
...
int** M1 = matrixAllocate<int>(rows, cols, M1);
double** M2 = matrixAllocate(rows, cols, M2);
...
}
This error means that the value indexed by the key "l_messages" is not of type hash
, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist())
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
Here's a full listing of a program and its results.
The code:
using System;
namespace TimeZoneIds
{
class Program
{
static void Main(string[] args)
{
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
{
Console.WriteLine(z.Id);
}
}
}
}
The TimeZoneId results on my Windows 7 workstation:
Dateline Standard Time
UTC-11
Samoa Standard Time
Hawaiian Standard Time
Alaskan Standard Time
Pacific Standard Time (Mexico)
Pacific Standard Time
US Mountain Standard Time
Mountain Standard Time (Mexico)
Mountain Standard Time
Central America Standard Time
Central Standard Time
Central Standard Time (Mexico)
Canada Central Standard Time
SA Pacific Standard Time
Eastern Standard Time
US Eastern Standard Time
Venezuela Standard Time
Paraguay Standard Time
Atlantic Standard Time
Central Brazilian Standard Time
SA Western Standard Time
Pacific SA Standard Time
Newfoundland Standard Time
E. South America Standard Time
Argentina Standard Time
SA Eastern Standard Time
Greenland Standard Time
Montevideo Standard Time
UTC-02
Mid-Atlantic Standard Time
Azores Standard Time
Cape Verde Standard Time
Morocco Standard Time
UTC
GMT Standard Time
Greenwich Standard Time
W. Europe Standard Time
Central Europe Standard Time
Romance Standard Time
Central European Standard Time
W. Central Africa Standard Time
Namibia Standard Time
Jordan Standard Time
GTB Standard Time
Middle East Standard Time
Egypt Standard Time
Syria Standard Time
South Africa Standard Time
FLE Standard Time
Israel Standard Time
E. Europe Standard Time
Arabic Standard Time
Arab Standard Time
Russian Standard Time
E. Africa Standard Time
Iran Standard Time
Arabian Standard Time
Azerbaijan Standard Time
Mauritius Standard Time
Georgian Standard Time
Caucasus Standard Time
Afghanistan Standard Time
Ekaterinburg Standard Time
Pakistan Standard Time
West Asia Standard Time
India Standard Time
Sri Lanka Standard Time
Nepal Standard Time
Central Asia Standard Time
Bangladesh Standard Time
N. Central Asia Standard Time
Myanmar Standard Time
SE Asia Standard Time
North Asia Standard Time
China Standard Time
North Asia East Standard Time
Singapore Standard Time
W. Australia Standard Time
Taipei Standard Time
Ulaanbaatar Standard Time
Tokyo Standard Time
Korea Standard Time
Yakutsk Standard Time
Cen. Australia Standard Time
AUS Central Standard Time
E. Australia Standard Time
AUS Eastern Standard Time
West Pacific Standard Time
Tasmania Standard Time
Vladivostok Standard Time
Central Pacific Standard Time
New Zealand Standard Time
UTC+12
Fiji Standard Time
Kamchatka Standard Time
Tonga Standard Time
Also possible like this
<button type="submit" class="icon-search icon-large"></button>
JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.
Your syntax above is wrong as you are initializing the users
object as null. I presume this is a typo, as the code should read:
// Initialize users as a new hash.
var users = {};
users["182982"] = "...";
To retrieve all the values from a hash, you need to iterate over it using a for loop:
function getValues (hash) {
var values = [];
for (var key in hash) {
// Ensure that the `key` is actually a member of the hash and not
// a member of the `prototype`.
// see: http://javascript.crockford.com/code.html#for%20statement
if (hash.hasOwnProperty(key)) {
values.push(key);
}
}
return values;
};
If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values
method which will perform the above task for you:
var values = _.values(users);
I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="btn-group btn-block">_x000D_
<button type="button" data-toggle="dropdown" class="btn btn-default btn-xs btn-block dropdown-toggle">Actions <span class="caret"></span>_x000D_
<span class="sr-only">Toggle Dropdown</span></button><ul role="menu" class="dropdown-menu"><li><a href="#">Action one</a></li><li class="divider"></li><li><a href="#" >Action Two</a></li></ul></div>
_x000D_
Try
adb uninstall package-name
It works for me. I have remove my app using Titanium Backup. However,I think Titanium backup didn't removed my app totally.
Another way is creating a system unit for your app. create a "XXX.service" file in "/etc/systemd/system" folder, similar to this:
[Unit]
Description=swagger
After=network.target
[Service]
ExecStart=/usr/bin/http-server /home/swagger/swagger-editor &
WorkingDirectory=/home/swagger
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target
A benefit is the app will run as a service, it automatically restarts if it crashed.
You can also use sytemctl to manage it:
systemctl start XXX
to start the service, systemctl stop XXX
to stop it and systemctl enable XXX
to automatically start the app when system boots.
I hate to answer an old question, but I don't think anybody has mentioned how K&R explain it in section A4.1 of "The C Programming Language".
In short, the word static is used with two meanings:
static
keyword (big emphasis on it being used in
code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). The opposite of static is the extern
keyword, which gives an object external linkage.Peter Van Der Linden gives these two meanings in "Expert C Programming":
why don't you go the simple way like
IF EXISTS(SELECT * FROM sys.procedures WHERE NAME LIKE 'uspBlackListGetAll')
BEGIN
DROP PROCEDURE uspBlackListGetAll
END
GO
CREATE Procedure uspBlackListGetAll
..........
If Character.isLetter(ch)
looks a bit wordy/ugly you can use a static import.
import static java.lang.Character.*;
if(isLetter(ch)) {
} else if(isDigit(ch)) {
}
String#toLowerCase and String#toUpperCase are the methods you need.
You can use the :not
filter selector:
$('foo:not(".someClass")')
Or not()
method:
$('foo').not(".someClass")
More Info:
just do this , you need to remove char other than "numeric" and "." form your string will do work for you
yourString = yourString.replace ( /[^\d.]/g, '' );
your final code will be
str1 = "test123.00".replace ( /[^\d.]/g, '' );
str2 = "yes50.00".replace ( /[^\d.]/g, '' );
total = parseInt(str1, 10) + parseInt(str2, 10);
alert(total);
$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');
or
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
Though I'm not certain it will have an affect as it will be generated after the page is loaded
If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx
This may allow other meta tags, if you're lucky
Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx
Let say you have 2 columns named first_name and last_name in your users table and you want to retrieve full name. you can achieve with the following code :
class User extends Eloquent {
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
}
now you can get full name as:
$user = User::find(1);
$user->full_name;
You can use
timestamp=`date --rfc-3339=seconds`
This delivers in the format 2014-02-01 15:12:35-05:00
The back-tick (`
) characters will cause what is between them to be evaluated and have the result included in the line. date --help
has other options.
You can use Pusher
It's a hosted service that makes it super-easy to add real-time data and functionality to web and mobile applications.
Pusher offers libraries to integrate into all the main runtimes and frameworks.
PHP, Ruby, Python, Java, .NET, Go and Node
on the server
JavaScript, Objective-C (iOS) and Java (Android)
on the client.
You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.
You can start with something like this:
<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
alert(document.someform.file1.value)
}
</script>
I agree with alexmac - do it server-side as well.
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
var checkboxes = document.getElementById("checkboxes");_x000D_
if (!expanded) {_x000D_
checkboxes.style.display = "block";_x000D_
expanded = true;_x000D_
} else {_x000D_
checkboxes.style.display = "none";_x000D_
expanded = false;_x000D_
}_x000D_
}
_x000D_
.multiselect {_x000D_
width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
width: 100%;_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
display: none;_x000D_
border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
<div class="multiselect">_x000D_
<div class="selectBox" onclick="showCheckboxes()">_x000D_
<select>_x000D_
<option>Select an option</option>_x000D_
</select>_x000D_
<div class="overSelect"></div>_x000D_
</div>_x000D_
<div id="checkboxes">_x000D_
<label for="one">_x000D_
<input type="checkbox" id="one" />First checkbox</label>_x000D_
<label for="two">_x000D_
<input type="checkbox" id="two" />Second checkbox</label>_x000D_
<label for="three">_x000D_
<input type="checkbox" id="three" />Third checkbox</label>_x000D_
</div>_x000D_
</div>_x000D_
</form>
_x000D_
Your string looks like a JSON string without the curly braces.
This should work then:
obj = eval('({' + str + '})');
The easiest way to do that is like below:
//Skip First Iteration
foreach ( int number in numbers.Skip(1))
//Skip any other like 5th iteration
foreach ( int number in numbers.Skip(5))