Programs & Examples On #Event handling

Event handling is a coding style about handling messages between a source and one or more subscribers. A point listener in the source provide a way which subscribed code can consume messages raised from the source.

event.preventDefault() vs. return false

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;
});

jQuery checkbox change and click event

$(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'));
            }
        }
    });
});

Why are only final variables accessible in anonymous class?

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.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

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.

Touch move getting stuck Ignored attempt to cancel a touchmove

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;
}

How to use onClick with divs in React.js

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>);
}

C#: calling a button event handler method without actually clicking the button

You can call the btnTest_Click just like any other function.

The most basic form would be this:

btnTest_Click(this, null);

How can I catch a ctrl-c event?

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;    
}

Calling one method from another within same class in Python

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)

How to remove "onclick" with JQuery?

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;
});

jQuery change method on input type="file"

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);
}

Explain ExtJS 4 event handling

Let's start by describing DOM elements' event handling.

DOM node 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

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);
  }
});

Custom events firing

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 */ });

Preventing event bubbling

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();
});

window.onload vs document.onload

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.

How do I add a simple onClick event handler to a canvas element?

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

UITextField text change event

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.

UITextField Change Event

jQuery: more than one handler for same event

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.

JavaScript: remove event listener

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;
};
};

Handling a Menu Item Click Event - Android

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)

Event system in Python

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"

How can I create a dynamic button click event on a dynamic button?

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
}

How do I make an Event in the Usercontrol and have it handled in the Main Form?

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.

How can I be notified when an element is added to the page?

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, clip I 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.

jQuery - Detect value change on hidden input field

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.

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

How can I capture the right-click event in JavaScript?

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(); >

How can I trigger an onchange event manually?

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");

Android Overriding onBackPressed()

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.

Reading the selected value from asp:RadioButtonList using jQuery

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>

Detecting Browser Autofill

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!!

On Chrome, Opera, Edge problem was solved quite EZ

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).

The problem was with Firefox

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.

What is DOM Event delegation?

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.

WPF button click in C# code

// 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);
}

jQuery equivalent of JavaScript's addEventListener method

_x000D_
_x000D_
$( "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_
_x000D_
_x000D_

jQuery preventDefault() not triggered

Try this one:

   $("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
    return false;   
    });

How to pass event as argument to an inline event handler in JavaScript?

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.

the getSource() and getActionCommand()

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)

How can I show a hidden div when a select option is selected?

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>

Pass parameter to EventHandler

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);

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

You need MouseClick instead of Click event handler, reference.

switch (e.Button) {

    case MouseButtons.Left:
    // Left click
    break;

    case MouseButtons.Right:
    // Right click
    break;
    ...
}

Fire event on enter key press for a textbox

  1. Wrap the textbox inside asp:Panel tags

  2. 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>

How to use the DropDownList's SelectedIndexChanged event

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
}

How to click a browser button with JavaScript automatically?

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>

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

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!') }"
    })
    

Fake "click" to activate an onclick method

If you're using JQuery you can do:

$('#elementid').click();

Javascript event handler with parameters

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
    };
};

How to trigger event when a variable's value is changed?

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;

Difference between e.target and e.currentTarget

  • e.target is element, which you f.e. click
  • e.currentTarget is element with added event listener.

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.

How to call function on child component on parent events

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

jQuery checkbox checked state changed event

Try this "html-approach" which is acceptable for small JS projects

_x000D_
_x000D_
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_
_x000D_
_x000D_

Understanding events and event handlers in C#

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".

Import Google Play Services library in Android Studio

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 :)

PowerShell: Comparing dates

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.

Close dialog on click (anywhere)

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');
        });
    }   

});

Wait one second in running program

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;

GET URL parameter in PHP

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

How to get a Docker container's IP address from the host

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.

Ignore <br> with CSS?

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;}

DEMO

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;
}

DEMO

Why is my CSS style not being applied?

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.

How to get client's IP address using JavaScript?

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!

How can I initialize an array without knowing it size?

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); 
}

ReferenceError: describe is not defined NodeJs

i have this error when using "--ui tdd". remove this or using "--ui bdd" fix problem.

How to POST form data with Spring RestTemplate?

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]";

See also https://stackoverflow.com/a/47045624/1357094

Laravel migration: unique key is too long, even if specified

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);

ffprobe or avprobe not found. Please install one

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:

  • Download one of the builds from https://ffmpeg.zeranoe.com/
  • Extract the zip contents
  • Place the contents of the 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.

What is the most "pythonic" way to iterate over a list in chunks?

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())

Arguments:

Obvious ones

  • iterable is any iterable / iterator / generator containg / generating / iterating over input data,
  • size is, of course, size of chunk you want get,

