Drop Down Menu/Text Field in one
I found this question and discussion very helpful and wanted to show the solution I ended up with. It is based on the answer given by @DevangRathod, but I used jQuery and made a couple tweaks to it, so wanted to show a fully commented sample to help anyone else working on something similar. I originally had been using the HTML5 data-list element, but was dissatisfied with that solution since it removes options from the drop down list that don't match text typed in the box. In my application, I wanted the full list to always be available.
Fully functional demo here: https://jsfiddle.net/abru77mm/
HTML:
<!--
Most style elements I left to the CSS file, but some are here.
Reason being that I am actually calculating my width dynamically
in my application so when I dynamically formulate this HTML, I
want the width and all the factors (such as padding and border
width and margin) that go into determining the proper widths to
be controlled by one piece of code, so those pieces are done in
the in-line style. Otherwise I leave the styling to the CSS file.
-->
<div class="data-list-input" style="width:190px;">
<select class="data-list-input" style="width:190px;">
<option value=""><Free Form Text></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<!-- Note that though the select/option allows for a different
display and internal value, there is no such distinction in the
text box, so for all the options (except the "none" option) the
value and content of the option should be identical. -->
</select>
<input class="data-list-input" style="width:160px;padding:4px 6px;border-width:1px;margin:0;" type="text" name="sex" required="required" value="">
</div>
JS:
jQuery(function() {
//keep the focus on the input box so that the highlighting
//I'm using doesn't give away the hidden select box to the user
$('select.data-list-input').focus(function() {
$(this).siblings('input.data-list-input').focus();
});
//when selecting from the select box, put the value in the input box
$('select.data-list-input').change(function() {
$(this).siblings('input.data-list-input').val($(this).val());
});
//When editing the input box, reset the select box setting to "free
//form input". This is important to do so that you can reselect the
//option you had selected if you want to.
$('input.data-list-input').change(function() {
$(this).siblings('select.data-list-input').val('');
});
});
CSS:
div.data-list-input
{
position: relative;
height: 20px;
display: inline-flex;
padding: 5px 0 5px 0;
}
select.data-list-input
{
position: absolute;
top: 5px;
left: 0px;
height: 20px;
}
input.data-list-input
{
position: absolute;
top: 0px;
left: 0px;
height: 20px;
}
Any comments for improvement on my implementation welcome. Hope someone finds this helpful.
How can I create an editable dropdownlist in HTML?
A combobox is unfortunately something that was left out of the HTML specifications.
The only way to manage it, rather unfortunately, is to roll your own or use a pre-built one. This one looks quite simple. I use this one for an open-source app although unfortunately you have to pay for commercial usage.
Fill drop down list on selection of another drop down list
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
jQuery - disable selected options
This seems to work:
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);
theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});
Working with select using AngularJS's ng-options
For some reason AngularJS allows to get me confused. Their documentation is pretty horrible on this. More good examples of variations would be welcome.
Anyway, I have a slight variation on Ben Lesh's answer.
My data collections looks like this:
items =
[
{ key:"AD",value:"Andorra" }
, { key:"AI",value:"Anguilla" }
, { key:"AO",value:"Angola" }
...etc..
]
Now
<select ng-model="countries" ng-options="item.key as item.value for item in items"></select>
still resulted in the options value to be the index (0, 1, 2, etc.).
Adding Track By fixed it for me:
<select ng-model="blah" ng-options="item.value for item in items track by item.key"></select>
I reckon it happens more often that you want to add an array of objects into an select list, so I am going to remember this one!
Be aware that from AngularJS 1.4 you can't use ng-options any more, but you need to use ng-repeat
on your option tag:
<select name="test">
<option ng-repeat="item in items" value="{{item.key}}">{{item.value}}</option>
</select>
How to ensure a <select> form field is submitted when it is disabled?
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
Where select_name
is the name that you would normally give the <select>
.
Another option.
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden
input either before, or after the <select>
.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.
jQuery remove options from select
if your dropdown is in a table and you do not have id for it then you can use the following jquery:
var select_object = purchasing_table.rows[row_index].cells[cell_index].childNodes[1];
$(select_object).find('option[value='+site_name+']').remove();
Post values from a multiple select
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
Default text which won't be shown in drop-down list
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
How to get selected value of a html select with asp.net
If you would use asp:dropdownlist
you could select it easier by testSelect.Text
.
Now you'd have to do a Request.Form["testSelect"]
to get the value after pressed btnTes
.
Hope it helps.
EDIT: You need to specify a name
of the select (not only ID) to be able to Request.Form["testSelect"]
How can I set the default value for an HTML <select> element?
I used this php function to generate the options, and insert it into my HTML
<?php
# code to output a set of options for a numeric drop down list
# parameters: (start, end, step, format, default)
function numericoptions($start, $end, $step, $formatstring, $default)
{
$retstring = "";
for($i = $start; $i <= $end; $i = $i + $step)
{
$retstring = $retstring . '<OPTION ';
$retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
if($default == $i)
{
$retstring = $retstring . ' selected="selected"';
}
$retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
}
return $retstring;
}
?>
And then in my webpage code I use it as below;
<select id="endmin" name="endmin">
<?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>
If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.
Is it possible to use JS to open an HTML select to show its option list?
This works on Google Chrome
dropDown = function (elementId) {
var dropdown = document.getElementById(elementId);
try {
showDropdown(dropdown);
} catch(e) {
}
return false;
};
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
Line Break in HTML Select Option?
An idea could be to use the optgroup. In my case found it better than the disabled approach. It's less confusing for the user than seeing the disabled option I think.
<select id="q1" v-model="selected" v-on:change="setCPost1(selected)">
<option value="0"></option>
<template
v-for="(child, idx) in getLevel1"
v-bind:value="child.id"
>
<optgroup v-bind:value="child.id" :key="idx"
:label="child.label"
v-if="child.label_line_two"
>
</optgroup>
<option v-bind:value="child.id" :key="idx" v-if="!child.label_line_two"
>
{{ child.label }}
</option>
<option v-bind:value="child.id" :key="idx" v-if="child.label_line_two"
style="font-style:italic">
{{ child.label_line_two }}
</option>
</template>
</select>
An external component sounds cool like Vue Select, but I wanted to stick with the native html select at the moment.
How can I get new selection in "select" in Angular 2?
I ran into this problem while doing the Angular 2 forms tutorial (TypeScript version) at https://angular.io/docs/ts/latest/guide/forms.html
The select/option block wasn't allowing the value of the selection to be changed by selecting one of the options.
Doing what Mark Rajcok suggested worked, although I'm wondering if there's something I missed in the original tutorial or if there was an update. In any case, adding
onChange(newVal) {
this.model.power = newVal;
}
to hero-form.component.ts in the HeroFormComponent class
and
(change)="onChange($event.target.value)"
to hero-form.component.html in the <select>
element made it work
How to remove the default arrow icon from a dropdown list (select element)?
Just wanted to complete the thread.
To be very clear this does not works in IE9, however we can do it by little css trick.
<div class="customselect">
<select>
<option>2000</option>
<option>2001</option>
<option>2002</option>
</select>
</div>
.customselect {
width: 80px;
overflow: hidden;
border:1px solid;
}
.customselect select {
width: 100px;
border:none;
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
}
Bootstrap 3 select input form inline
This is how I made it without extra css or jquery:
<div class="form-group">
<div class="input-group">
<label class="sr-only" for="extra3">Extra name 3</label>
<input type="text" id="extra3" class="form-control" placeholder="Extra name">
<span class="input-group-addon">
<label class="checkbox-inline">
Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
</label>
</span>
<span class="input-group-addon">
<label class="checkbox-inline">
Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
</label>
</span>
<span class="input-group-addon">
To be paid?
<select>
<option value="online">Online</option>
<option value="on spot">On Spot</option>
</select>
</span>
</div>
</div>
Change <select>'s option and trigger events with JavaScript
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
How do I clear all options in a dropdown box?
The items should be removed in reverse, otherwise it will cause an error. Also, I do not recommended simply setting the values to null
, as that may cause unexpected behaviour.
var select = document.getElementById("myselect");
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
Or if you prefer, you can make it a function:
function clearOptions(id)
{
var select = document.getElementById(id);
for (var i = select.options.length - 1 ; i >= 0 ; i--)
select.remove(i);
}
clearOptions("myselect");
Set width of dropdown element in HTML select dropdown options
On the server-side:
- Define a max length of the string
- Clip the string
- (optional) append horizontal ellipsis
Alternative solution: the select element is in your case (only guessing) a single-choice form control and you could use a group of radio buttons instead. These you could then style with better control. If you have a select[@multiple] you could do the same with a group of checkboxes instead as they can both be seen as a multiple-choice form control.
How to style a select tag's option element?
Unfortunately, WebKit browsers do not support styling of <option>
tags yet, except for color
and background-color
.
The most widely used cross browser solution is to use <ul>
/ <li>
and style them using CSS. Frameworks like Bootstrap do this well.
What is the best way to add options to a select from a JavaScript object with jQuery?
$.each
is slower than a for
loop
- Each time, a DOM selection is not the best practice in loop
$("#mySelect").append();
So the best solution is the following
If JSON data resp
is
[
{"id":"0001", "name":"Mr. P"},
{"id":"0003", "name":"Mr. Q"},
{"id":"0054", "name":"Mr. R"},
{"id":"0061", "name":"Mr. S"}
]
use it as
var option = "";
for (i=0; i<resp.length; i++) {
option += "<option value='" + resp[i].id + "'>" + resp[i].name + "</option>";
}
$('#mySelect').html(option);
Height of an HTML select box (dropdown)
Confirmed.
The part that drops down is set to either:
- The height needed to show all entries, or
- The height needed to show
x
entries (with scrollbars to see remaining), where x
is
- 20 in Firefox & Chrome
- 30 in IE 6, 7, 8
- 16 for Opera 10
- 14 for Opera 11
- 22 for Safari 4
- 18 for Safari 5
- 11 in IE 5.0, 5.5
- In IE/Edge, if there are no options, a stupidly high list of 11 blanks entries.
For (3) above you can see the results in this JSFiddle
Remove Select arrow on IE
I would suggest mine solution that you can find in this GitHub repo.
This works also for IE8 and IE9 with a custom arrow that comes from an icon font.
Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.
Anyway, let's start with the modern browsers and then we will see the solution for the older ones.
Drop-down Arrow for Chrome, Firefox, Opera, Internet Explorer 10+
For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.
To do so, you have to reset the browser's default style for the select
tag and set new background rules (like suggested before).
select {
/* you should keep these firsts rules in place to maintain cross-browser behaviour */
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance: none;
background-image: url('<custom_arrow_image_url_here>');
background-position: 98% center;
background-repeat: no-repeat;
outline: none;
...
}
The appearance
rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.
The background
rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).
In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline
. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.
Drop-down Arrow for Internet Explorer 8 (IE8) and Internet Explorer 9 (IE9) using Icon Font
This is the harder part... Or maybe not.
There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand
for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select
CSS rule for more details about the inline SVG used).
The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html
tag to recognize the older IE browser.
After that, every select
in the HTML have to be wrapped by a div
(or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.
<div class="selectTagWrapper prefix-icon-arrow-down-fill">
...
</div>
In easy words, this wrapper is used to simulate the select
tag.
To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select
.
Notice that we cannot use the select
border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden
rule applied to the select
itself.
The custom arrow icon-font is placed in the pseudo class :before
where the rule content
contains the reference for the arrow (in this case it is a right parenthesis).
We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).
.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
content: ")";
position: absolute;
top: 43%;
left: 93%;
font-size: 6px;
...
}
You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image
rule or making a new icon font file by yourself.
How to expand 'select' option width after the user wants to select an option
This mimics most of the behavior your looking for:
<!--
I found this works fairly well.
-->
<!-- On page load, be sure that something else has focus. -->
<body onload="document.getElementById('name').focus();">
<input id=name type=text>
<!-- This div is for demonstration only. The parent container may be anything -->
<div style="height:50; width:100px; border:1px solid red;">
<!-- Note: static width, absolute position but no top or left specified, Z-Index +1 -->
<select
style="width:96px; position:absolute; z-index:+1;"
onactivate="this.style.width='auto';"
onchange="this.blur();"
onblur="this.style.width='96px';">
<!-- "activate" happens before all else and "width='auto'" expands per content -->
<!-- Both making a selection and moving to another control should return static width -->
<option>abc</option>
<option>abcdefghij</option>
<option>abcdefghijklmnop</option>
<option>abcdefghijklmnopqrstuvwxyz</option>
</select>
</div>
</body>
</html>
This will override some of the key-press behavior.
Change border color on <select> HTML form
I would consinder enclosing that select block within a div block and setting the border property like this:
_x000D_
_x000D_
<div style="border: 2px solid blue;">_x000D_
<select style="width: 100%;">_x000D_
<option value="Sal">Sal</option>_x000D_
<option value="Awesome">Awesome!</option>_x000D_
</select>_x000D_
</div>
_x000D_
_x000D_
_x000D_
You should be able to play with that to accomplish what you need.
Is there an onSelect event or equivalent for HTML <select>?
To properly fire an event every time the user selects something(even the same option), you just need to trick the select box.
Like others have said, specify a negative selectedIndex
on focus to force the change event. While this does allow you to trick the select box, it won't work after that as long as it still has focus. The simple fix is to force the select box to blur, shown below.
Standard JS/HTML:
<select onchange="myCallback();" onfocus="this.selectedIndex=-1;this.blur();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
jQuery Plugin:
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script type="text/javascript">
$.fn.alwaysChange = function(callback) {
return this.each(function(){
var elem = this;
var $this = $(this);
$this.change(function(){
if(callback) callback($this.val());
}).focus(function(){
elem.selectedIndex = -1;
elem.blur();
});
});
}
$('select').alwaysChange(function(val){
// Optional change event callback,
// shorthand for $('select').alwaysChange().change(function(){});
});
</script>
You can see a working demo here.
How to use Checkbox inside Select Option
Try multiple-select, especially multiple-items. Looks to be much clean and managed solution, with tons of examples. You can also view the source.
<div>
<div class="form-group row">
<label class="col-sm-2">
Basic Select
</label>
<div class="col-sm-10">
<select multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2">
Group Select
</label>
<div class="col-sm-10">
<select multiple="multiple">
<optgroup label="Group 1">
<option value="1">1</option>
<option value="2">2</option>
</optgroup>
<optgroup label="Group 2">
<option value="6">6</option>
<option value="7">7</option>
</optgroup>
<optgroup label="Group 3">
<option value="11">11</option>
<option value="12">12</option>
</optgroup>
</select>
</div>
</div>
</div>
<script>
$(function() {
$('select').multipleSelect({
multiple: true,
multipleWidth: 60
})
})
</script>
Set select option 'selected', by value
You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue]
, so in your case you can select the option and set the selected attribute.
$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);
Where value
is the value you wish to select by.
If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute
$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
.prop("selected",true);
Get drop down value
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
How do I make a placeholder for a 'select' box?
I had the same problem and while searching I came across this question, and after I found a good solution for me, I would like to share it with you guys in case some one can benefit from it.
Here it is:
HTML:
<select class="place_holder dropdown">
<option selected="selected" style=" display: none;">Sort by</option>
<option>two</option>
<option>something</option>
<option>4</option>
<option>5</option>
</select>
CSS:
.place_holder {
color: gray;
}
option {
color: #000000;
}
JavaScript:
jQuery(".dropdown").change(function () {
jQuery(this).removeClass("place_holder");
});
After the customer makes the first select, there isn't any need for gray color, so the JavaScript code removes the class place_holder
.
Thanks to @user1096901, as a workaround for the Internet Explorer browser, you can add the place_holder
class again in case the first option is selected again :)
How to select a drop-down menu value with Selenium using Python?
You don't have to click anything.
Use find by xpath or whatever you choose and then use send keys
For your example:
HTML:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
Python:
fruit_field = browser.find_element_by_xpath("//input[@name='fruits']")
fruit_field.send_keys("Mango")
That's it.
How to show disable HTML select option in by default?
If you are using jQuery to fill your select element, you can use this:
html
<select id="tagging"></select>
js
array_of_options = ['Choose Tagging', 'Option A', 'Option B', 'Option C']
$.each(array_of_options, function(i, item) {
if(i==0) { sel_op = 'selected'; dis_op = 'disabled'; } else { sel_op = ''; dis_op = ''; }
$('<option ' + sel_op + ' ' + dis_op + '/>').val(item).html(item).appendTo('#tagging');
})
This will allow the user to see the first option as a disabled heading ('Choose Tagging'), and select all other options.
How to set the 'selected option' of a select dropdown list with jquery
_x000D_
_x000D_
$(document).ready(function() {_x000D_
$('#YourID option[value="3"]').attr("selected", "selected");_x000D_
$('#YourID option:selected').attr("selected",null);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
<option value="1">A</option>_x000D_
<option value="2">B</option>_x000D_
<option value="3">C</option>_x000D_
<option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_
Hide options in a select list using jQuery
Here is my spin, likely a bit faster due to native DOM methods
$.each(results['hide'], function(name, title) {
$(document.getElementById('edit-field-service-sub-cat-value').options).each(function(index, option) {
if( option.value == title ) {
option.hidden = true; // not fully compatible. option.style.display = 'none'; would be an alternative or $(option).hide();
}
});
});
How to fire a change event on a HTMLSelectElement if the new value is the same as the old?
You have to add empty option to solve it,
I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.
<select onChange="jsFunction()" id="selectOpt">
<option value="1" onclick="jsFunction()">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
alert(myselect.options[myselect.selectedIndex].value);
}
How to style the <option> with only CSS?
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
How to use a Bootstrap 3 glyphicon in an html select
To my knowledge the only way to achieve this in a native select would be to use the unicode representations of the font. You'll have to apply the glyphicon font to the select and as such can't mix it with other fonts. However, glyphicons include regular characters, so you can add text. Unfortunately setting the font for individual options doesn't seem to be possible.
<select class="form-control glyphicon">
<option value="">− − − Hello</option>
<option value="glyphicon-list-alt"> Text</option>
</select>
Here's a list of the icons with their unicode:
http://glyphicons.bootstrapcheatsheets.com/
How to change options of <select> with jQuery?
I threw CMS's excellent answer into a quick jQuery extension:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
Get selected key/value of a combo box using jQuery
I assume by "key" and "value" you mean:
<select>
<option value="KEY">VALUE</option>
</select>
If that's the case, this will get you the "VALUE":
$(this).find('option:selected').text();
And you can get the "KEY" like this:
$(this).find('option:selected').val();
How to clear exisiting dropdownlist items when its content changes?
just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal
e As EventArgs)
//ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub
and it worked just fine
HTML Form: Select-Option vs Datalist-Option
I noticed that there is no selected feature in datalist. It only gives you choice but can't have a default option. You can't show the selected option on the next page either.
How to use jQuery to select a dropdown option?
$('select>option:eq(3)').attr('selected', 'selected');
One caveat here is if you have javascript watching for select/option's change event you need to add .trigger('change')
so the code become.
$('select>option:eq(3)').attr('selected', 'selected').trigger('change');
because only calling .attr('selected', 'selected')
does not trigger the event
How can change width of dropdown list?
Try this code:
<select name="wgtmsr" id="wgtmsr">
<option value="kg">Kg</option>
<option value="gm">Gm</option>
<option value="pound">Pound</option>
<option value="MetricTon">Metric ton</option>
<option value="litre">Litre</option>
<option value="ounce">Ounce</option>
</select>
CSS:
#wgtmsr{
width:150px;
}
If you want to change the width of the option you can do this in your css:
#wgtmsr option{
width:150px;
}
Maybe you have a conflict in your css rules that override the width of your select
DEMO
Editable 'Select' element
Similar to answer above but without the absolute positioning:
<select style="width: 200px; float: left;" onchange="this.nextElementSibling.value=this.value">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input style="width: 185px; margin-left: -199px; margin-top: 1px; border: none; float: left;"/>
So create a input box and put it over the top of the combobox
jQuery Set Selected Option Using Next
Find the row, then
var row = $('#yourTable');
the value you want to select
var theValue = "5";
row.find("select:eq(2)").find("option[value="+theValue+']').attr('selected','selected');
Javascript to Select Multiple options
This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:
var values = ["Red", "Green"],
colors = document.getElementById("colors");
_.each(colors.options, function (option) {
option.selected = ~_.indexOf(values, option.text);
});
If you're using jQuery, it could be even more terse:
var values = ["Red", "Green"];
$("#colors option").prop("selected", function () {
return ~$.inArray(this.text, values);
});
If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:
var color, i, j,
values = ["Red", "Green"],
options = document.getElementById("colors").options;
for ( i = 0; i < values.length; i++ ) {
for ( j = 0, color = values[i]; j < options.length; j++ ) {
options[j].selected = options[j].selected || color === options[j].text;
}
}
How to add Drop-Down list (<select>) programmatically?
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
Pure Javascript Create Element Solution
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
This can be highly customized to suit your project!
How to get equal width of input and select fields
I tried Gaby's answer (+1) above but it only partially solved my problem. Instead I used the following CSS, where content-box was changed to border-box:
input, select {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
Path to MSBuild
This powershell method gets the path to msBuild from multiple sources. Trying in order:
First using vswhere (because Visual Studio seems to have more up to date versions of msBuild) e.g.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe
If not found trying the registry (framework version) e.g.
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
Powershell code:
Function GetMsBuildPath {
Function GetMsBuildPathFromVswhere {
# Based on https://github.com/microsoft/vswhere/wiki/Find-MSBuild/62adac8eb22431fa91d94e03503d76d48a74939c
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$path = & $vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath
if ($path) {
$tool = join-path $path 'MSBuild\Current\Bin\MSBuild.exe'
if (test-path $tool) {
return $tool
}
$tool = join-path $path 'MSBuild\15.0\Bin\MSBuild.exe'
if (test-path $tool) {
return $tool
}
}
}
Function GetMsBuildPathFromRegistry {
# Based on Martin Brandl's answer: https://stackoverflow.com/a/57214958/146513
$msBuildDir = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\' |
Get-ItemProperty -Name MSBuildToolsPath |
Sort-Object PSChildName |
Select-Object -ExpandProperty MSBuildToolsPath -last 1
$msBuildPath = join-path $msBuildDir 'msbuild.exe'
if (test-path $msBuildPath) {
return $msBuildPath
}
}
$msBuildPath = GetMsBuildPathFromVswhere
if (-Not $msBuildPath) {
$msBuildPath = GetMsBuildPathFromRegistry
}
return $msBuildPath
}
Change old commit message on Git
As Gregg Lind suggested, you can use reword to be prompted to only change the commit message (and leave the commit intact otherwise):
git rebase -i HEAD~n
Here, n
is the list of last n commits.
For example, if you use git rebase -i HEAD~4
, you may see something like this:
pick e459d80 Do xyz
pick 0459045 Do something
pick 90fdeab Do something else
pick facecaf Do abc
Now replace pick with reword for the commits you want to edit the messages of:
pick e459d80 Do xyz
reword 0459045 Do something
reword 90fdeab Do something else
pick facecaf Do abc
Exit the editor after saving the file, and next you will be prompted to edit the messages for the commits you had marked reword, in one file per message. Note that it would've been much simpler to just edit the commit messages when you replaced pick
with reword
, but doing that has no effect.
Learn more on GitHub's page for Changing a commit message.
Getting HTTP code in PHP using curl
use this hitCurl method for fetch all type of api response i.e. Get / Post
function hitCurl($url,$param = [],$type = 'POST'){
$ch = curl_init();
if(strtoupper($type) == 'GET'){
$param = http_build_query((array)$param);
$url = "{$url}?{$param}";
}else{
curl_setopt_array($ch,[
CURLOPT_POST => (strtoupper($type) == 'POST'),
CURLOPT_POSTFIELDS => (array)$param,
]);
}
curl_setopt_array($ch,[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
]);
$resp = curl_exec($ch);
$statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'statusCode' => $statusCode,
'resp' => $resp
];
}
Demo function to test api
function fetchApiData(){
$url = 'https://postman-echo.com/get';
$resp = $this->hitCurl($url,[
'foo1'=>'bar1',
'foo2'=>'bar2'
],'get');
$apiData = "Getting header code {$resp['statusCode']}";
if($resp['statusCode'] == 200){
$apiData = json_decode($resp['resp']);
}
echo "<pre>";
print_r ($apiData);
echo "</pre>";
}
Apache redirect to another port
This might be an old question, but here's what I did:
In a .conf file loaded by apache:
<VirtualHost *:80>
ServerName something.com
ProxyPass / http://localhost:8080/
</VirtualHost>
Explanation: Listen on all requests to the local machine's port 80. If I requested "http://something.com/somethingorother
", forward that request to "http://localhost:8080/somethingorother
". This should work for an external visitor because, according to the docs, it maps the remote request to the local server's space.
I'm running Apache 2.4.6-2ubuntu2.2, so I'm not sure how the "-2ubuntu2.2" affects the wider applicability of this answer.
After you make these changes, add the needed modules and restart apache
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart
Calculating Covariance with Python and Numpy
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
How do I center a window onscreen in C#?
In Windows Forms:
this.StartPosition = FormStartPosition.CenterScreen;
In WPF:
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
That's all you have to do...
Use JAXB to create Object from XML String
To pass XML content, you need to wrap the content in a Reader
, and unmarshal that instead:
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);
Add JsonArray to JsonObject
here is simple code
List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
obj.put("result", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());
How to include layout inside layout?
Try this
<include
android:id="@+id/OnlineOffline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
layout="@layout/YourLayoutName" />
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Make Bootstrap 3 Tabs Responsive
The solution is just 3 lines:
@media only screen and (max-width: 479px) {
.nav-tabs > li {
width: 100%;
}
}
..but you have to accept the idea of tabs that wrap to more lines in other dimensions.
Of course you can achieve a horizontal scrolling area with white-space: nowrap
trick but the scrollbars look ugly on desktops so you have to write js code and the whole thing starts becoming no trivial at all!
Why would we call cin.clear() and cin.ignore() after reading input?
The cin.clear()
clears the error flag on cin
(so that future I/O operations will work correctly), and then cin.ignore(10000, '\n')
skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.
Observable Finally on Subscribe
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
Quicksort: Choosing the pivot
Never ever choose a fixed pivot - this can be attacked to exploit your algorithm's worst case O(n2) runtime, which is just asking for trouble. Quicksort's worst case runtime occurs when partitioning results in one array of 1 element, and one array of n-1 elements. Suppose you choose the first element as your partition. If someone feeds an array to your algorithm that is in decreasing order, your first pivot will be the biggest, so everything else in the array will move to the left of it. Then when you recurse, the first element will be the biggest again, so once more you put everything to the left of it, and so on.
A better technique is the median-of-3 method, where you pick three elements at random, and choose the middle. You know that the element that you choose won't be the the first or the last, but also, by the central limit theorem, the distribution of the middle element will be normal, which means that you will tend towards the middle (and hence, nlog(n) time).
If you absolutely want to guarantee O(nlog(n)) runtime for the algorithm, the columns-of-5 method for finding the median of an array runs in O(n) time, which means that the recurrence equation for quicksort in the worst case will be:
T(n) = O(n) (find the median) + O(n) (partition) + 2T(n/2) (recurse left and right)
By the Master Theorem, this is O(nlog(n)). However, the constant factor will be huge, and if worst case performance is your primary concern, use a merge sort instead, which is only a little bit slower than quicksort on average, and guarantees O(nlog(n)) time (and will be much faster than this lame median quicksort).
Explanation of the Median of Medians Algorithm
SQL Server CTE and recursion example
Would like to outline a brief semantic parallel to an already correct answer.
In 'simple' terms, a recursive CTE can be semantically defined as the following parts:
1: The CTE query. Also known as ANCHOR.
2: The recursive CTE query on the CTE in (1) with UNION ALL (or UNION or EXCEPT or INTERSECT) so the ultimate result is accordingly returned.
3: The corner/termination condition. Which is by default when there are no more rows/tuples returned by the recursive query.
A short example that will make the picture clear:
;WITH SupplierChain_CTE(supplier_id, supplier_name, supplies_to, level)
AS
(
SELECT S.supplier_id, S.supplier_name, S.supplies_to, 0 as level
FROM Supplier S
WHERE supplies_to = -1 -- Return the roots where a supplier supplies to no other supplier directly
UNION ALL
-- The recursive CTE query on the SupplierChain_CTE
SELECT S.supplier_id, S.supplier_name, S.supplies_to, level + 1
FROM Supplier S
INNER JOIN SupplierChain_CTE SC
ON S.supplies_to = SC.supplier_id
)
-- Use the CTE to get all suppliers in a supply chain with levels
SELECT * FROM SupplierChain_CTE
Explanation:
The first CTE query returns the base suppliers (like leaves) who do not supply to any other supplier directly (-1)
The recursive query in the first iteration gets all the suppliers who supply to the suppliers returned by the ANCHOR.
This process continues till the condition returns tuples.
UNION ALL returns all the tuples over the total recursive calls.
Another good example can be found here.
PS: For a recursive CTE to work, the relations must have a hierarchical (recursive) condition to work on. Ex: elementId = elementParentId.. you get the point.
Printing out a linked list using toString
I do it the following way:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
StringBuilder result = new StringBuilder();
for(Object item:this) {
result.append(item.toString());
result.append("\n"); //optional
}
return result.toString();
}
What is the preferred Bash shebang?
/bin/sh
is usually a link to the system's default shell, which is often bash
but on, e.g., Debian systems is the lighter weight dash
. Either way, the original Bourne shell is sh
, so if your script uses some bash
(2nd generation, "Bourne Again sh") specific features ([[ ]]
tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.
Also note that when evoked as sh
, bash
to some extent behaves as POSIX standard sh
(see also the GNU docs about this).
Chain-calling parent initialisers in python
You can simply write :
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Initialiser B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Initialiser C was called"
How do I get Maven to use the correct repositories?
By default, Maven will always look in the official Maven repository, which is http://repo1.maven.org.
When Maven tries to build a project, it will look in your local repository (by default ~/.m2/repository
but you can configure it by changing the <localRepository>
value in your ~/.m2/settings.xml
) to find any dependency, plugin or report defined in your pom.xml
. If the adequate artifact is not found in your local repository, it will look in all external repositories configured, starting with the default one, http://repo1.maven.org.
You can configure Maven to avoid this default repository by setting a mirror in your settings.xml
file:
<mirrors>
<mirror>
<id>repoMirror</id>
<name>Our mirror for Maven repository</name>
<url>http://the/server/</url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
This way, instead of contacting http://repo1.maven.org
, Maven will contact your entreprise repository (http://the/server
in this example).
If you want to add another repository, you can define a new one in your settings.xml file:
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>foo.bar</id>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
<url>http://new/repository/server</url>
</repository>
</repositories>
You can see the complete settings.xml
model here.
Concerning the clean
process, you can ask Maven to run it offline. In this case, Maven will not try to reach any external repositories:
mvn -o clean
Subtracting two lists in Python
Python 2.7 and 3.2 added the collections.Counter
class, which is a dictionary subclass that maps elements to the number of occurrences of the element. This can be used as a multiset. You can do something like this:
from collections import Counter
a = Counter([0, 1, 2, 1, 0])
b = Counter([0, 1, 1])
c = a - b # ignores items in b missing in a
print(list(c.elements())) # -> [0, 2]
As well, if you want to check that every element in b
is in a
:
# a[key] returns 0 if key not in a, instead of raising an exception
assert all(a[key] >= b[key] for key in b)
But since you are stuck with 2.5, you could try importing it and define your own version if that fails. That way you will be sure to get the latest version if it is available, and fall back to a working version if not. You will also benefit from speed improvements if if gets converted to a C implementation in the future.
try:
from collections import Counter
except ImportError:
class Counter(dict):
...
You can find the current Python source here.
How does createOrReplaceTempView work in Spark?
SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.
In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.
In order to create the view, developer need an utility called createOrReplaceTempView
How to get all options in a drop-down list by Selenium WebDriver using C#?
Here is code in Java to get all options in dropdown list.
WebElement sel = myD.findElement(By.name("dropdown_name"));
List<WebElement> lists = sel.findElements(By.tagName("option"));
for(WebElement element: lists)
{
String var2 = tdElement.getText();
System.out.println(var2);
}
Hope it may helpful to someone.
Setting up an MS-Access DB for multi-user access
Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.
What is monkey patching?
According to Wikipedia:
In Python, the term monkey patch only
refers to dynamic modifications of a
class or module at runtime, motivated
by the intent to patch existing
third-party code as a workaround to a
bug or feature which does not act as
you desire.
Getting session value in javascript
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
Vue.js unknown custom element
I had the same error
[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
however, I totally forgot to run npm install && npm run dev
to compiling the js files.
maybe this helps newbies like me.
Create table variable in MySQL
MYSQL 8 does, in a way:
MYSQL 8 supports JSON tables, so you could load your results into a JSON variable and select from that variable using the JSON_TABLE() command.
Unsupported operand type(s) for +: 'int' and 'str'
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
Default optional parameter in Swift function
in case you need to use a bool param, you need just to assign the default value.
func test(WithFlag flag: Bool = false){.....}
then you can use without or with the param:
test() //here flag automatically has the default value: false
test(WithFlag: true) //here flag has the value: true
How can I use a DLL file from Python?
Maybe with Dispatch
:
from win32com.client import Dispatch
zk = Dispatch("zkemkeeper.ZKEM")
Where zkemkeeper is a registered DLL file on the system...
After that, you can access functions just by calling them:
zk.Connect_Net(IP_address, port)
How do I create an Excel chart that pulls data from multiple sheets?
Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:
Sub createAllGraphs()
Const chartWidth As Integer = 260
Const chartHeight As Integer = 200
If Sheets.Count = 1 Then
Sheets.Add , Sheets(1)
Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)
Dim i As Integer
Dim chartX As Integer
Dim chartY As Integer
Dim r As Integer
r = 2
Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2
Dim lastTime As Boolean
lastTime = False
Do While s.Range("A" & r) <> ""
If curC <> s.Range("C" & r) Then
If r <> 2 Then
seriesAdd:
c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
If lastTime = True Then GoTo postLoop
End If
If curB <> s.Range("B" & r).Value Then
If curA <> s.Range("A" & r).Value Then
chartX = chartX + chartWidth * 2
chartY = 0
curA = s.Range("A" & r)
End If
Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
Set c = c.Chart
c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")
Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
Set c2 = c2.Chart
c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")
chartY = chartY + chartHeight
curB = s.Range("B" & r)
curC = s.Range("C" & r)
End If
curC = s.Range("C" & r)
startR = r
End If
If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
r = r + 1
Loop
lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate
End Sub
Why do we have to override the equals() method in Java?
By default .equals() uses == identity function to compare which obviously doesn't work as the instances test1 and test2 are not the same. == only works with primitive data types like int or string. So you need to override it to make it work by comparing all the member variables of the Test class
how to convert string into dictionary in python 3.*?
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
How to call C++ function from C?
I would do it in the following way:
(If working with MSVC, ignore the GCC compilation commands)
Suppose that I have a C++ class named AAA, defined in files aaa.h, aaa.cpp, and that the class AAA has a method named sayHi(const char *name), that I want to enable for C code.
The C++ code of class AAA - Pure C++, I don't modify it:
aaa.h
#ifndef AAA_H
#define AAA_H
class AAA {
public:
AAA();
void sayHi(const char *name);
};
#endif
aaa.cpp
#include <iostream>
#include "aaa.h"
AAA::AAA() {
}
void AAA::sayHi(const char *name) {
std::cout << "Hi " << name << std::endl;
}
Compiling this class as regularly done for C++. This code "does not know" that it is going to be used by C code. Using the command:
g++ -fpic -shared aaa.cpp -o libaaa.so
Now, also in C++, creating a C connector. Defining it in files aaa_c_connector.h, aaa_c_connector.cpp. This connector is going to define a C function, named AAA_sayHi(cosnt char *name), that will use an instance of AAA and will call its method:
aaa_c_connector.h
#ifndef AAA_C_CONNECTOR_H
#define AAA_C_CONNECTOR_H
#ifdef __cplusplus
extern "C" {
#endif
void AAA_sayHi(const char *name);
#ifdef __cplusplus
}
#endif
#endif
aaa_c_connector.cpp
#include <cstdlib>
#include "aaa_c_connector.h"
#include "aaa.h"
#ifdef __cplusplus
extern "C" {
#endif
// Inside this "extern C" block, I can implement functions in C++, which will externally
// appear as C functions (which means that the function IDs will be their names, unlike
// the regular C++ behavior, which allows defining multiple functions with the same name
// (overloading) and hence uses function signature hashing to enforce unique IDs),
static AAA *AAA_instance = NULL;
void lazyAAA() {
if (AAA_instance == NULL) {
AAA_instance = new AAA();
}
}
void AAA_sayHi(const char *name) {
lazyAAA();
AAA_instance->sayHi(name);
}
#ifdef __cplusplus
}
#endif
Compiling it, again, using a regular C++ compilation command:
g++ -fpic -shared aaa_c_connector.cpp -L. -laaa -o libaaa_c_connector.so
Now I have a shared library (libaaa_c_connector.so), that implements the C function AAA_sayHi(const char *name). I can now create a C main file and compile it all together:
main.c
#include "aaa_c_connector.h"
int main() {
AAA_sayHi("David");
AAA_sayHi("James");
return 0;
}
Compiling it using a C compilation command:
gcc main.c -L. -laaa_c_connector -o c_aaa
I will need to set LD_LIBRARY_PATH to contain $PWD, and if I run the executable ./c_aaa, I will get the output I expect:
Hi David
Hi James
EDIT:
On some linux distributions, -laaa
and -lstdc++
may also be required for the last compilation command. Thanks to @AlaaM. for the attention
Select all 'tr' except the first one
Sorry I know this is old but why not style all tr elements the way you want all except the first and the use the psuedo class :first-child where you revoke what you specified for all tr elements.
Better descriped by this example:
http://jsfiddle.net/DWTr7/1/
tr {
border-top: 1px solid;
}
tr:first-child {
border-top: none;
}
/Patrik
How to use PHP's password_hash to hash and verify passwords
There is a distinct lack of discussion on backwards and forwards compatibility that is built in to PHP's password functions. Notably:
- Backwards Compatibility: The password functions are essentially a well-written wrapper around
crypt()
, and are inherently backwards-compatible with crypt()
-format hashes, even if they use obsolete and/or insecure hash algorithms.
- Forwards Compatibilty: Inserting
password_needs_rehash()
and a bit of logic into your authentication workflow can keep you your hashes up to date with current and future algorithms with potentially zero future changes to the workflow. Note: Any string that does not match the specified algorithm will be flagged for needing a rehash, including non-crypt-compatible hashes.
Eg:
class FakeDB {
public function __call($name, $args) {
printf("%s::%s(%s)\n", __CLASS__, $name, json_encode($args));
return $this;
}
}
class MyAuth {
protected $dbh;
protected $fakeUsers = [
// old crypt-md5 format
1 => ['password' => '$1$AVbfJOzY$oIHHCHlD76Aw1xmjfTpm5.'],
// old salted md5 format
2 => ['password' => '3858f62230ac3c915f300c664312c63f', 'salt' => 'bar'],
// current bcrypt format
3 => ['password' => '$2y$10$3eUn9Rnf04DR.aj8R3WbHuBO9EdoceH9uKf6vMiD7tz766rMNOyTO']
];
public function __construct($dbh) {
$this->dbh = $dbh;
}
protected function getuser($id) {
// just pretend these are coming from the DB
return $this->fakeUsers[$id];
}
public function authUser($id, $password) {
$userInfo = $this->getUser($id);
// Do you have old, turbo-legacy, non-crypt hashes?
if( strpos( $userInfo['password'], '$' ) !== 0 ) {
printf("%s::legacy_hash\n", __METHOD__);
$res = $userInfo['password'] === md5($password . $userInfo['salt']);
} else {
printf("%s::password_verify\n", __METHOD__);
$res = password_verify($password, $userInfo['password']);
}
// once we've passed validation we can check if the hash needs updating.
if( $res && password_needs_rehash($userInfo['password'], PASSWORD_DEFAULT) ) {
printf("%s::rehash\n", __METHOD__);
$stmt = $this->dbh->prepare('UPDATE users SET pass = ? WHERE user_id = ?');
$stmt->execute([password_hash($password, PASSWORD_DEFAULT), $id]);
}
return $res;
}
}
$auth = new MyAuth(new FakeDB());
for( $i=1; $i<=3; $i++) {
var_dump($auth->authuser($i, 'foo'));
echo PHP_EOL;
}
Output:
MyAuth::authUser::password_verify
MyAuth::authUser::rehash
FakeDB::prepare(["UPDATE users SET pass = ? WHERE user_id = ?"])
FakeDB::execute([["$2y$10$zNjPwqQX\/RxjHiwkeUEzwOpkucNw49yN4jjiRY70viZpAx5x69kv.",1]])
bool(true)
MyAuth::authUser::legacy_hash
MyAuth::authUser::rehash
FakeDB::prepare(["UPDATE users SET pass = ? WHERE user_id = ?"])
FakeDB::execute([["$2y$10$VRTu4pgIkGUvilTDRTXYeOQSEYqe2GjsPoWvDUeYdV2x\/\/StjZYHu",2]])
bool(true)
MyAuth::authUser::password_verify
bool(true)
As a final note, given that you can only re-hash a user's password on login you should consider "sunsetting" insecure legacy hashes to protect your users. By this I mean that after a certain grace period you remove all insecure [eg: bare MD5/SHA/otherwise weak] hashes and have your users rely on your application's password reset mechanisms.
What is the best way to modify a list in a 'foreach' loop?
The collection used in foreach is immutable. This is very much by design.
As it says on MSDN:
The foreach statement is used to
iterate through the collection to get
the information that you want, but can
not be used to add or remove items
from the source collection to avoid
unpredictable side effects. If you
need to add or remove items from the
source collection, use a for loop.
The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.
Using Git, show all commits that are in one branch, but not the other(s)
Start to Create a Pull Request via the git hosting service you're using. If the branch has been fully merged into the base branch, you'll be unable to create the new PR.
You don't need to actually make the pull request, just use the first step where you pick branches.
For example, on GitHub:
There isn't anything to compare
This doesn't use git on the command line, but I often find it's helpful to use the other tools at your disposal with a clear mental model rather than attempt to remember another arcane git command.
Center div on the middle of screen
Try this:
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: red;
}
Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.
In reactJS, how to copy text to clipboard?
copyclip = (item) => {
var textField = document.createElement('textarea')
textField.innerText = item
document.body.appendChild(textField)
textField.select()
document.execCommand('copy')
this.setState({'copy':"Copied"});
textField.remove()
setTimeout(() => {
this.setState({'copy':""});
}, 1000);
}
<span className="cursor-pointer ml-1" onClick={()=> this.copyclip(passTextFromHere)} >Copy</span> <small>{this.state.copy}</small>
Check if string matches pattern
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
I believe that should work for an uppercase, number pattern.
ExecuteNonQuery: Connection property has not been initialized.
A couple of things wrong here.
Do you really want to open and close the connection for every single log entry?
Shouldn't you be using SqlCommand
instead of SqlDataAdapter
?
The data adapter (or SqlCommand
) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).
I highly recommend a C# / SQL Server tutorial.
Relative path to absolute path in C#?
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Eclipse - java.lang.ClassNotFoundException
I had the same problem. All what I did was,
i). Generated Eclipse artifacts
mvn clean eclipse:eclipse
ii). Refresh the project and rerun your junit test. Should work fine.
Change status bar text color to light in iOS 9 with Objective-C
Using a UINavigationController
and setting its navigation bar's barStyle
to .Black
. past this line in your AppDelegate.m
file.
navigationController.navigationBar.barStyle = UIBarStyleBlack;
If you are not using UINavigationController
then add following code in your ViewController.m
file.
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
And call the method to this line :
[self setNeedsStatusBarAppearanceUpdate];
How do I check if an object's type is a particular subclass in C++?
dynamic_cast
can determine if the type contains the target type anywhere in the inheritance hierarchy (yes, it's a little-known feature that if B
inherits from A
and C
, it can turn an A*
directly into a C*
). typeid()
can determine the exact type of the object. However, these should both be used extremely sparingly. As has been mentioned already, you should always be avoiding dynamic type identification, because it indicates a design flaw. (also, if you know the object is for sure of the target type, you can do a downcast with a static_cast
. Boost offers a polymorphic_downcast
that will do a downcast with dynamic_cast
and assert
in debug mode, and in release mode it will just use a static_cast
).
How to fix Warning Illegal string offset in PHP
Magic word is: isset
Validate the entry:
if(isset($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)
I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.
I had no luck with any of the above methods.
I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.
This is working very well for me.
(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf
javax.persistence.NoResultException: No entity found for query
Another option is to use uniqueResultOptional() method, which gives you Optional in result:
String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());
Optional<DrawUnusedBalance> drawUnusedBalance=query.uniqueResultOptional();
How do I handle newlines in JSON?
According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:
A string is a sequence of Unicode code points wrapped with quotation marks
(U+0022
). All characters may be placed within the quotation marks except for the
characters that must be escaped: quotation mark (U+0022
), reverse solidus
(U+005C
), and the control characters U+0000
to U+001F
. There are two-character
escape sequence representations of some characters.
So you can't pass 0x0A
or 0x0C
codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000
to U+001F
:
\f
represents the form feed character (U+000C
).
\n
represents the line feed character (U+000A
).
As most of programming languages uses \
for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):
jsonStr = "{ \"name\": \"Multi\\nline.\" }";
How can I use break or continue within for loop in Twig template?
A way to be able to use {% break %}
or {% continue %}
is to write TokenParser
s for them.
I did it for the {% break %}
token in the code below. You can, without much modifications, do the same thing for the {% continue %}
.
AppBundle\Twig\AppExtension.php:
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
function getTokenParsers() {
return array(
new BreakToken(),
);
}
public function getName()
{
return 'app_extension';
}
}
AppBundle\Twig\BreakToken.php:
namespace AppBundle\Twig;
class BreakToken extends \Twig_TokenParser
{
public function parse(\Twig_Token $token)
{
$stream = $this->parser->getStream();
$stream->expect(\Twig_Token::BLOCK_END_TYPE);
// Trick to check if we are currently in a loop.
$currentForLoop = 0;
for ($i = 1; true; $i++) {
try {
// if we look before the beginning of the stream
// the stream will throw a \Twig_Error_Syntax
$token = $stream->look(-$i);
} catch (\Twig_Error_Syntax $e) {
break;
}
if ($token->test(\Twig_Token::NAME_TYPE, 'for')) {
$currentForLoop++;
} else if ($token->test(\Twig_Token::NAME_TYPE, 'endfor')) {
$currentForLoop--;
}
}
if ($currentForLoop < 1) {
throw new \Twig_Error_Syntax(
'Break tag is only allowed in \'for\' loops.',
$stream->getCurrent()->getLine(),
$stream->getSourceContext()->getName()
);
}
return new BreakNode();
}
public function getTag()
{
return 'break';
}
}
AppBundle\Twig\BreakNode.php:
namespace AppBundle\Twig;
class BreakNode extends \Twig_Node
{
public function compile(\Twig_Compiler $compiler)
{
$compiler
->write("break;\n")
;
}
}
Then you can simply use {% break %}
to get out of loops like this:
{% for post in posts %}
{% if post.id == 10 %}
{% break %}
{% endif %}
<h2>{{ post.heading }}</h2>
{% endfor %}
To go even further, you may write token parsers for {% continue X %}
and {% break X %}
(where X is an integer >= 1) to get out/continue multiple loops like in PHP.
Change hover color on a button with Bootstrap customization
The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:
/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
color: #fff;
background-color: #0495c9;
border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
color: #fff;
background-color: #00b3db;
border-color: #285e8e; /*set the color you want here*/
}
Webdriver and proxy server for firefox
The WebDriver API has been changed. The current snippet for setting the proxy is
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port", "3128");
WebDriver driver = new FirefoxDriver(profile);
XML element with attribute and content using JAXB
Here is working solution:
Output:
public class XmlTest {
private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
@Test
public void createDefaultBook() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(new Book(), writer);
log.debug("Book xml:\n {}", writer.toString());
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "book")
public static class Book {
@XmlElementRef(name = "price")
private Price price = new Price();
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "price")
public static class Price {
@XmlAttribute(name = "drawable")
private Boolean drawable = true; //you may want to set default value here
@XmlValue
private int priceValue = 1234;
public Boolean getDrawable() {
return drawable;
}
public void setDrawable(Boolean drawable) {
this.drawable = drawable;
}
public int getPriceValue() {
return priceValue;
}
public void setPriceValue(int priceValue) {
this.priceValue = priceValue;
}
}
}
Output:
22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<price drawable="true">1234</price>
</book>
Only numbers. Input number in React
Here's my solution of plain Javascript
Attach a keyup
event to the input
field of your choice - id
in this example.
In the event-handler function just test the key of event.key
with the given regex.
In this case if it doesn't match we prevent the default action of the element - so a "wrong" key-press within the input box won't be registered thus it will never appear in the input box.
let idField = document.getElementById('id');
idField.addEventListener('keypress', function(event) {
if (! /([0-9])/g.test(event.key)) {
event.preventDefault();
}
});
The benefit of this solution may be its flexible nature and by changing and/or logically chaining regular expression(s) can fit many requirements.
E.g. the regex /([a-z0-9-_])/g
should match only lowercase English alphanumeric characters with no spaces and only -
and _
allowed.
Note: that if you use /[a-z]/gi
(note the i at the end) will ignore
letter case and will still accept capital letters.
CSS smooth bounce animation
The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration
to suit your needs.
_x000D_
_x000D_
.animated {_x000D_
-webkit-animation-duration: .5s;_x000D_
animation-duration: .5s;_x000D_
-webkit-animation-fill-mode: both;_x000D_
animation-fill-mode: both;_x000D_
-webkit-animation-timing-function: linear;_x000D_
animation-timing-function: linear;_x000D_
animation-iteration-count: infinite;_x000D_
-webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
0%, 100% {_x000D_
-webkit-transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
-webkit-transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
@keyframes bounce {_x000D_
0%, 100% {_x000D_
transform: translateY(0);_x000D_
}_x000D_
50% {_x000D_
transform: translateY(-5px);_x000D_
}_x000D_
}_x000D_
.bounce {_x000D_
-webkit-animation-name: bounce;_x000D_
animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color: red;_x000D_
position: relative;_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
position: relative;_x000D_
top: 92px;_x000D_
left: -300px;_x000D_
width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
_x000D_
_x000D_
Here is how your original keyframe
settings would be interpreted by the browser:
- At 0% (that is, at 0s or start of animation) -
translate
by 0px in Y axis.
- At 20% (that is, at 0.5s of animation) -
translate
by 0px in Y axis.
- At 40% (that is, at 1s of animation) -
translate
by 0px in Y axis.
- At 50% (that is, at 1.25s of animation) -
translate
by 5px in Y axis. This results in a gradual upward movement.
- At 60% (that is, at 1.5s of animation) -
translate
by 0px in Y axis. This results in a gradual downward movement.
- At 80% (that is, at 2s of animation) -
translate
by 0px in Y axis.
- At 100% (that is, at 2.5s or end of animation) -
translate
by 0px in Y axis.
How do I clone a generic list in C#?
Use AutoMapper (or whatever mapping lib you prefer) to clone is simple and a lot maintainable.
Define your mapping:
Mapper.CreateMap<YourType, YourType>();
Do the magic:
YourTypeList.ConvertAll(Mapper.Map<YourType, YourType>);
C read file line by line
readLine()
returns pointer to local variable, which causes undefined behaviour.
To get around you can:
- Create variable in caller function and pass its address to
readLine()
- Allocate memory for
line
using malloc()
- in this case line
will be persistent
- Use global variable, although it is generally a bad practice
Boolean operators && and ||
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all
and any
to reduce it to length one for use in control flow statements, like if
.
The functions all
and any
are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse
.
One final difference: the &&
and ||
only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a
; if it didn't short-circuit, as &
and |
don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
How to convert all tables in database to one collation?
Taking the answer from @Petr Stastny a step further by adding a password variable. I'd prefer if it actually took it in like a regular password rather than as an argument, but it's working for what I needed.
#!/bin/bash
# mycollate.sh <database> <password> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables
DB="$1"
PW="$2"
CHARSET="$3"
COLL="$4"
[ -n "$DB" ] || exit 1
[ -n "$PW" ]
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_bin"
PW="--password=""$PW"
echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql -u root "$PW"
echo "USE $DB; SHOW TABLES;" | mysql -s "$PW" | (
while read TABLE; do
echo $DB.$TABLE
echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql "$PW" $DB
done
)
PW="pleaseEmptyMeNow"
Determining type of an object in ruby
I would say "Yes".
As "Matz" had said something like this in one of his talks,
"Ruby objects have no types."
Not all of it but the part that he is trying to get across to us.
Why would anyone have said
"Everything is an Object" then?
To add he said "Data has Types not objects".
So we might enjoy this.
https://www.youtube.com/watch?v=1l3U1X3z0CE
But Ruby doesn't care to much about the type of object just the class.
We use classes not types. All data then has a class.
12345.class
'my string'.class
They may also have ancestors
Object.ancestors
They also have meta classes but I'll save you the details on that.
Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed.
If you really want to get into details the look up...
"The Ruby Object Model"
This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.
Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.
text blocks
numbers
curl usage to get header
curl --head https://www.example.net
I was pointed to this by curl itself; when I issued the command with -X HEAD
, it printed:
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
How to convert latitude or longitude to meters?
'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim theta As Double = lon1 - lon2
Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
Math.Cos(deg2rad(theta))
dist = Math.Acos(dist)
dist = rad2deg(dist)
dist = dist * 60 * 1.1515
If unit = "K" Then
dist = dist * 1.609344
ElseIf unit = "N" Then
dist = dist * 0.8684
End If
Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
ByVal lat2 As Double, ByVal lon2 As Double, _
Optional ByVal unit As Char = "M"c) As Double
Dim R As Double = 6371 'earth radius in km
Dim dLat As Double
Dim dLon As Double
Dim a As Double
Dim c As Double
Dim d As Double
dLat = deg2rad(lat2 - lat1)
dLon = deg2rad((lon2 - lon1))
a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
d = R * c
Select Case unit.ToString.ToUpper
Case "M"c
d = d * 0.62137119
Case "N"c
d = d * 0.5399568
End Select
Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
Return rad / Math.PI * 180.0
End Function
How to expand and compute log(a + b)?
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
What is a semaphore?
Mutex: exclusive-member access to a resource
Semaphore: n-member access to a resource
That is, a mutex can be used to syncronize access to a counter, file, database, etc.
A sempahore can do the same thing but supports a fixed number of simultaneous callers. For example, I can wrap my database calls in a semaphore(3) so that my multithreaded app will hit the database with at most 3 simultaneous connections. All attempts will block until one of the three slots opens up. They make things like doing naive throttling really, really easy.
DateTime "null" value
For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue
, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
DateTime? MyNullableDate;
Or the longer form:
Nullable<DateTime> MyNullableDate;
And, finally, there's a built in way to reference the default of any type. This returns null
for reference types, but for our DateTime example it will return the same as DateTime.MinValue
:
default(DateTime)
or, in more recent versions of C#,
default
How to run functions in parallel?
This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.
To parallelize your example, you'd need to define your functions with the @ray.remote
decorator, and then invoke them with .remote
.
import ray
ray.init()
dir1 = 'C:\\folder1'
dir2 = 'C:\\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]
# Define the functions.
# You need to pass every global variable used by the function as an argument.
# This is needed because each remote function runs in a different process,
# and thus it does not have access to the global variables defined in
# the current process.
@ray.remote
def func1(filename, addFiles, dir):
# func1() code here...
@ray.remote
def func2(filename, addFiles, dir):
# func2() code here...
# Start two tasks in the background and wait for them to finish.
ray.get([func1.remote(filename, addFiles, dir1), func2.remote(filename, addFiles, dir2)])
If you pass the same argument to both functions and the argument is large, a more efficient way to do this is using ray.put()
. This avoids the large argument to be serialized twice and to create two memory copies of it:
largeData_id = ray.put(largeData)
ray.get([func1(largeData_id), func2(largeData_id)])
Important - If func1()
and func2()
return results, you need to rewrite the code as follows:
ret_id1 = func1.remote(filename, addFiles, dir1)
ret_id2 = func2.remote(filename, addFiles, dir2)
ret1, ret2 = ray.get([ret_id1, ret_id2])
There are a number of advantages of using Ray over the multiprocessing module. In particular, the same code will run on a single machine as well as on a cluster of machines. For more advantages of Ray see this related post.
HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference
My WPF project referenced 3 custom dlls. I updated one of them, deleted the reference and added the reference to the new dll. It also showed the correct version number in the properties of the reference. It was rebuilding without an error.
But when the application was running, the failure "The located assembly's manifest .." occured, mentioning the old version.
After searching for a solution for hours and reading couple of threads like this, I remembered the other dlls.
One of the other dlls was referencing the old version, and that's why the failure occured. After rebuilding the 2nd dll and recreating both references in my WPF project, the failure was gone.
Don't forget to check your other dlls!
Import cycle not allowed
I just encountered this. You may be accessing a method/type from within the same package using the package name itself.
Here is an example to illustrate what I mean:
In foo.go:
// foo.go
package foo
func Foo() {...}
In foo_test.go:
// foo_test.go
package foo
// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT
Image vs Bitmap class
This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.
As others have said before - Bitmap inherits from the Abstract Image class
Abstract effectively means you cannot create a New() instance of it.
Image imgBad1 = new Image(); // Bad - won't compile
Image imgBad2 = new Image(200,200); // Bad - won't compile
But you can do the following:
Image imgGood; // Not instantiated object!
// Now you can do this
imgGood = new Bitmap(200, 200);
You can now use imgGood as you would the same bitmap object if you had done the following:
Bitmap bmpGood = new Bitmap(200,200);
The nice thing here is you can draw the imgGood object using a Graphics object
Graphics gr = default(Graphics);
gr = Graphics.FromImage(new Bitmap(1000, 1000));
Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
gr.DrawImage(imgGood, rect);
Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!
Convert base64 string to ArrayBuffer
Pure JS - no string middlestep (no atob)
I write following function which convert base64 in direct way (without conversion to string at the middlestep). IDEA
- get 4 base64 characters chunk
- find index of each character in base64 alphabet
- convert index to 6-bit number (binary string)
- join four 6 bit numbers which gives 24-bit numer (stored as binary string)
- split 24-bit string to three 8-bit and covert each to number and store them in output array
- corner case: if input base64 string ends with one/two
=
char, remove one/two numbers from output array
Below solution allows to process large input base64 strings. Similar function for convert bytes to base64 without btoa is HERE
_x000D_
_x000D_
function base64ToBytesArr(str) {
const abc = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"]; // base64 alphabet
let result = [];
for(let i=0; i<str.length/4; i++) {
let chunk = [...str.slice(4*i,4*i+4)]
let bin = chunk.map(x=> abc.indexOf(x).toString(2).padStart(6,0)).join('');
let bytes = bin.match(/.{1,8}/g).map(x=> +('0b'+x));
result.push(...bytes.slice(0,3 - (str[4*i+2]=="=") - (str[4*i+3]=="=")));
}
return result;
}
// --------
// TEST
// --------
let test = "Alice's Adventure in Wonderland.";
console.log('test string:', test.length, test);
let b64_btoa = btoa(test);
console.log('encoded string:', b64_btoa);
let decodedBytes = base64ToBytesArr(b64_btoa); // decode base64 to array of bytes
console.log('decoded bytes:', JSON.stringify(decodedBytes));
let decodedTest = decodedBytes.map(b => String.fromCharCode(b) ).join``;
console.log('Uint8Array', JSON.stringify(new Uint8Array(decodedBytes)));
console.log('decoded string:', decodedTest.length, decodedTest);
_x000D_
_x000D_
_x000D_
How to create Windows EventLog source from command line?
If someone is interested, it is also possible to create an event source manually by adding some registry values.
Save the following lines as a .reg file, then import it to registry by double clicking it:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\YOUR_EVENT_SOURCE_NAME_GOES_HERE]
"EventMessageFile"="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\EventLogMessages.dll"
"TypesSupported"=dword:00000007
This creates an event source named YOUR_EVENT_SOURCE_NAME_GOES_HERE
.
Integrating Dropzone.js into existing HTML form with other fields
This is just another example of how you can use Dropzone.js in an existing form.
dropzone.js :
init: function() {
this.on("success", function(file, responseText) {
//alert("HELLO ?" + responseText);
mylittlefix(responseText);
});
return noop;
},
Then, later in the file I put
function mylittlefix(responseText) {
$('#botofform').append('<input type="hidden" name="files[]" value="'+ responseText +'">');
}
This assumes you have a div with id #botofform
that way when uploading you can use the uploaded files' names.
Note: my upload script returned theuploadedfilename.jpeg
dubblenote you also would need to make a cleanup script that checks the upload directory for files not in use and deletes them ..if in a front end non authenticated form :)
How to autosize and right-align GridViewColumn data in WPF?
I know that this is too late but here is my approach:
<GridViewColumn x:Name="GridHeaderLocalSize" Width="100">
<GridViewColumn.Header>
<GridViewColumnHeader HorizontalContentAlignment="Right">
<Grid Width="Auto" HorizontalAlignment="Right">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Local size" TextAlignment="Right" Padding="0,0,5,0"/>
</Grid>
</GridViewColumnHeader>
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Width="{Binding ElementName=GridHeaderLocalSize, Path=Width, FallbackValue=100}" HorizontalAlignment="Right" TextAlignment="Right" Padding="0,0,5,0" Text="Text" >
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
The main idea is to bind the width of the cellTemplete element to the width of the ViewGridColumn. Width=100 is default width used until first resize. There isn't any code behind. Everything is in xaml.
Environment variable substitution in sed
?. bad way: change delimiter
sed 's/xxx/'"$PWD"'/'
sed 's:xxx:'"$PWD"':'
sed 's@xxx@'"$PWD"'@'
maybe those not the final answer,
you can not known what character will occur in $PWD
, /
:
OR @
.
the good way is replace(escape) the special character in $PWD
.
?. good way: escape delimiter
for example:
try to replace URL
as $url (has :
/
in content)
x.com:80/aa/bb/aa.js
in string $tmp
<a href="URL">URL</a>
A. use /
as delimiter
escape /
as \/
in var (before use in sed expression)
echo ${url//\//\\/}
x.com:80\/aa\/bb\/aa.js #escape fine
echo ${url//\//\/}
x.com:80/aa/bb/aa.js #escape not success
echo "${url//\//\/}"
x.com:80\/aa\/bb\/aa.js #escape fine, notice `"`
echo $tmp | sed "s/URL/${url//\//\\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>
echo $tmp | sed "s/URL/${url//\//\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>
OR
B. use :
as delimiter (more readable than /
)
escape :
as \:
in var (before use in sed expression)
echo ${url//:/\:}
x.com:80/aa/bb/aa.js #escape not success
echo "${url//:/\:}"
x.com\:80/aa/bb/aa.js #escape fine, notice `"`
echo $tmp | sed "s:URL:${url//:/\:}:g"
<a href="x.com:80/aa/bb/aa.js">x.com:80/aa/bb/aa.js</a>
Writing an Excel file in EPPlus
It's best if you worked with DataSet
s and/or DataTable
s. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage
object as in your code above called pck
..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
Entityframework Join using join method and lambdas
If you have configured navigation property 1-n I would recommend you to use:
var query = db.Categories // source
.SelectMany(c=>c.CategoryMaps, // join
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
Much more clearer to me and looks better with multiple nested joins.
PreparedStatement IN clause alternatives?
I've never tried it, but would .setArray() do what you're looking for?
Update: Evidently not. setArray only seems to work with a java.sql.Array that comes from an ARRAY column that you've retrieved from a previous query, or a subquery with an ARRAY column.
What is the simplest jQuery way to have a 'position:fixed' (always at top) div?
Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).
The reason I wanted that version in particular is because that's what ships with MVC currently.
Here's the code:
$(document).ready(function() {
$("#topBar").css("position", "absolute");
});
$(window).scroll(function() {
$("#topBar").css("top", $(window).scrollTop() + "px");
});
Spring not autowiring in unit tests with JUnit
You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml
available on the test classpath.
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {
@Autowired
protected SessionFactory sessionFactory;
@Test
public void testDBSourceIsCorrect() throws SQLException {
String databaseProductName = sessionFactory.getCurrentSession()
.connection()
.getMetaData()
.getDatabaseProductName();
assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
}
}
Note: This works with Spring 2.5.2 and Hibernate 3.6.5
Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition
This may be a very naive idea (or may not work at all), but the dimensions of all the coke cans are fixed. So may be if the same image contains both a can and a bottle then you can tell them apart by size considerations (bottles are going to be larger). Now because of missing depth (i.e. 3D mapping to 2D mapping) its possible that a bottle may appear shrunk and there isn't a size difference. You may recover some depth information using stereo-imaging and then recover the original size.
Get most recent file in a directory on Linux
A note about reliability:
Since the newline character is as valid as any in a file name, any solution that relies on lines like the head
/tail
based ones are flawed.
With GNU ls
, another option is to use the --quoting-style=shell-always
option and a bash
array:
eval "files=($(ls -t --quoting-style=shell-always))"
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"
(add the -A
option to ls
if you also want to consider hidden files).
If you want to limit to regular files (disregard directories, fifos, devices, symlinks, sockets...), you'd need to resort to GNU find
.
With bash 4.4 or newer (for readarray -d
) and GNU coreutils 8.25 or newer (for cut -z
):
readarray -t -d '' files < <(
LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' |
sort -rzn | cut -zd/ -f2)
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"
Or recursively:
readarray -t -d '' files < <(
LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' |
sort -rzn | cut -zd/ -f2-)
Best here would be to use zsh
and its glob qualifiers instead of bash
to avoid all this hassle:
Newest regular file in the current directory:
printf '%s\n' *(.om[1])
Including hidden ones:
printf '%s\n' *(D.om[1])
Second newest:
printf '%s\n' *(.om[2])
Check file age after symlink resolution:
printf '%s\n' *(-.om[1])
Recursively:
printf '%s\n' **/*(.om[1])
Also, with the completion system (compinit
and co) enabled, Ctrl+Xm becomes a completer that expands to the newest file.
So:
vi Ctrl+Xm
Would make you edit the newest file (you also get a chance to see which it before you press Return).
vi Alt+2Ctrl+Xm
For the second-newest file.
vi *.cCtrl+Xm
for the newest c
file.
vi *(.)Ctrl+Xm
for the newest regular file (not directory, nor fifo/device...), and so on.
Troubleshooting BadImageFormatException
For anyone who may arrive here at a later time...
For Desktop solution I got BadImageFormatException
exception.
All project's build options was fine (all x86
). But StartUp project of solution was changed to some other project(class library project).
Changing StartUp project to the original(.exe application project) was a solution in my case
View's getWidth() and getHeight() returns 0
Maybe this helps someone:
Create an extension function for the View class
filename: ViewExt.kt
fun View.afterLayout(what: () -> Unit) {
if(isLaidOut) {
what.invoke()
} else {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
what.invoke()
}
})
}
}
This can then be used on any view with:
view.afterLayout {
do something with view.height
}
How to make a vertical SeekBar in Android?
I tried in many different ways, but the one which worked for me was.
Use Seekbar inside FrameLayout
<FrameLayout
android:id="@+id/VolumeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/MuteButton"
android:layout_below="@id/volumeText"
android:layout_centerInParent="true">
<SeekBar
android:id="@+id/volume"
android:layout_width="500dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:progress="50"
android:secondaryProgress="40"
android:progressDrawable="@drawable/seekbar_volume"
android:secondaryProgressTint="@color/tint_neutral"
android:thumbTint="@color/tint_neutral"
/>
And in Code.
Setup Pre Draw callback on Seekbar, Where you can change the Width and height of the Seekbar
I did this part in c#, so Code i used was
var volumeSlider = view.FindViewById<SeekBar>(Resource.Id.home_link_volume);
var volumeFrameLayout = view.FindViewById<FrameLayout>(Resource.Id.linkVolumeFrameLayout);
void OnPreDrawVolume(object sender, ViewTreeObserver.PreDrawEventArgs e)
{
volumeSlider.ViewTreeObserver.PreDraw -= OnPreDrawVolume;
var h = volumeFrameLayout.Height;
volumeSlider.Rotation = 270.0f;
volumeSlider.LayoutParameters.Width = h;
volumeSlider.RequestLayout();
}
volumeSlider.ViewTreeObserver.PreDraw += OnPreDrawVolume;
Here i Add listener to PreDraw Event and when its triggered, I remove the PreDraw so that it doesnt go into Infinite loop.
So when Pre Draw gets executed, I fetch the Height of FrameLayout and assign it to Seekbar. And set the rotation of seekbar to 270.
As my seekbar is inside frame Layout and its Gravity is set as Center. I dont need to worry about the Translation. As Seekbar always stay in middle of Frame Layout.
Reason i remove EventHandler is because seekbar.RequestLayout(); Will make this event to be executed again.
Listing only directories using ls in Bash?
Here is a variation using tree which outputs directory names only on separate lines, yes it's ugly, but hey, it works.
tree -d | grep -E '^[+|+]' | cut -d ' ' -f2
or with awk
tree -d | grep -E '^[+|+]' | awk '{print $2}'
This is probably better however and will retain the /
after directory name.
ls -l | grep "^d" | awk '{print $9}'
urlencoded Forward slash is breaking URL
On my hosting account this problem was caused by a ModSecurity rule that was set for all accounts automatically. Upon my reporting this problem, their admin quickly removed this rule for my account.
"Rate This App"-link in Google Play store app on the phone
I use the following approach by combining this and this answer without using exception based programming and also supports pre-API 21 intent flag.
@SuppressWarnings("deprecation")
private Intent getRateIntent()
{
String url = isMarketAppInstalled() ? "market://details" : "https://play.google.com/store/apps/details";
Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
int intentFlags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
intentFlags |= Build.VERSION.SDK_INT >= 21 ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
rateIntent.addFlags(intentFlags);
return rateIntent;
}
private boolean isMarketAppInstalled()
{
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=anyText"));
return getPackageManager().queryIntentActivities(marketIntent, 0).size() > 0;
}
// use
startActivity(getRateIntent());
Since the intent flag FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
is deprecated from API 21 I use the @SuppressWarnings("deprecation")
tag on the getRateIntent method because my app target SDK is below API 21.
I also tried the official Google way suggested on their website (Dec. 6th 2019). To what I see it doesn't handle the case if the Play Store app isn't installed:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
"https://play.google.com/store/apps/details?id=com.example.android"));
intent.setPackage("com.android.vending");
startActivity(intent);
Java Round up Any Number
10 years later but that problem still caught me.
So this is the answer to those that are too late as me.
This does not work
int b = (int) Math.ceil(a / 100);
Cause the result a / 100
turns out to be an integer and it's rounded so Math.ceil
can't do anything about it.
You have to avoid the rounded operation with this
int b = (int) Math.ceil((float) a / 100);
Now it works.
How can I create numbered map markers in Google Maps V3?
It's quite feasible to generate labeled icons server-side, if you have some programming skills. You'll need the GD library at the server, in addition to PHP. Been working well for me for several years now, but admittedly tricky to get the icon images in synch.
I do that via AJAX by sending the few parameters to define the blank icon and the text and color as well as bgcolor to be applied. Here's my PHP:
header("Content-type: image/png");
//$img_url = "./icons/gen_icon5.php?blank=7&text=BB";
function do_icon ($icon, $text, $color) {
$im = imagecreatefrompng($icon);
imageAlphaBlending($im, true);
imageSaveAlpha($im, true);
$len = strlen($text);
$p1 = ($len <= 2)? 1:2 ;
$p2 = ($len <= 2)? 3:2 ;
$px = (imagesx($im) - 7 * $len) / 2 + $p1;
$font = 'arial.ttf';
$contrast = ($color)? imagecolorallocate($im, 255, 255, 255): imagecolorallocate($im, 0, 0, 0); // white on dark?
imagestring($im, $p2, $px, 3, $text, $contrast); // imagestring ( $image, $font, $x, $y, $string, $color)
imagepng($im);
imagedestroy($im);
}
$icons = array("black.png", "blue.png", "green.png", "red.png", "white.png", "yellow.png", "gray.png", "lt_blue.png", "orange.png"); // 1/9/09
$light = array( TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE); // white text?
$the_icon = $icons[$_GET['blank']]; // 0 thru 8 (note: total 9)
$the_text = substr($_GET['text'], 0, 3); // enforce 2-char limit
do_icon ($the_icon, $the_text,$light[$_GET['blank']] );
It's invoked client-side via something like the following:
var image_file = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + iconStr;
Oracle timestamp data type
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
See Oracle documentation on data types.
raw_input function in Python
raw_input
is a form of input that takes the argument in the form of a string whereas the input function takes the value depending upon your input.
Say, a=input(5)
returns a as an integer with value 5 whereas
a=raw_input(5)
returns a as a string of "5"
Create a mocked list by mockito
OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.
Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.
But the real cause of your problem is that you are using when
on two different objects, before you complete the stubbing. When you call when
, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn
part. Each call to when
must be followed by one and only one call to thenReturn
, before you do any more calls to when
. You made two calls to when
without calling thenReturn
- that's your error.
Found a swap file by the name
I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.
Eg - This creates a new branch matching night-version
of upstream
git checkout upstream/night-version -b testnightversion
This creates a branch testmaster
in local which matches the master
branch of upstream.
git checkout upstream/master -b testmaster
Now if I try to pull the changes of night-version
into testmaster
branch leads to this error.
git pull upstream night-version //while I'm in `master` cloned branch
I managed to solve this by navigating to proper branch and pull the changes.
git checkout testnightversion
git pull upstream night-version // works fine.
How to change active class while click to another link in bootstrap use jquery?
guys try this is a perfect answer for this question:
_x000D_
_x000D_
<script>
$(function(){
$('.nav li a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active')
$('.nav li a').click(function(){
$(this).parent().addClass('active').siblings().removeClass('active')
})
})
</script>
_x000D_
_x000D_
_x000D_
How to detect when a UIScrollView has finished scrolling
Using Ashley Smart logic and is being converted into Swift 4.0 and above.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
NSObject.cancelPreviousPerformRequests(withTarget: self)
perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:)), with: scrollView, afterDelay: 0.3)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
The logic above solve issues such as when user is scrolling off the tableview. Without the logic, when you scroll off the tableview, didEnd
will be called but it will not execute anything. Currently using it in year 2020.
Java, looping through result set
List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();
String query = "SELECT rlink_id, COUNT(*)"
+ "FROM dbo.Locate "
+ "GROUP BY rlink_id ";
Statement stmt = yourconnection.createStatement();
try {
ResultSet rs4 = stmt.executeQuery(query);
while (rs4.next()) {
sids.add(rs4.getString(1));
lids.add(rs4.getString(2));
}
} finally {
stmt.close();
}
String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());
ConnectionTimeout versus SocketTimeout
A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.
A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.
By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!
If only the incoming stream stalls for more than a millisecond you are running into a timeout.
Generating Unique Random Numbers in Java
This isn't significantly different from other answers, but I wanted the array of integers in the end:
Integer[] indices = new Integer[n];
Arrays.setAll(indices, i -> i);
Collections.shuffle(Arrays.asList(indices));
return Arrays.stream(indices).mapToInt(Integer::intValue).toArray();
Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect
The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).
Typical symptoms:
[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100
[root@host /]# netstat -plant | grep 25
tcp 0 0 :::25 :::* LISTEN 1082/exim
If this happens, make sure that you don't have two entries for localhost
in /etc/hosts
with different IP addresses, like this (bad) example:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
To avoid confusion, make sure you only have one entry for localhost
, preferably an IPv4 address, like this:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4.localdomain4 localhost4
::1 localhost6 localhost6.localdomain6
How to load html string in a webview?
I had the same requirement and I have done this in following way.You also can try out this..
Use loadData method
web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");
movDirector movProducer like all are my string variable.
In short i retain custom styling for my url.
When to use LinkedList over ArrayList in Java?
Here is the Big-O notation in both ArrayList
and LinkedList
and also CopyOnWrite-ArrayList
:
ArrayList
get O(1)
add O(1)
contains O(n)
next O(1)
remove O(n)
iterator.remove O(n)
LinkedList
get O(n)
add O(1)
contains O(n)
next O(1)
remove O(1)
iterator.remove O(1)
CopyOnWrite-ArrayList
get O(1)
add O(n)
contains O(n)
next O(1)
remove O(n)
iterator.remove O(n)
Based on these you have to decide what to choose. :)
How can I make Bootstrap columns all the same height?
Solution 4 using Bootstrap 4
Bootstrap 4 uses Flexbox so there is no need for extra CSS.
Demo
<div class="container">
<div class="row ">
<div class="col-md-4" style="background-color: red">
some content
</div>
<div class="col-md-4" style="background-color: yellow">
catz
<img width="100" height="100" src="https://placekitten.com/100/100/">
</div>
<div class="col-md-4" style="background-color: green">
some more content
</div>
</div>
</div>
Solution 1 using negative margins (doesn't break responsiveness)
Demo
.row{
overflow: hidden;
}
[class*="col-"]{
margin-bottom: -99999px;
padding-bottom: 99999px;
}
Solution 2 using table
Demo
.row {
display: table;
}
[class*="col-"] {
float: none;
display: table-cell;
vertical-align: top;
}
Solution 3 using flex added August 2015. Comments posted before this don't apply to this solution.
Demo
.row {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
flex-wrap: wrap;
}
.row > [class*='col-'] {
display: flex;
flex-direction: column;
}
Disable button in jQuery
For Jquery UI buttons this works :
$("#buttonId").button( "option", "disabled", true | false );
Skip first couple of lines while reading lines in Python file
for line in dropwhile(isBadLine, lines):
# process as you see fit
Full demo:
from itertools import *
def isBadLine(line):
return line=='0'
with open(...) as f:
for line in dropwhile(isBadLine, f):
# process as you see fit
Advantages: This is easily extensible to cases where your prefix lines are more complicated than "0" (but not interdependent).
Change URL without refresh the page
When you use a function ...
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>
HttpClient does not exist in .net 4.0: what can I do?
Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):
HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
http.Referer = referrer;
HttpWebResponse response = (HttpWebResponse )http.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string responseJson = sr.ReadToEnd();
// more stuff
}
Vertical Tabs with JQuery?
super simple function that will allow you to create your own tab / accordion structure here: http://jsfiddle.net/nabeezy/v36DF/
bindSets = function (tabClass, tabClassActive, contentClass, contentClassHidden) {
//Dependent on jQuery
//PARAMETERS
//tabClass: 'the class name of the DOM elements that will be clicked',
//tabClassActive: 'the class name that will be applied to the active tabClass element when clicked (must write your own css)',
//contentClass: 'the class name of the DOM elements that will be modified when the corresponding tab is clicked',
//contentClassHidden: 'the class name that will be applied to all contentClass elements except the active one (must write your own css)',
//MUST call bindSets() after dom has rendered
var tabs = $('.' + tabClass);
var tabContent = $('.' + contentClass);
if(tabs.length !== tabContent.length){console.log('JS bindSets: sets contain a different number of elements')};
tabs.each(function (index) {
this.matchedElement = tabContent[index];
$(this).click(function () {
tabs.each(function () {
this.classList.remove(tabClassActive);
});
tabContent.each(function () {
this.classList.add(contentClassHidden);
});
this.classList.add(tabClassActive);
this.matchedElement.classList.remove(contentClassHidden);
});
})
tabContent.each(function () {
this.classList.add(contentClassHidden);
});
//tabs[0].click();
}
bindSets('tabs','active','content','hidden');
MongoDB vs Firebase
Apples and oranges. Firebase is a Backend-as-a-Service containing identity management, realtime data views and a document database. It runs in the cloud.
MongoDB on the other hand is a full fledged database with a rich query language. In principle it runs on your own machine, but there are cloud providers.
If you are looking for the database component only MongoDB is much more mature and feature-rich.
How to perform OR condition in django queryset?
Both options are already mentioned in the existing answers:
from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
and
q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
However, there seems to be some confusion regarding which one is to prefer.
The point is that they are identical on the SQL level, so feel free to pick whichever you like!
The Django ORM Cookbook talks in some detail about this, here is the relevant part:
queryset = User.objects.filter(
first_name__startswith='R'
) | User.objects.filter(
last_name__startswith='D'
)
leads to
In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'
and
qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))
leads to
In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'
source: django-orm-cookbook
How to get number of rows using SqlDataReader in C#
I also face a situation when I needed to return a top result but also wanted to get the total rows that where matching the query. i finaly get to this solution:
public string Format(SelectQuery selectQuery)
{
string result;
if (string.IsNullOrWhiteSpace(selectQuery.WherePart))
{
result = string.Format(
@"
declare @maxResult int;
set @maxResult = {0};
WITH Total AS
(
SELECT count(*) as [Count] FROM {2}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart);
}
else
{
result = string.Format(
@"
declare @maxResult int;
set @maxResult = {0};
WITH Total AS
(
SELECT count(*) as [Count] FROM {2} WHERE {3}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2} WHERE {3}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart, selectQuery.WherePart);
}
if (!string.IsNullOrWhiteSpace(selectQuery.OrderPart))
result = string.Format("{0} ORDER BY {1}", result, selectQuery.OrderPart);
return result;
}
Target class controller does not exist - Laravel 8
Happened to me when I passing null to the middleware
function
Route::middleware(null)->group(function () {
Route::get('/some-path', [SomeController::class, 'search']);
});
Passing []
for no middleware works or probably just remove the middleware
call if not using middleware :D
How to permanently remove few commits from remote branch
Important: Make sure you specify which branches on "git push -f" or you might inadvertently modify other branches![*]
There are three options shown in this tutorial. In case the link breaks I'll leave the main steps here.
- Revert the full commit
- Delete the last commit
- Delete commit from a list
1 Revert the full commit
git revert dd61ab23
2 Delete the last commit
git push <<remote>> +dd61ab23^:<<BRANCH_NAME_HERE>>
or, if the branch is available locally
git reset HEAD^ --hard
git push <<remote>> -f
where +dd61... is your commit hash and git interprets x^ as the parent of x, and + as a forced non-fastforwared push.
3 Delete the commit from a list
git rebase -i dd61ab23^
This will open and editor showing a list of all commits. Delete the one you want to get rid off. Finish the rebase and push force to repo.
git rebase --continue
git push <remote_repo> <remote_branch> -f
Get length of array?
Function
Public Function ArrayLen(arr As Variant) As Integer
ArrayLen = UBound(arr) - LBound(arr) + 1
End Function
Usage
Dim arr(1 To 3) As String ' Array starting at 1 instead of 0: nightmare fuel
Debug.Print ArrayLen(arr) ' Prints 3. Everything's going to be ok.
Eloquent: find() and where() usage laravel
Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail
and firstOrFail
methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException
will be thrown:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
Catch a thread's exception in the caller thread in Python
Although it is not possible to directly catch an exception thrown in a different thread, here's a code to quite transparently obtain something very close to this functionality. Your child thread must subclass the ExThread
class instead of threading.Thread
and the parent thread must call the child_thread.join_with_exception()
method instead of child_thread.join()
when waiting for the thread to finish its job.
Technical details of this implementation: when the child thread throws an exception, it is passed to the parent through a Queue
and thrown again in the parent thread. Notice that there's no busy waiting in this approach .
#!/usr/bin/env python
import sys
import threading
import Queue
class ExThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.__status_queue = Queue.Queue()
def run_with_exception(self):
"""This method should be overriden."""
raise NotImplementedError
def run(self):
"""This method should NOT be overriden."""
try:
self.run_with_exception()
except BaseException:
self.__status_queue.put(sys.exc_info())
self.__status_queue.put(None)
def wait_for_exc_info(self):
return self.__status_queue.get()
def join_with_exception(self):
ex_info = self.wait_for_exc_info()
if ex_info is None:
return
else:
raise ex_info[1]
class MyException(Exception):
pass
class MyThread(ExThread):
def __init__(self):
ExThread.__init__(self)
def run_with_exception(self):
thread_name = threading.current_thread().name
raise MyException("An error in thread '{}'.".format(thread_name))
def main():
t = MyThread()
t.start()
try:
t.join_with_exception()
except MyException as ex:
thread_name = threading.current_thread().name
print "Caught a MyException in thread '{}': {}".format(thread_name, ex)
if __name__ == '__main__':
main()
Difference between 2 dates in seconds
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
Multiple Where clauses in Lambda expressions
Maybe
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty)
.Where(l => l.InternalName != string.Empty)
?
You can probably also put it in the same where clause:
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
Which to use <div class="name"> or <div id="name">?
ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...
What is the difference between Views and Materialized Views in Oracle?
A view uses a query to pull data from the underlying tables.
A materialized view is a table on disk that contains the result set of a query.
Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH
option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH
has been in place since at least Oracle 10.