More interesting

  • 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

Select a date from date picker using Selenium webdriver

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;
}

Jinja2 template variable if None Object set a default value

{{p.User['first_name'] or 'My default string'}}

How to force a view refresh without having it trigger automatically from an observable?

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 -->

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Used implementation 'androidx.appcompat:appcompat:1.1.2' in App gradle fixed the issue for me

wkhtmltopdf: cannot connect to X server

  1. Download file from this link
  2. Extract it and move executable file(/wkhtmltox/bin/wkhtmltopdf) to /usr/bin/
  3. Rename it to wkhtmltopdf if current name is not wkhtmltopdf. So that now you have an executable at /usr/bin/wkhtmltopdf
  4. Set permissions: sudo chmod a+x /usr/bin/wkhtmltopdf
  5. Install required support packages. sudo apt-get install openssl build-essential xorg libssl-dev
  6. Now, check with wkhtmltopdf http://www.google.com test.pdf hint: detail information from this link

Return list using select new in LINQ

try 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();
        }
      }

File path issues in R using Windows ("Hex digits in character string" error)

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()

Can I scroll a ScrollView programmatically in Android?

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());*/
                }
            });
        }
    });
}

Angular.js How to change an elements css class on click and to remove all others

I only change/remove the class:

   function removeClass() {
                    var element = angular.element('#nameInput');
          element.removeClass('nameClass');
   };

Is it possible to overwrite a function in PHP

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;');

Use FontAwesome or Glyphicons with css :before

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';}

.datepicker('setdate') issues, in jQuery

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.

How to write to a JSON file in the correct format

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 }

How to change theme for AlertDialog

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.

Bash scripting missing ']'

Change

if [ -s "p1"];  #line 13

into

if [ -s "p1" ];  #line 13

note the space.

Get timezone from users browser using moment(timezone).js

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.

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

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/

Create dynamic variable name

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

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

Aside from other great responses, I just had to give NTFS permissions to the Oracle installation folder. (I gave read access)

Getting a Request.Headers value

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);
}

Python nonlocal statement

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

django no such table:

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.

Razor MVC Populating Javascript array with Model Array

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 });

How to know if a Fragment is Visible?

Try this if you have only one Fragment

if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                    //TODO: Your Code Here
                }

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Easy done:

(?<=\[)(.*?)(?=\])

Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:

  • is preceded by a [ that is not captured (lookbehind);
  • a non-greedy captured group. It's non-greedy to stop at the first ]; and
  • is followed by a ] that is not captured (lookahead).

Alternatively you can just capture what's between the square brackets:

\[(.*?)\]

and return the first captured group instead of the entire match.

Best practice for storing and protecting private API keys in applications

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.

Move_uploaded_file() function is not working

if files are not moving this could be due to several reasons

  • check permissions that upload directory , make sure its permission is at least 0755.
> find * -type d -print0 | xargs -0 chmod 0755 # for directories find *
> -type f -print0 | xargs -0 chmod 0666 # for files
  • make sure upload directory owner & group is not root , in that case your script will not be able to write anything there, so change it to admin or any non-root user.
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
  • check your tmp directory that its writable or not so open php.ini and check upload_tmp_dir = your temp directory path , make sure its writable.
  • try copy function instead of move_uploaded_file

Can Flask have optional URL parameters?

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

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

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

jQuery has deprecated synchronous XMLHTTPRequest

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — 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.

How to set only time part of a DateTime variable in C#

date = new DateTime(date.year, date.month, date.day, HH, MM, SS);

javac : command not found

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.

Using Custom Domains With IIS Express

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.

How do I configure Notepad++ to use spaces instead of tabs?

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.

Screenshot of the windows with preferences

A quick and easy way to join array elements with a separator (the opposite of split) in Java

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.

Get nth character of a string in Swift programming language

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

Visit https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

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

'module' object has no attribute 'DataFrame'

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

What command shows all of the topics and offsets of partitions in Kafka?

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

Update for 0.9 (and higher) consumer APIs

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

Python how to write to a binary file?

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

How to format an inline code in Confluence?

I found formatting with colors a bit trickier as Confluence (5.6.3) is very fussy about spaces around the {{monospace}} blocks.

Creating Colored Monospace with Wiki Markup

As rendered by Confluence

Refused to apply inline style because it violates the following Content Security Policy directive

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.

Important note

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).

Java 8: Lambda-Streams, Filter by Method with Exception

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);
    }
}

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. 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/
    
  2. 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'

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

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();
    }


});

CodeIgniter Disallowed Key Characters

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.

How to make child process die after parent exits?

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:

  • If you deliberately kill the intermediate process, then the child won't be killed when the parent dies.
  • If the child exits before the parent, then the intermediate process will try to kill the original child pid, which could now refer to a different process. (This could be fixed with more code in the intermediate process.)

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)

How to count down in for loop?

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)

CSS Inset Borders

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;
  }

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

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>

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

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)

How can foreign key constraints be temporarily disabled using T-SQL?

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

How can I select rows by range?

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.

From Arraylist to Array

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]);
       }
   }    

}

form action with javascript

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.

Clear listview content?

It's simple .First you should clear your collection and after clear list like this code :

 yourCollection.clear();
 setListAdapter(null);

What's the difference between RANK() and DENSE_RANK() functions in oracle?

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}.

bootstrap multiselect get selected values

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);
    }
}); 

Uploading images using Node.js, Express, and Mongoose

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.
    })

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

C++ - struct vs. class

1) It is the only difference in C++.

2) POD: plain old data Other classes -> not POD

How can I tell how many objects I've stored in an S3 bucket?

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;
    }
}

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

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 ;

Where is SQL Server Management Studio 2012?

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).

sql server setup

Is there a simple way to remove multiple spaces in a string?

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)

How to perform runtime type checking in Dart?

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);

How to check for null in Twig?

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 %}

Convert boolean result into number/integer

Javascript has a ternary operator you could use:

var i = result ? 1 : 0;

How to check if another instance of the application is running

You can try this

Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
    //
}

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

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.

CSS - center two images in css side by side

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.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

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.

libstdc++-6.dll not found

I just had this issue.. I just added the MinGW\bin directory to the path environment variable, and it solved the issue.

Is there a way to automatically generate getters and setters in Eclipse?

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:

  1. Go to Window > Preferences
  2. Go to General > Keys
  3. List for "Quick Assist - Create getter/setter for field"
  4. In the "Binding" textfield below, hold the desired keys (in my case, I use ALT + SHIFT + G)
  5. Hit Apply and Ok
  6. Now in your Java editor, select the field you want to create getter/setter methods for and press the shortcut you setup in Step 4. Hit ok in this window to create the methods.

Hope this helps!

typeof !== "undefined" vs. != null

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

react-router getting this.props.location in child components

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>

filtering NSArray into a new NSArray in Objective-C

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.


Swift:

For those working with NSArrays 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.

How to activate "Share" button in android app?

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.

forward declaration of a struct in C?

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;
}

Clear the entire history stack and start a new activity on Android

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.

How to get a path to the desktop for current user in C#?

// 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

Changing file extension in Python

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')

How to get a subset of a javascript object's properties

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!

TypeScript Playground

how to loop through json array in jquery?

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);
}); 

How to jump to top of browser page

_x000D_
_x000D_
// 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_
_x000D_
_x000D_

Reference member variables as class members

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.

Error including image in Latex

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).

How to add chmod permissions to file in Git?

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.

assembly to compare two numbers

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:

How do I pass multiple parameter in URL?

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.

Call An Asynchronous Javascript Function Synchronously

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;
}

Convert A String (like testing123) To Binary In Java

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);
  }
}   

SQL Update with row_number()

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

Get the current language in device

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();

How to align an input tag to the center without specifying the width?

You need to put the text-align:center on the containing div, not on the input itself.

Python module for converting PDF to text

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

What does %>% mean in R

Use ?'%*%' to get the documentation.

%*% is matrix multiplication. For matrix multiplication, you need an m x n matrix times an n x p matrix.

How to calculate distance between two locations using their longitude and latitude value

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));}

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

SELECT word FROM table WHERE word NOT LIKE '%a%' 
AND word NOT LIKE '%b%' 
AND word NOT LIKE '%c%';

Simulate delayed and dropped packets on Linux

iptables(8) has a statistic match module that can be used to match every nth packet. To drop this packet, just append -j DROP.

In Excel, how do I extract last four letters of a ten letter string?

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))

XAMPP, Apache - Error: Apache shutdown unexpectedly

i also got the same error and i was uninstall vmware to fix that error.

MS Access - execute a saved query by name in VBA

Thre are 2 ways to run Action Query in MS Access VBA:


  1. You can use DoCmd.OpenQuery statement. This allows you to control these warnings:

Action Query Warning Example

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

  1. You can use 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

Change Text Color of Selected Option in a Select Box

<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>

Android setOnClickListener method - How does it work?

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/

How to define an optional field in protobuf 3

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

Object Dump JavaScript

console.log("my object: %o", myObj)

Otherwise you'll end up with a string representation sometimes displaying:

[object Object]

or some such.

How to get the html of a div on another page with jQuery ajax?

$.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'))

Differences between strong and weak in Objective-C

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.

How to change the status bar color in Android?

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>

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

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 - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

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/

How to send string from one activity to another?

For those people who use Kotlin do this instead:

  1. Create a method with a parameter containing String Object.
  2. Navigate to another Activity

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~

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

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.

How to set DateTime to null

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.

is it possible to update UIButton title/text programmatically?

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!

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

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.

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

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";

List passed by ref - help me explain this behaviour

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;
    }
}

oracle SQL how to remove time from date

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.

sweet-alert display HTML code in text

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.

Is there any way to kill a Thread?

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.

adb is not recognized as internal or external command on windows

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.

Basic authentication with fetch?

You can also use btoa instead of base64.encode().

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

Razor If/Else conditional operator syntax

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.

About the Full Screen And No Titlebar from manifest

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>

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

How to append elements into a dictionary in Swift?

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)

How to choose between Hudson and Jenkins?

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

How to kill zombie process

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 }')

How to get image height and width using java?

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();
    }

Java: Instanceof and Generics

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.

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

Why does 2 mod 4 = 2?

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).

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How can I check if the current date/time is past a set date/time?

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';
}

Get Mouse Position

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 diff says subproject is dirty

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.

jQuery event handlers always execute in order they were bound - any way around this?

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.

C# version of java's synchronized keyword?

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).

Get filename from input [type='file'] using jQuery

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);
  });
});

Aliases in Windows command prompt

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.

  • Loads automatically with every instance of cmd
  • Doesn't require keyword DOSKEY for aliases
    example: ls=ls --color=auto $*

Note that this is largely based on Argyll's answer and comments, definitely read it to understand the concepts.

How to make it work?

  1. Create a mac macro file with the aliases
    you can even use a bat/cmd file to also run other stuff (similar to .bashrc in linux)
  2. Register it in Registry to run on each instance of cmd
      or run it via shortcut only if you want

Example steps:

%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

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

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.

HTTP Get with 204 No Content: Is that normal

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.

Multiple inputs with same name through POST in php

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.

Mockito. Verify method arguments

Verify(a).aFunc(eq(b))

In pseudocode:

When in the instance a - a function named aFunc is called.

Verify this call got an argument which is equal to b.

How do you set EditText to only accept numeric values in Android?

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="numberPassword"

inputType="phone"

inputType="phone"

inputType="number"

inputType="number"

How to uncheck checkbox using jQuery Uniform library

$('#check1').prop('checked', true).uniform(); 
$('#check1').prop('checked', false).uniform(); 

This worked for me.

Storing files in SQL Server

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.

angular.js ng-repeat li items with html content

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>

http://jsfiddle.net/gFFBa/3/

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>

http://jsfiddle.net/gFFBa/4/

Note that you can not do it with an option tag: Can I use HTML tags in the options for select elements?

Remove Trailing Spaces and Update in Columns in SQL Server

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

JSLint is suddenly reporting: Use the function form of "use strict"

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

Android Color Picker

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.

enter image description here

How to skip the first n rows in sql query

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.

URL rewriting with PHP

PHP is not what you are looking for, check out mod_rewrite

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: 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.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like 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()

enter image description here

How do I know if jQuery has an Ajax request pending?

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. :)

How to scroll to the bottom of a UITableView on the iPhone before the view appears

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)
})

What is the --save option for npm install?

–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

How do you dynamically allocate a matrix?

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);
    ...
}

WRONGTYPE Operation against a key holding the wrong kind of value php

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.

how do I insert a column at a specific column index in pandas?

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

List of Timezone IDs for use with FindTimeZoneById() in C#?

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

Font-awesome, input type 'submit'

Also possible like this

<button type="submit" class="icon-search icon-large"></button>

How to use ng-repeat for dictionaries in AngularJs?

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 :))

Set a button group's width to 100% and make buttons equal width?

_x000D_
_x000D_
<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_
_x000D_
_x000D_

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

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.

How to make a node.js application run permanently?

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.

What does "static" mean in C?

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:

  1. Static is one of the two storage classes (the other being automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
  2. But, when the 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":

  • Inside a function, retains its value between calls.
  • At the function level, visible only in this file.

How to check if a stored procedure exists before creating it

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

..........

"Char cannot be dereferenced" error

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)) {

} 

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

Getting Integer value from a String using javascript/jquery

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);

Demo

How to add meta tag in JavaScript

$('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

Add a custom attribute to a Laravel / Eloquent model on load?

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;

Create timestamp variable in bash script

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.

Push Notifications in Android Platform

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.

Filter Extensions in HTML form upload

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.

How to create checkbox inside dropdown?

_x000D_
_x000D_
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_
_x000D_
_x000D_

String to object in JS

Your string looks like a JSON string without the curly braces.

This should work then:

obj = eval('({' + str + '})');

How do I skip an iteration of a `foreach` loop?

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))