Hey You can Use this insted
<iframe width="100%" height="100%" class="absolute inset-0" frameborder="0" title="map" marginheight="0" marginwidth="0" scrolling="no" src="https://maps.google.com/maps?width=100%&height=600&hl=en&q=%C4%B0ikaneir+(Mumma's%20Bakery)&ie=UTF8&t=&z=14&iwloc=B&output=embed" style="filter: scale(100) contrast(1.2) opacity(0.4);"></iframe>
I have just finished adding Google Maps to my company's CMS offering. My code allows for more than one map in a page.
Notes:
HTML:
<div class="block maps first">
<div class="content">
<div class="map_canvas">
<div class="infotext">
<div class="location">Middle East Bakery & Grocery</div>
<div class="address">327 5th St</div>
<div class="city">West Palm Beach</div>
<div class="state">FL</div>
<div class="zip">33401-3995</div>
<div class="country">USA</div>
<div class="phone">(561) 659-4050</div>
<div class="zoom">14</div>
</div>
</div>
</div>
</div>
<div class="block maps last">
<div class="content">
<div class="map_canvas">
<div class="infotext">
<div class="location">Global Design, Inc</div>
<div class="address">3434 SW Ash Pl</div>
<div class="city">Palm City</div>
<div class="state">FL</div>
<div class="zip">34990</div>
<div class="country">USA</div>
<div class="phone"></div>
<div class="zoom">17</div>
</div>
</div>
</div>
</div>
Code:
$(document).ready(function() {
$maps = $('.block.maps .content .map_canvas');
$maps.each(function(index, Element) {
$infotext = $(Element).children('.infotext');
var myOptions = {
'zoom': parseInt($infotext.children('.zoom').text()),
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map;
var geocoder;
var marker;
var infowindow;
var address = $infotext.children('.address').text() + ', '
+ $infotext.children('.city').text() + ', '
+ $infotext.children('.state').text() + ' '
+ $infotext.children('.zip').text() + ', '
+ $infotext.children('.country').text()
;
var content = '<strong>' + $infotext.children('.location').text() + '</strong><br />'
+ $infotext.children('.address').text() + '<br />'
+ $infotext.children('.city').text() + ', '
+ $infotext.children('.state').text() + ' '
+ $infotext.children('.zip').text()
;
if (0 < $infotext.children('.phone').text().length) {
content += '<br />' + $infotext.children('.phone').text();
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myOptions.center = results[0].geometry.location;
map = new google.maps.Map(Element, myOptions);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: $infotext.children('.location').text()
});
infowindow = new google.maps.InfoWindow({'content': content});
google.maps.event.addListener(map, 'tilesloaded', function(event) {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert('The address could not be found for the following reason: ' + status);
}
});
});
});
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
String temp = s.Replace("\r\n","").Trim();
s
being the original string. (Note capitals)
Full option searchable select box
This also supports Control buttons keyboards such as ArrowDown
ArrowUp
and Enter
keys
function filterFunction(that, event) {_x000D_
let container, input, filter, li, input_val;_x000D_
container = $(that).closest(".searchable");_x000D_
input_val = container.find("input").val().toUpperCase();_x000D_
_x000D_
if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {_x000D_
keyControl(event, container)_x000D_
} else {_x000D_
li = container.find("ul li");_x000D_
li.each(function (i, obj) {_x000D_
if ($(this).text().toUpperCase().indexOf(input_val) > -1) {_x000D_
$(this).show();_x000D_
} else {_x000D_
$(this).hide();_x000D_
}_x000D_
});_x000D_
_x000D_
container.find("ul li").removeClass("selected");_x000D_
setTimeout(function () {_x000D_
container.find("ul li:visible").first().addClass("selected");_x000D_
}, 100)_x000D_
}_x000D_
}_x000D_
_x000D_
function keyControl(e, container) {_x000D_
if (e.key == "ArrowDown") {_x000D_
_x000D_
if (container.find("ul li").hasClass("selected")) {_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {_x000D_
container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
_x000D_
} else {_x000D_
container.find("ul li:first-child").addClass("selected");_x000D_
}_x000D_
_x000D_
} else if (e.key == "ArrowUp") {_x000D_
_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {_x000D_
container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
} else if (e.key == "Enter") {_x000D_
container.find("input").val(container.find("ul li.selected").text()).blur();_x000D_
onSelect(container.find("ul li.selected").text())_x000D_
}_x000D_
_x000D_
container.find("ul li.selected")[0].scrollIntoView({_x000D_
behavior: "smooth",_x000D_
});_x000D_
}_x000D_
_x000D_
function onSelect(val) {_x000D_
alert(val)_x000D_
}_x000D_
_x000D_
$(".searchable input").focus(function () {_x000D_
$(this).closest(".searchable").find("ul").show();_x000D_
$(this).closest(".searchable").find("ul li").show();_x000D_
});_x000D_
$(".searchable input").blur(function () {_x000D_
let that = this;_x000D_
setTimeout(function () {_x000D_
$(that).closest(".searchable").find("ul").hide();_x000D_
}, 300);_x000D_
});_x000D_
_x000D_
$(document).on('click', '.searchable ul li', function () {_x000D_
$(this).closest(".searchable").find("input").val($(this).text()).blur();_x000D_
onSelect($(this).text())_x000D_
});_x000D_
_x000D_
$(".searchable ul li").hover(function () {_x000D_
$(this).closest(".searchable").find("ul li.selected").removeClass("selected");_x000D_
$(this).addClass("selected");_x000D_
});
_x000D_
div.searchable {_x000D_
width: 300px;_x000D_
float: left;_x000D_
margin: 0 15px;_x000D_
}_x000D_
_x000D_
.searchable input {_x000D_
width: 100%;_x000D_
height: 50px;_x000D_
font-size: 18px;_x000D_
padding: 10px;_x000D_
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */_x000D_
-moz-box-sizing: border-box; /* Firefox, other Gecko */_x000D_
box-sizing: border-box; /* Opera/IE 8+ */_x000D_
display: block;_x000D_
font-weight: 400;_x000D_
line-height: 1.6;_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
background-clip: padding-box;_x000D_
border: 1px solid #ced4da;_x000D_
border-radius: .25rem;_x000D_
transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;_x000D_
background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center/8px 10px;_x000D_
}_x000D_
_x000D_
.searchable ul {_x000D_
display: none;_x000D_
list-style-type: none;_x000D_
background-color: #fff;_x000D_
border-radius: 0 0 5px 5px;_x000D_
border: 1px solid #add8e6;_x000D_
border-top: none;_x000D_
max-height: 180px;_x000D_
margin: 0;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.searchable ul li {_x000D_
padding: 7px 9px;_x000D_
border-bottom: 1px solid #e1e1e1;_x000D_
cursor: pointer;_x000D_
color: #6e6e6e;_x000D_
}_x000D_
_x000D_
.searchable ul li.selected {_x000D_
background-color: #e8e8e8;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="searchable">_x000D_
<input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">_x000D_
<ul>_x000D_
<li>Algeria</li>_x000D_
<li>Bulgaria</li>_x000D_
<li>Canada</li>_x000D_
<li>Egypt</li>_x000D_
<li>Fiji</li>_x000D_
<li>India</li>_x000D_
<li>Japan</li>_x000D_
<li>Iran (Islamic Republic of)</li>_x000D_
<li>Lao People's Democratic Republic</li>_x000D_
<li>Micronesia (Federated States of)</li>_x000D_
<li>Nicaragua</li>_x000D_
<li>Senegal</li>_x000D_
<li>Tajikistan</li>_x000D_
<li>Yemen</li>_x000D_
</ul>_x000D_
</div>
_x000D_
This is the correct answer to auto hide of zero value and cell shows blank for zero value only follow:
You do not need to select the columns separately in order to use them in your CONCAT. Simply remove them, and your query will become:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
Because a null collection is not the same thing as an empty collection. An empty collection is a collection object with no elements; a null collection is a nonexistent object.
Here's something to try: Declare two collections of any sort. Initialize one normally so that it's empty, and assign the other the value null
. Then try adding an object to both collections and see what happens.
For me worked like a charm
element(by.cssContainingText('option', 'BeaverBox Testing')).click();
Never and forever are two words that I avoid using due to the unpredictability of life.
The latest time since 1 January 1970
that can be stored using a signed 32-bit
integer is 03:14:07 on Tuesday, 19 January 2038
(231-1 = 2,147,483,647
seconds after 1 January 1970
). This limitation is known as the Year 2038 problem
setCookie("name", "value", strtotime("2038-01-19 03:14:07"));
Even though is not the fastest choice, if performance is not an issue you can use:
sum(~np.isnan(data))
.
In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop
In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop
In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop
To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography
: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable
There is delete
, delete_all
, destroy
, and destroy_all
.
The docs are: older docs and Rails 3.0.0 docs
delete
doesn't instantiate the objects, while destroy
does. In general, delete
is faster than destroy
.
I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"
here is the sample
<connectionStrings>
<add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
</connectionStrings>
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Excel ColumnWidth from dataGridView:
foreach (DataGridViewColumn co in dataGridView1.Columns)
{ worksheet.Columns[co.Index + 1].ColumnWidth = co.Width/8; }
I don't think you can use braces.
According to the Bash manual about case in Conditional Constructs.
Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
Nothing about Brace Expansion unfortunately.
So you'd have to do something like this:
case $1 in
req*)
...
;;
met*|meet*)
...
;;
*)
# You should have a default one too.
esac
The other answers explain how to produce a string formatted like in your example, but if all you need to do is to print
that stuff you could simply write:
first = 10
second = 20
print "First number is", first, "and second number is", second
byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);
For Reading Properties file with its original order:
File file = new File("../config/edc.properties");
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
layout.load(new InputStreamReader(new FileInputStream(file)));
for(Object propKey : layout.getKeys()){
PropertiesConfiguration propval = layout.getConfiguration();
String value = propval.getProperty((String) propKey).toString();
out.print("Current Key:" + propkey + "Current Value:" + propval + "<br>");
}
A point in favor of alias
instead of alias_method
is that its semantic is recognized by rdoc, leading to neat cross references in the generated documentation, while rdoc completely ignore alias_method
.
A simple Stream extension method would do the job:
public static class StreamExtensions
{
public static string ConvertToBase64(this Stream stream)
{
var bytes = new Byte[(int)stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(bytes, 0, (int)stream.Length);
return Convert.ToBase64String(bytes);
}
}
The methods for Read (and also Write) and optimized for the respective class (whether is file stream, memory stream, etc.) and will do the work for you. For simple task like this, there is no need of readers, and etc.
The only drawback is that the stream is copied into byte array, but that is how the conversion to base64 via Convert.ToBase64String works unfortunately.
One terrible but workable solution: render the image using a Flash object, which then gives you all the transformations possible in Flash.
If your users are using bleeding-edge browsers and if Firefox 3.5 and Safari 4 support it (I don't know that either do/will), you could adjust the CSS color-profile attribute of the image, setting it to a grayscale ICC profile URL. But that's a lot of if's!
... and Trick #3 Multiline entries in an Xtable
Generate some more data
moredata<-data.frame(Nominal=c(1:5), n=rep(5,5),
MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4),
LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4),
QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))
names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")
Now produce our xtable, using the sanitize function to replace column names with the correct Latex newline commands (including double backslashes so R is happy)
<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo,
floating=FALSE,
include.rownames=FALSE,
sanitize.text.function = function(str) {
str<-gsub("\n","\\\\", str, fixed=TRUE)
return(str)
},
sanitize.colnames.function = function(str) {
str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
return(str)
})
@
(although this isn't perfect, as we need \tabularnewline so the table is formatted correctly, and Xtable still puts in a final \, so we end up with a blank line below the table header.)
I created a pure on hover dropdown menu based on the latest (v2.0.2) Bootstrap framework that has support for multiple submenus and thought I'd post it for future users:
body {_x000D_
padding-top: 60px;_x000D_
padding-bottom: 40px;_x000D_
}_x000D_
_x000D_
.sidebar-nav {_x000D_
padding: 9px 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .sub-menu {_x000D_
left: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
visibility: hidden;_x000D_
margin-top: -1px;_x000D_
}_x000D_
_x000D_
.dropdown-menu li:hover .sub-menu {_x000D_
visibility: visible;_x000D_
}_x000D_
_x000D_
.dropdown:hover .dropdown-menu {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.nav-tabs .dropdown-menu,_x000D_
.nav-pills .dropdown-menu,_x000D_
.navbar .dropdown-menu {_x000D_
margin-top: 0;_x000D_
}_x000D_
_x000D_
.navbar .sub-menu:before {_x000D_
border-bottom: 7px solid transparent;_x000D_
border-left: none;_x000D_
border-right: 7px solid rgba(0, 0, 0, 0.2);_x000D_
border-top: 7px solid transparent;_x000D_
left: -7px;_x000D_
top: 10px;_x000D_
}_x000D_
_x000D_
.navbar .sub-menu:after {_x000D_
border-top: 6px solid transparent;_x000D_
border-left: none;_x000D_
border-right: 6px solid #fff;_x000D_
border-bottom: 6px solid transparent;_x000D_
left: 10px;_x000D_
top: 11px;_x000D_
left: -6px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="navbar navbar-fixed-top">_x000D_
<div class="navbar-inner">_x000D_
<div class="container-fluid">_x000D_
<a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar">_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</a>_x000D_
<a href="#" class="brand">Project name</a>_x000D_
<div class="nav-collapse">_x000D_
<ul class="nav">_x000D_
<li class="active"><a href="#">Home</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li class="dropdown">_x000D_
<a data-toggle="dropdown" class="dropdown-toggle" href="#">Dropdown <b class="caret"></b></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li>_x000D_
<a href="#">2-level Dropdown <i class="icon-arrow-right"></i></a>_x000D_
<ul class="dropdown-menu sub-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li class="divider"></li>_x000D_
<li class="nav-header">Nav header</li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
<li><a href="#">One more separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li class="divider"></li>_x000D_
<li class="nav-header">Nav header</li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
<li><a href="#">One more separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<form action="" class="navbar-search pull-left">_x000D_
<input type="text" placeholder="Search" class="search-query span2">_x000D_
</form>_x000D_
<ul class="nav pull-right">_x000D_
<li><a href="#">Link</a></li>_x000D_
<li class="divider-vertical"></li>_x000D_
<li class="dropdown">_x000D_
<a class="#" href="#">Menu</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.nav-collapse -->_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<ul class="nav nav-pills">_x000D_
<li class="active"><a href="#">Regular link</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" data-toggle="dropdown" class="dropdown-toggle">Dropdown <b class="caret"></b></a>_x000D_
<ul class="dropdown-menu" id="menu1">_x000D_
<li>_x000D_
<a href="#">2-level Menu <i class="icon-arrow-right"></i></a>_x000D_
<ul class="dropdown-menu sub-menu">_x000D_
<li><a href="#">Action</a></li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li class="divider"></li>_x000D_
<li class="nav-header">Nav header</li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
<li><a href="#">One more separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">Another action</a></li>_x000D_
<li><a href="#">Something else here</a></li>_x000D_
<li class="divider"></li>_x000D_
<li><a href="#">Separated link</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li class="dropdown">_x000D_
<a href="#">Menu</a>_x000D_
</li>_x000D_
<li class="dropdown">_x000D_
<a href="#">Menu</a>_x000D_
</li>_x000D_
</ul>
_x000D_
You should be able to use join
, which joins on the index as default. Given your desired result, you must use outer
as the join type.
>>> df1.join(df2, how='outer')
V1 V2
A 1/1/2012 12 15
2/1/2012 14 NaN
3/1/2012 NaN 21
B 1/1/2012 15 24
2/1/2012 8 9
C 1/1/2012 17 NaN
2/1/2012 9 NaN
D 1/1/2012 NaN 7
2/1/2012 NaN 16
Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)
According to documentation it is:
spring.jpa.show-sql=true # Enable logging of SQL statements.
There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.
They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.
Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools
There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?
If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.
On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).
Another possible solution specially if you want batch delete
deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))
session.execute(deleted_objects)
session.commit()
Array.isArray
:function isObject(o) {
return o !== null && typeof o === 'object' && Array.isArray(o) === false;
}
Array.isArray
:Just surprised how many upvotes for wrong answers
Only 1 answer passed my tests!!! Here I've created my simplified version:
function isObject(o) {
return o instanceof Object && o.constructor === Object;
}
As for me, it's clear and simple, and just works! Here my tests:
console.log(isObject({})); // Will return: true
console.log(isObject([])); // Will return: false
console.log(isObject(null)); // Will return: false
console.log(isObject(/.*/)); // Will return: false
console.log(isObject(function () {})); // Will return: false
ONE MORE TIME: not all answers pass this tests !!!
In case you need to verify that object is instance of particular class you have to check constructor with your particular class, like:
function isDate(o) {
return o instanceof Object && o.constructor === Date;
}
simple test:
var d = new Date();
console.log(isObject(d)); // Will return: false
console.log(isDate(d)); // Will return: true
As result, you will have strict and robust code!
In case you won't create functions like isDate
, isError
, isRegExp
, etc you may consider option to use this generalized functions:
function isObject(o) {
return o instanceof Object && typeof o.constructor === 'function';
}
it won't work correctly for all test cases mentioned earlier, but it's good enough for all objects (plain or constructed).
isObject
won't work in case of Object.create(null)
because of internal implementation of Object.create
which is explained here but you can use isObject
in more sophisticated implementation:
function isObject(o, strict = true) {
if (o === null || o === undefined) {
return false;
}
const instanceOfObject = o instanceof Object;
const typeOfObject = typeof o === 'object';
const constructorUndefined = o.constructor === undefined;
const constructorObject = o.constructor === Object;
const typeOfConstructorObject = typeof o.constructor === 'function';
let r;
if (strict === true) {
r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject);
} else {
r = (constructorUndefined || typeOfConstructorObject);
}
return r;
};
There is already created package on npm v1 based on this implementation! And it works for all earlier described test cases!
It seems to mean your node server's connection to your MongoDB instance was interrupted while it was trying to write to it.
Take a look at the Mongo source code that generates that error
Mongos.prototype.insert = function(ns, ops, options, callback) {
if(typeof options == 'function') callback = options, options = {};
if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed')));
// Topology is not connected, save the call in the provided store to be
// Executed at some point when the handler deems it's reconnected
if(!this.isConnected() && this.s.disconnectHandler != null) {
callback = bindToCurrentDomain(callback);
return this.s.disconnectHandler.add('insert', ns, ops, options, callback);
}
executeWriteOperation(this.s, 'insert', ns, ops, options, callback);
}
This does not appear to be related to the Sails issue cited in the comments, as no upgrades were installed to precipitate the crash or the "fix"
My use case was I wanted to replace
foo:/Drive_Letter
with foo:/bar/baz/xyz
In my case I was able to do it with the following code.
I was in the same directory location where there were bulk of files.
find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'
hope that helped.
UPDATE s|foo:/Drive_letter:|foo:/ba/baz/xyz|g
Use of pointer before character array
Normally, Character array is used to store single elements in it i.e 1 byte each
eg:
char a[]={'a','b','c'};
we can't store multiple value in it.
by using pointer before the character array we can store the multi dimensional array elements in the array
i.e.
char *a[]={"one","two","three"};
printf("%s\n%s\n%s",a[0],a[1],a[2]);
I do this as a side-effect of pushing with the -u
option as in
$ git push -u origin branch-name
The equivalent long option is --set-upstream
.
The git-branch
command also understands --set-upstream
, but its use can be confusing. Version 1.8.0 modifies the interface.
git branch --set-upstream
is deprecated and may be removed in a relatively distant future.git branch [-u|--set-upstream-to]
has been introduced with a saner order of arguments.…
It was tempting to say
git branch --set-upstream origin/master
, but that tells Git to arrange the local branch "origin/master" to integrate with the currently checked out branch, which is highly unlikely what the user meant. The option is deprecated; use the new--set-upstream-to
(with a short-and-sweet-u
) option instead.
Say you have a local foo
branch and want it to treat the branch by the same name as its upstream. Make this happen with
$ git branch foo
$ git branch --set-upstream-to=origin/foo
or just
$ git branch --set-upstream-to=origin/foo foo
In one answer above:
The simplest & the best solution:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));
There is an syntax error, ,null
must be added:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s,null));
There is way without requiring user to do changes on his PC. Runtime.getRuntime.exec() allows us to start cmd.exe and execute commands inside of it. So, it's possible for java program to run itself in command prompt when user clicks .jar file.
public static void main(String[] args) throws IOException {
if(args.length == 0) {
Process p = Runtime.getRuntime().exec("cmd.exe /c start java -jar " + (new File(NameOfClass.class.getProtectionDomain().getCodeSource().getLocation().getPath())).getAbsolutePath() + " cmd");
} else {
//code to be executed
}
}
$(document).ready(function() {_x000D_
// executes when HTML-Document is loaded and DOM is ready_x000D_
console.log("document is ready");_x000D_
});_x000D_
_x000D_
_x000D_
$(window).load(function() {_x000D_
// executes when complete page is fully loaded, including all frames, objects and images_x000D_
console.log("window is loaded");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Query 3.0 version
These methods are shortcuts for event operations, but had several API limitations. The event
.load()
method conflicted with the ajax.load()
method. The.error()
method could not be used withwindow.onerror
because of the way the DOM method is defined. If you need to attach events by these names, use the.on()
method, e.g. change$("img").load(fn)
to$(img).on("load", fn)
.1
$(window).load(function() {});
Should be changed to
$(window).on('load', function (e) {})
These are all equivalent:
$(function(){
});
jQuery(document).ready(function(){
});
$(document).ready(function(){
});
$(document).on('ready', function(){
})
Welcome to the wonderful world of portability... or rather the lack of it. Before we start analyzing these two options in detail and take a deeper look how different operating systems handle them, it should be noted that the BSD socket implementation is the mother of all socket implementations. Basically all other systems copied the BSD socket implementation at some point in time (or at least its interfaces) and then started evolving it on their own. Of course the BSD socket implementation was evolved as well at the same time and thus systems that copied it later got features that were lacking in systems that copied it earlier. Understanding the BSD socket implementation is the key to understanding all other socket implementations, so you should read about it even if you don't care to ever write code for a BSD system.
There are a couple of basics you should know before we look at these two options. A TCP/UDP connection is identified by a tuple of five values:
{<protocol>, <src addr>, <src port>, <dest addr>, <dest port>}
Any unique combination of these values identifies a connection. As a result, no two connections can have the same five values, otherwise the system would not be able to distinguish these connections any longer.
The protocol of a socket is set when a socket is created with the socket()
function. The source address and port are set with the bind()
function. The destination address and port are set with the connect()
function. Since UDP is a connectionless protocol, UDP sockets can be used without connecting them. Yet it is allowed to connect them and in some cases very advantageous for your code and general application design. In connectionless mode, UDP sockets that were not explicitly bound when data is sent over them for the first time are usually automatically bound by the system, as an unbound UDP socket cannot receive any (reply) data. Same is true for an unbound TCP socket, it is automatically bound before it will be connected.
If you explicitly bind a socket, it is possible to bind it to port 0
, which means "any port". Since a socket cannot really be bound to all existing ports, the system will have to choose a specific port itself in that case (usually from a predefined, OS specific range of source ports). A similar wildcard exists for the source address, which can be "any address" (0.0.0.0
in case of IPv4 and ::
in case of IPv6). Unlike in case of ports, a socket can really be bound to "any address" which means "all source IP addresses of all local interfaces". If the socket is connected later on, the system has to choose a specific source IP address, since a socket cannot be connected and at the same time be bound to any local IP address. Depending on the destination address and the content of the routing table, the system will pick an appropriate source address and replace the "any" binding with a binding to the chosen source IP address.
By default, no two sockets can be bound to the same combination of source address and source port. As long as the source port is different, the source address is actually irrelevant. Binding socketA
to ipA:portA
and socketB
to ipB:portB
is always possible if ipA != ipB
holds true, even when portA == portB
. E.g. socketA
belongs to a FTP server program and is bound to 192.168.0.1:21
and socketB
belongs to another FTP server program and is bound to 10.0.0.1:21
, both bindings will succeed. Keep in mind, though, that a socket may be locally bound to "any address". If a socket is bound to 0.0.0.0:21
, it is bound to all existing local addresses at the same time and in that case no other socket can be bound to port 21
, regardless which specific IP address it tries to bind to, as 0.0.0.0
conflicts with all existing local IP addresses.
Anything said so far is pretty much equal for all major operating system. Things start to get OS specific when address reuse comes into play. We start with BSD, since as I said above, it is the mother of all socket implementations.
If SO_REUSEADDR
is enabled on a socket prior to binding it, the socket can be successfully bound unless there is a conflict with another socket bound to exactly the same combination of source address and port. Now you may wonder how is that any different than before? The keyword is "exactly". SO_REUSEADDR
mainly changes the way how wildcard addresses ("any IP address") are treated when searching for conflicts.
Without SO_REUSEADDR
, binding socketA
to 0.0.0.0:21
and then binding socketB
to 192.168.0.1:21
will fail (with error EADDRINUSE
), since 0.0.0.0 means "any local IP address", thus all local IP addresses are considered in use by this socket and this includes 192.168.0.1
, too. With SO_REUSEADDR
it will succeed, since 0.0.0.0
and 192.168.0.1
are not exactly the same address, one is a wildcard for all local addresses and the other one is a very specific local address. Note that the statement above is true regardless in which order socketA
and socketB
are bound; without SO_REUSEADDR
it will always fail, with SO_REUSEADDR
it will always succeed.
To give you a better overview, let's make a table here and list all possible combinations:
SO_REUSEADDR socketA socketB Result --------------------------------------------------------------------- ON/OFF 192.168.0.1:21 192.168.0.1:21 Error (EADDRINUSE) ON/OFF 192.168.0.1:21 10.0.0.1:21 OK ON/OFF 10.0.0.1:21 192.168.0.1:21 OK OFF 0.0.0.0:21 192.168.1.0:21 Error (EADDRINUSE) OFF 192.168.1.0:21 0.0.0.0:21 Error (EADDRINUSE) ON 0.0.0.0:21 192.168.1.0:21 OK ON 192.168.1.0:21 0.0.0.0:21 OK ON/OFF 0.0.0.0:21 0.0.0.0:21 Error (EADDRINUSE)
The table above assumes that socketA
has already been successfully bound to the address given for socketA
, then socketB
is created, either gets SO_REUSEADDR
set or not, and finally is bound to the address given for socketB
. Result
is the result of the bind operation for socketB
. If the first column says ON/OFF
, the value of SO_REUSEADDR
is irrelevant to the result.
Okay, SO_REUSEADDR
has an effect on wildcard addresses, good to know. Yet that isn't it's only effect it has. There is another well known effect which is also the reason why most people use SO_REUSEADDR
in server programs in the first place. For the other important use of this option we have to take a deeper look on how the TCP protocol works.
A socket has a send buffer and if a call to the send()
function succeeds, it does not mean that the requested data has actually really been sent out, it only means the data has been added to the send buffer. For UDP sockets, the data is usually sent pretty soon, if not immediately, but for TCP sockets, there can be a relatively long delay between adding data to the send buffer and having the TCP implementation really send that data. As a result, when you close a TCP socket, there may still be pending data in the send buffer, which has not been sent yet but your code considers it as sent, since the send()
call succeeded. If the TCP implementation was closing the socket immediately on your request, all of this data would be lost and your code wouldn't even know about that. TCP is said to be a reliable protocol and losing data just like that is not very reliable. That's why a socket that still has data to send will go into a state called TIME_WAIT
when you close it. In that state it will wait until all pending data has been successfully sent or until a timeout is hit, in which case the socket is closed forcefully.
At most, the amount of time the kernel will wait before it closes the socket, regardless if it still has data in flight or not, is called the Linger Time. The Linger Time is globally configurable on most systems and by default rather long (two minutes is a common value you will find on many systems). It is also configurable per socket using the socket option SO_LINGER
which can be used to make the timeout shorter or longer, and even to disable it completely. Disabling it completely is a very bad idea, though, since closing a TCP socket gracefully is a slightly complex process and involves sending forth and back a couple of packets (as well as resending those packets in case they got lost) and this whole close process is also limited by the Linger Time. If you disable lingering, your socket may not only lose data in flight, it is also always closed forcefully instead of gracefully, which is usually not recommended. The details about how a TCP connection is closed gracefully are beyond the scope of this answer, if you want to learn more about, I recommend you have a look at this page. And even if you disabled lingering with SO_LINGER
, if your process dies without explicitly closing the socket, BSD (and possibly other systems) will linger nonetheless, ignoring what you have configured. This will happen for example if your code just calls exit()
(pretty common for tiny, simple server programs) or the process is killed by a signal (which includes the possibility that it simply crashes because of an illegal memory access). So there is nothing you can do to make sure a socket will never linger under all circumstances.
The question is, how does the system treat a socket in state TIME_WAIT
? If SO_REUSEADDR
is not set, a socket in state TIME_WAIT
is considered to still be bound to the source address and port and any attempt to bind a new socket to the same address and port will fail until the socket has really been closed, which may take as long as the configured Linger Time. So don't expect that you can rebind the source address of a socket immediately after closing it. In most cases this will fail. However, if SO_REUSEADDR
is set for the socket you are trying to bind, another socket bound to the same address and port in state TIME_WAIT
is simply ignored, after all its already "half dead", and your socket can bind to exactly the same address without any problem. In that case it plays no role that the other socket may have exactly the same address and port. Note that binding a socket to exactly the same address and port as a dying socket in TIME_WAIT
state can have unexpected, and usually undesired, side effects in case the other socket is still "at work", but that is beyond the scope of this answer and fortunately those side effects are rather rare in practice.
There is one final thing you should know about SO_REUSEADDR
. Everything written above will work as long as the socket you want to bind to has address reuse enabled. It is not necessary that the other socket, the one which is already bound or is in a TIME_WAIT
state, also had this flag set when it was bound. The code that decides if the bind will succeed or fail only inspects the SO_REUSEADDR
flag of the socket fed into the bind()
call, for all other sockets inspected, this flag is not even looked at.
SO_REUSEPORT
is what most people would expect SO_REUSEADDR
to be. Basically, SO_REUSEPORT
allows you to bind an arbitrary number of sockets to exactly the same source address and port as long as all prior bound sockets also had SO_REUSEPORT
set before they were bound. If the first socket that is bound to an address and port does not have SO_REUSEPORT
set, no other socket can be bound to exactly the same address and port, regardless if this other socket has SO_REUSEPORT
set or not, until the first socket releases its binding again. Unlike in case of SO_REUESADDR
the code handling SO_REUSEPORT
will not only verify that the currently bound socket has SO_REUSEPORT
set but it will also verify that the socket with a conflicting address and port had SO_REUSEPORT
set when it was bound.
SO_REUSEPORT
does not imply SO_REUSEADDR
. This means if a socket did not have SO_REUSEPORT
set when it was bound and another socket has SO_REUSEPORT
set when it is bound to exactly the same address and port, the bind fails, which is expected, but it also fails if the other socket is already dying and is in TIME_WAIT
state. To be able to bind a socket to the same addresses and port as another socket in TIME_WAIT
state requires either SO_REUSEADDR
to be set on that socket or SO_REUSEPORT
must have been set on both sockets prior to binding them. Of course it is allowed to set both, SO_REUSEPORT
and SO_REUSEADDR
, on a socket.
There is not much more to say about SO_REUSEPORT
other than that it was added later than SO_REUSEADDR
, that's why you will not find it in many socket implementations of other systems, which "forked" the BSD code before this option was added, and that there was no way to bind two sockets to exactly the same socket address in BSD prior to this option.
Most people know that bind()
may fail with the error EADDRINUSE
, however, when you start playing around with address reuse, you may run into the strange situation that connect()
fails with that error as well. How can this be? How can a remote address, after all that's what connect adds to a socket, be already in use? Connecting multiple sockets to exactly the same remote address has never been a problem before, so what's going wrong here?
As I said on the very top of my reply, a connection is defined by a tuple of five values, remember? And I also said, that these five values must be unique otherwise the system cannot distinguish two connections any longer, right? Well, with address reuse, you can bind two sockets of the same protocol to the same source address and port. That means three of those five values are already the same for these two sockets. If you now try to connect both of these sockets also to the same destination address and port, you would create two connected sockets, whose tuples are absolutely identical. This cannot work, at least not for TCP connections (UDP connections are no real connections anyway). If data arrived for either one of the two connections, the system could not tell which connection the data belongs to. At least the destination address or destination port must be different for either connection, so that the system has no problem to identify to which connection incoming data belongs to.
So if you bind two sockets of the same protocol to the same source address and port and try to connect them both to the same destination address and port, connect()
will actually fail with the error EADDRINUSE
for the second socket you try to connect, which means that a socket with an identical tuple of five values is already connected.
Most people ignore the fact that multicast addresses exist, but they do exist. While unicast addresses are used for one-to-one communication, multicast addresses are used for one-to-many communication. Most people got aware of multicast addresses when they learned about IPv6 but multicast addresses also existed in IPv4, even though this feature was never widely used on the public Internet.
The meaning of SO_REUSEADDR
changes for multicast addresses as it allows multiple sockets to be bound to exactly the same combination of source multicast address and port. In other words, for multicast addresses SO_REUSEADDR
behaves exactly as SO_REUSEPORT
for unicast addresses. Actually, the code treats SO_REUSEADDR
and SO_REUSEPORT
identically for multicast addresses, that means you could say that SO_REUSEADDR
implies SO_REUSEPORT
for all multicast addresses and the other way round.
All these are rather late forks of the original BSD code, that's why they all three offer the same options as BSD and they also behave the same way as in BSD.
At its core, macOS is simply a BSD-style UNIX named "Darwin", based on a rather late fork of the BSD code (BSD 4.3), which was then later on even re-synchronized with the (at that time current) FreeBSD 5 code base for the Mac OS 10.3 release, so that Apple could gain full POSIX compliance (macOS is POSIX certified). Despite having a microkernel at its core ("Mach"), the rest of the kernel ("XNU") is basically just a BSD kernel, and that's why macOS offers the same options as BSD and they also behave the same way as in BSD.
iOS is just a macOS fork with a slightly modified and trimmed kernel, somewhat stripped down user space toolset and a slightly different default framework set. watchOS and tvOS are iOS forks, that are stripped down even further (especially watchOS). To my best knowledge they all behave exactly as macOS does.
Prior to Linux 3.9, only the option SO_REUSEADDR
existed. This option behaves generally the same as in BSD with two important exceptions:
As long as a listening (server) TCP socket is bound to a specific port, the SO_REUSEADDR
option is entirely ignored for all sockets targeting that port. Binding a second socket to the same port is only possible if it was also possible in BSD without having SO_REUSEADDR
set. E.g. you cannot bind to a wildcard address and then to a more specific one or the other way round, both is possible in BSD if you set SO_REUSEADDR
. What you can do is you can bind to the same port and two different non-wildcard addresses, as that's always allowed. In this aspect Linux is more restrictive than BSD.
The second exception is that for client sockets, this option behaves exactly like SO_REUSEPORT
in BSD, as long as both had this flag set before they were bound. The reason for allowing that was simply that it is important to be able to bind multiple sockets to exactly to the same UDP socket address for various protocols and as there used to be no SO_REUSEPORT
prior to 3.9, the behavior of SO_REUSEADDR
was altered accordingly to fill that gap. In that aspect Linux is less restrictive than BSD.
Linux 3.9 added the option SO_REUSEPORT
to Linux as well. This option behaves exactly like the option in BSD and allows binding to exactly the same address and port number as long as all sockets have this option set prior to binding them.
Yet, there are still two differences to SO_REUSEPORT
on other systems:
To prevent "port hijacking", there is one special limitation: All sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! So one user cannot "steal" ports of another user. This is some special magic to somewhat compensate for the missing SO_EXCLBIND
/SO_EXCLUSIVEADDRUSE
flags.
Additionally the kernel performs some "special magic" for SO_REUSEPORT
sockets that isn't found in other operating systems: For UDP sockets, it tries to distribute datagrams evenly, for TCP listening sockets, it tries to distribute incoming connect requests (those accepted by calling accept()
) evenly across all the sockets that share the same address and port combination. Thus an application can easily open the same port in multiple child processes and then use SO_REUSEPORT
to get a very inexpensive load balancing.
Even though the whole Android system is somewhat different from most Linux distributions, at its core works a slightly modified Linux kernel, thus everything that applies to Linux should apply to Android as well.
Windows only knows the SO_REUSEADDR
option, there is no SO_REUSEPORT
. Setting SO_REUSEADDR
on a socket in Windows behaves like setting SO_REUSEPORT
and SO_REUSEADDR
on a socket in BSD, with one exception:
Prior to Windows 2003, a socket with SO_REUSEADDR
could always been bound to exactly the same source address and port as an already bound socket, even if the other socket did not have this option set when it was bound. This behavior allowed an application "to steal" the connected port of another application. Needless to say that this has major security implications!
Microsoft realized that and added another important socket option: SO_EXCLUSIVEADDRUSE
. Setting SO_EXCLUSIVEADDRUSE
on a socket makes sure that if the binding succeeds, the combination of source address and port is owned exclusively by this socket and no other socket can bind to them, not even if it has SO_REUSEADDR
set.
This default behavior was changed first in Windows 2003, Microsoft calls that "Enhanced Socket Security" (funny name for a behavior that is default on all other major operating systems). For more details just visit this page. There are three tables: The first one shows the classic behavior (still in use when using compatibility modes!), the second one shows the behavior of Windows 2003 and up when the bind()
calls are made by the same user, and the third one when the bind()
calls are made by different users.
Solaris is the successor of SunOS. SunOS was originally based on a fork of BSD, SunOS 5 and later was based on a fork of SVR4, however SVR4 is a merge of BSD, System V, and Xenix, so up to some degree Solaris is also a BSD fork, and a rather early one. As a result Solaris only knows SO_REUSEADDR
, there is no SO_REUSEPORT
. The SO_REUSEADDR
behaves pretty much the same as it does in BSD. As far as I know there is no way to get the same behavior as SO_REUSEPORT
in Solaris, that means it is not possible to bind two sockets to exactly the same address and port.
Similar to Windows, Solaris has an option to give a socket an exclusive binding. This option is named SO_EXCLBIND
. If this option is set on a socket prior to binding it, setting SO_REUSEADDR
on another socket has no effect if the two sockets are tested for an address conflict. E.g. if socketA
is bound to a wildcard address and socketB
has SO_REUSEADDR
enabled and is bound to a non-wildcard address and the same port as socketA
, this bind will normally succeed, unless socketA
had SO_EXCLBIND
enabled, in which case it will fail regardless the SO_REUSEADDR
flag of socketB
.
In case your system is not listed above, I wrote a little test program that you can use to find out how your system handles these two options. Also if you think my results are wrong, please first run that program before posting any comments and possibly making false claims.
All that the code requires to build is a bit POSIX API (for the network parts) and a C99 compiler (actually most non-C99 compiler will work as well as long as they offer inttypes.h
and stdbool.h
; e.g. gcc
supported both long before offering full C99 support).
All that the program needs to run is that at least one interface in your system (other than the local interface) has an IP address assigned and that a default route is set which uses that interface. The program will gather that IP address and use it as the second "specific address".
It tests all possible combinations you can think of:
SO_REUSEADDR
set on socket1, socket2, or both socketsSO_REUSEPORT
set on socket1, socket2, or both sockets0.0.0.0
(wildcard), 127.0.0.1
(specific address), and the second specific address found at your primary interface (for multicast it's just 224.1.2.3
in all tests)and prints the results in a nice table. It will also work on systems that don't know SO_REUSEPORT
, in which case this option is simply not tested.
What the program cannot easily test is how SO_REUSEADDR
acts on sockets in TIME_WAIT
state as it's very tricky to force and keep a socket in that state. Fortunately most operating systems seems to simply behave like BSD here and most of the time programmers can simply ignore the existence of that state.
Here's the code (I cannot include it here, answers have a size limit and the code would push this reply over the limit).
For the same reason C# doesn't allow multiple inheritence but allows you to implement multiple interfaces.
The lesson learned from C++ w/ multiple inheritence was that it lead to more issues than it was worth.
An interface is a contract of things your class has to implement. You don't gain any functionality from the interface. Inheritence allows you to inherit the functionality of a parent class (and in multiple-inheritence, that can get extremely confusing).
Allowing multiple interfaces allows you to use Design Patterns (like Adapter) to solve the same types of issues you can solve using multiple inheritence, but in a much more reliable and predictable manner.
System.Windows.Forms.MessageBox.Show("My message here");
Make sure the System.Windows.Forms
assembly is referenced your project.
I just wrapped the navbar in a
<div width="100%">
<div class="nav-? ??">
...
</nav>
</div>
No fancy hocus pocus but it worked..
Are you talking about code within <script>
tags, or in the HTML tag attributes, like this?
<a href="#" onclick="alert('this is inline JS');return false;">Click</a>
Either way, the debugger
keyword like this will work:
<a href="#" onclick="debugger; alert('this is inline JS');return false;">Click</a>
N.B. Chrome won't pause at debugger
s if the dev tools are not open.
You can also set property breakpoints in JS files and <script>
tags:
Try my JavaScript hash table implementation: http://www.timdown.co.uk/jshashtable
It looks for a hashCode() method of key objects, or you can supply a hashing function when creating a Hashtable object.
You just need to add one more attribute to your DIV tag which is
data-interval="false"
no need to touch JS!
You can use cvResize
. Or better use c++ interface (eg cv::Mat
instead of IplImage
and cv::imread
instead of cvLoadImage
) and then use cv::resize
which handles memory allocation and deallocation itself.
Example of prepending in-place:
var A = [7,8,9]_x000D_
var B = [1,2,3]_x000D_
_x000D_
A.unshift(...B)_x000D_
_x000D_
console.log(A) // [1,2,3,7,8,9]
_x000D_
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i
is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count
to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count
or i
. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring
returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
This should disconnect everyone else, and leave you as the only user:
alter database YourDb set single_user with rollback immediate
Note: Don't forget
alter database YourDb set MULTI_USER
after you're done!
You say in a comment you want to get "15.09.2016".
For this, use Date
and DateFormatter
:
let date = Date()
let formatter = DateFormatter()
Give the format you want to the formatter:
formatter.dateFormat = "dd.MM.yyyy"
Get the result string:
let result = formatter.string(from: date)
Set your label:
label.text = result
Result:
15.09.2016
All you need to do is add \n or to write on files go \r\n.
Examples:
say you wanted to write duck(line break) cow this is how you would do it Console.WriteLine("duck\n cow");
Edit: I think I didn't understand the question. You can use
@"duck
cow".Replace("\r\n", "")
as a linebreak in code, that produces \r\n which is used Windows.
The method show()
must be called from the User-Interface (UI) thread, while doInBackground()
runs on different thread which is the main reason why AsyncTask
was designed.
You have to call show()
either in onProgressUpdate()
or in onPostExecute()
.
For example:
class ExampleTask extends AsyncTask<String, String, String> {
// Your onPreExecute method.
@Override
protected String doInBackground(String... params) {
// Your code.
if (condition_is_true) {
this.publishProgress("Show the dialog");
}
return "Result";
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
}
}
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server
For specific versions, such as mysql-server-5.6
, you'll need to specify the version in like this:
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6
For mysql-community-server, the keys are slightly different:
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server
Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)
If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:
echo ... | sudo debconf-set-selections
Here are a couple functions I wrote to get a file in a json format which can be passed around easily:
//takes an array of JavaScript File objects
function getFiles(files) {
return Promise.all(files.map(file => getFile(file)));
}
//take a single JavaScript File object
function getFile(file) {
var reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
reader.onload = function () {
//This will result in an array that will be recognized by C#.NET WebApi as a byte[]
let bytes = Array.from(new Uint8Array(this.result));
//if you want the base64encoded file you would use the below line:
let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));
//Resolve the promise with your custom file structure
resolve({
bytes: bytes,
base64StringFile: base64StringFile,
fileName: file.name,
fileType: file.type
});
}
reader.readAsArrayBuffer(file);
});
}
//using the functions with your file:
file = document.querySelector('#files > input[type="file"]').files[0]
getFile(file).then((customJsonFile) => {
//customJsonFile is your newly constructed file.
console.log(customJsonFile);
});
//if you are in an environment where async/await is supported
files = document.querySelector('#files > input[type="file"]').files
let customJsonFiles = await getFiles(files);
//customJsonFiles is an array of your custom files
console.log(customJsonFiles);
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
There's nothing inherently wrong with testing threaded/async code, particularly if threading is the point of the code you're testing. The general approach to testing this stuff is to:
But that's a lot of boilerplate for one test. A better/simpler approach is to just use ConcurrentUnit:
final Waiter waiter = new Waiter();
new Thread(() -> {
doSomeWork();
waiter.assertTrue(true);
waiter.resume();
}).start();
// Wait for resume() to be called
waiter.await(1000);
The benefit of this over the CountdownLatch
approach is that it's less verbose since assertion failures that occur in any thread are properly reported to the main thread, meaning the test fails when it should. A writeup that compares the CountdownLatch
approach to ConcurrentUnit is here.
I also wrote a blog post on the topic for those who want to learn a bit more detail.
For a String constant you have no choice other than escaping via backslash.
Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.
It has already been mentioned how to remove a single element from a list and which advantages the different methods have. Note, however, that removing multiple elements has some potential for errors:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]
Elements 3 and 8 (not 3 and 7) of the original list have been removed (as the list was shortened during the loop), which might not have been the intention. If you want to safely remove multiple indices you should instead delete the elements with highest index first, e.g. like this:
>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
... del l[i]
...
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]
The following works on 2008R2+ to produce 'HH:MM':
select
case
when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]
Proximity Sensor Dial
*#*#7378423#*#*
1) Service Tests - (If present)
2) Proximity Switch
3) Test on sensor (Next to logo(top) of mobile)
4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery
OR
4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.
Technically, Its not any software solution, but hardware solution will work.
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
var gandalf = {
"real name": "Gandalf",
"age (est)": 11000,
"race": "Maia",
"haveRetirementPlan": true,
"aliases": [
"Greyhame",
"Stormcrow",
"Mithrandir",
"Gandalf the Grey",
"Gandalf the White"
]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
I am migrating from V1 to V2 of Google Maps. I was getting this failure trying to run the app via Eclipse. The root cause for me was using my release certificate keystore rather than the Android debug keystore which is what gets used when you run it via Eclipse. The following command (OSX/Linux) will get you the SHA1 key of the debug keystore:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
If you are using Windows 7 instead, you would use this command:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
It is probably best to uninstall your app completely from your device before trying with a new key as Android caches the security credentials.
intel mkl suggests in-place and out-of-place transposition/copying matrices. here is the link to the documentation. I would recommend trying out of place implementation as faster ten in-place and into the documentation of the latest version of mkl contains some mistakes.
Kafka ships with some tools you can use to accomplish this.
List topics:
# ./bin/kafka-topics.sh --list --zookeeper localhost:2181
test_topic_1
test_topic_2
...
List partitions and offsets:
# ./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --broker-info --group test_group --topic test_topic --zookeeper localhost:2181
Group Topic Pid Offset logSize Lag Owner
test_group test_topic 0 698020 698021 1 test_group-0
test_group test_topic 1 235699 235699 0 test_group-1
test_group test_topic 2 117189 117189 0 test_group-2
If you're using the new apis, there's a new tool you can use: kafka-consumer-groups.sh
.
./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group count_errors --describe
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG OWNER
count_errors logs 2 2908278 2908278 0 consumer-1_/10.8.0.55
count_errors logs 3 2907501 2907501 0 consumer-1_/10.8.0.43
count_errors logs 4 2907541 2907541 0 consumer-1_/10.8.0.177
count_errors logs 1 2907499 2907499 0 consumer-1_/10.8.0.115
count_errors logs 0 2907469 2907469 0 consumer-1_/10.8.0.126
I had overcome this issue, and my sample code is as follows.
Add the below line in your Main Activity, here BackGroundClass is the service class.You can create this class in New -> JavaClass (In this class, add the process (tasks) in which you needs to occur at background). For Convenience, first denote them with notification ringtone as background process.
startService(new Intent(this, BackGroundClass .class));
In the BackGroundClass, just include my codings and you may see the result.
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class BackgroundService extends Service {
private MediaPlayer player;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
And in AndroidManifest.xml, try to add this.
<service android:name=".BackgroundService"/>
Run the program, just open the application, you may find the notification alert at the background. Even, you may exit the application but still you might have hear the ringtone alert unless and until if you switched off the application or Uninstall the application. This denotes that the notification alert is at the background process. Like this you may add some process for background.
Kind Attention: Please, Don't verify with TOAST as it will run only once even though it was at background process.
Hope it will helps...!!
A much more robust way would be to use the getline()
function of GNU awk
to use a variable from a pipe. In form cmd | getline
result, cmd
is run, then its output is piped to getline
. It returns 1
if got output, 0
if EOF, -1
on failure.
First construct the command to run in a variable in the BEGIN
clause if the command is not dependant on the contents of the file, e.g. a simple date
or an ls
.
A simple example of the above would be
awk 'BEGIN {
cmd = "ls -lrth"
while ( ( cmd | getline result ) > 0 ) {
print result
}
close(cmd);
}'
When the command to run is part of the columnar content of a file, you generate the cmd
string in the main {..}
as below. E.g. consider a file whose $2
contains the name of the file and you want it to be replaced with the md5sum
hash content of the file. You can do
awk '{ cmd = "md5sum "$2
while ( ( cmd | getline md5result ) > 0 ) {
$2 = md5result
}
close(cmd);
}1'
Another frequent usage involving external commands in awk
is during date
processing when your awk
does not support time functions out of the box with mktime()
, strftime()
functions.
Consider a case when you have Unix EPOCH timestamp stored in a column and you want to convert that to a human readable date format. Assuming GNU date
is available
awk '{ cmd = "date -d @" $1 " +\"%d-%m-%Y %H:%M:%S\""
while ( ( cmd | getline fmtDate) > 0 ) {
$1 = fmtDate
}
close(cmd);
}1'
for an input string as
1572608319 foo bar zoo
the above command produces an output as
01-11-2019 07:38:39 foo bar zoo
The command can be tailored to modify the date
fields on any of the columns in a given line. Note that -d
is a GNU specific extension, the *BSD variants support -f
( though not exactly similar to -d
).
More information about getline
can be referred to from this AllAboutGetline article at awk.freeshell.org page.
Add this method to a static class:
public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false)
{
var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0));
if (relativeToScreen)
{
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0));
absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y);
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
Set relativeToScreen
paramater to true
for placement from top left corner of whole screen or to false
for placement from top left corner of application window.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
THIRD VERSION OF MY ANSWER:
Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -
. This is a flash message example that I use in a partial. Hope this helps!
-if(typeof(info) !== 'undefined')
-if (info)
- if(info.length){
ul
-info.forEach(function(info){
li= info
-})
-}
Is the code you're trying to get to compile the code in your question?
If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -
; second, after you type -if
you don't need to type the {
or }
either. That's what makes Jade pretty sweet.
--------------ORIGINAL ANSWER BELOW ---------------
Try prepending if
with -
:
-if(10 == 10)
//do whatever you want here as long as it's indented two spaces from
the `-` above
There are also tons of Jade examples at:
Here is a more strict version:
^([-+]?\d{1,2}[.]\d+),\s*([-+]?\d{1,3}[.]\d+)$
-90
-- +90
-180
-- +180
Following what @viveknuna suggested, I upgraded to the latest version of node.js and npm using the downloaded installer. I also installed the latest version of yarn using a downloaded installer. Then, as you can see below, I upgraded angular-cli and typescript. Here's what that process looked like:
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g @angular/cli@latest
C:\Users\Jack\AppData\Roaming\npm\ng -> C:\Users\Jack\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ @angular/[email protected]
added 75 packages, removed 166 packages, updated 61 packages and moved 24 packages in 29.084s
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g typescript
C:\Users\Jack\AppData\Roaming\npm\tsserver -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\Jack\AppData\Roaming\npm\tsc -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
updated 1 package in 2.427s
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>node -v
v8.10.0
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm -v
5.6.0
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn --version
1.5.1
Thereafter, I ran yarn
and npm start
in my angular folder and all appears to be well. Here's what that looked like:
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn
yarn install v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning " > [email protected]" has incorrect peer dependency "@angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0".
warning " > [email protected]" has incorrect peer dependency "@angular/core@^2.3.1 || >=4.0.0-beta <5.0.0".
[4/4] Building fresh packages...
Done in 232.79s.
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm start
> [email protected] start D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular
> ng serve --host 0.0.0.0 --port 4200
** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ **
Date: 2018-03-22T13:17:28.935Z
Hash: 8f226b6fa069b7c201ea
Time: 22494ms
chunk {account.module} account.module.chunk.js () 129 kB [rendered]
chunk {app.module} app.module.chunk.js () 497 kB [rendered]
chunk {common} common.chunk.js (common) 1.46 MB [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 515 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.1 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.53 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 15.1 MB [initial] [rendered]
webpack: Compiled successfully.
Not an answer, per se, but an observation that seems to have been overlooked.
The description for carat ranges:
see: https://github.com/npm/node-semver#caret-ranges-123-025-004
Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple.
Means that ^10.2.3
matches 10.2.3 <= v < 20.0.0
I don't think that's what they meant. Pulling in versions 11.x.x through 19.x.x will break your code.
I think they meant left most non-zero number field
. There is nothing in SemVer that requires number-fields to be single-digit.
It could have something to do with your styles. In my case, I am using a link within the parent "item" div, so I had to change my stylesheet to say the following:
.carousel .item a > img {
display: block;
line-height: 1;
}
under the preexisting boostrap code:
.carousel .item > img {
display: block;
line-height: 1;
}
and my image looks like:
<div class="active item" id="2"><a href="http://epdining.com/eats.php?place=TestRestaurant1"><img src="rimages/2.jpg"></a><div class="carousel-caption"><p>This restaurant is featured blah blah blah blah blah.</p></div></div>
If you want to add row
before the <tr>
first child.
$("#myTable > tbody").prepend("<tr><td>my data</td><td>more data</td></tr>");
If you want to add row
after the <tr>
last child.
$("#myTable > tbody").append("<tr><td>my data</td><td>more data</td></tr>");
React TypeScript with Hooks
From a Class
this.history.push({
pathname: "/unauthorized",
state: { message: "Hello" },
});
UnAuthorized Functional Component
interface IState {
message?: string;
}
export default function UnAuthorized() {
const location = useLocation();
const message = (location.state as IState).message;
return (
<div className="jumbotron">
<h6>{message}</h6>
</div>
);
}
JLabel is actually capable of displaying some rudimentary HTML, which is why it is not responding to your use of the newline character (unlike, say, System.out).
If you put in the corresponding HTML and used <BR>
, you would get your newlines.
And what about:
if ($('#dataTable[data-timer]').length > 0) {
// logic here
}
To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
If you care for it to be in the same order as before you can use a common table expression for that:
;WITH CTE AS (
SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC
)
SELECT *
FROM CTE
ORDER BY MySortColumn
Alternatively to German Attanasio Ruiz's answer, you can eliminate the 2nd loop by using Array.reduce() instead of Array.map();
var Data = [
{ name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -1);
It's important to understand that there are two aspects to thread safety.
The first has to do with controlling when code executes (including the order in which instructions are executed) and whether it can execute concurrently, and the second to do with when the effects in memory of what has been done are visible to other threads. Because each CPU has several levels of cache between it and main memory, threads running on different CPUs or cores can see "memory" differently at any given moment in time because threads are permitted to obtain and work on private copies of main memory.
Using synchronized
prevents any other thread from obtaining the monitor (or lock) for the same object, thereby preventing all code blocks protected by synchronization on the same object from executing concurrently. Synchronization also creates a "happens-before" memory barrier, causing a memory visibility constraint such that anything done up to the point some thread releases a lock appears to another thread subsequently acquiring the same lock to have happened before it acquired the lock. In practical terms, on current hardware, this typically causes flushing of the CPU caches when a monitor is acquired and writes to main memory when it is released, both of which are (relatively) expensive.
Using volatile
, on the other hand, forces all accesses (read or write) to the volatile variable to occur to main memory, effectively keeping the volatile variable out of CPU caches. This can be useful for some actions where it is simply required that visibility of the variable be correct and order of accesses is not important. Using volatile
also changes treatment of long
and double
to require accesses to them to be atomic; on some (older) hardware this might require locks, though not on modern 64 bit hardware. Under the new (JSR-133) memory model for Java 5+, the semantics of volatile have been strengthened to be almost as strong as synchronized with respect to memory visibility and instruction ordering (see http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#volatile). For the purposes of visibility, each access to a volatile field acts like half a synchronization.
Under the new memory model, it is still true that volatile variables cannot be reordered with each other. The difference is that it is now no longer so easy to reorder normal field accesses around them. Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread
A
when it writes to volatile fieldf
becomes visible to threadB
when it readsf
.
So, now both forms of memory barrier (under the current JMM) cause an instruction re-ordering barrier which prevents the compiler or run-time from re-ordering instructions across the barrier. In the old JMM, volatile did not prevent re-ordering. This can be important, because apart from memory barriers the only limitation imposed is that, for any particular thread, the net effect of the code is the same as it would be if the instructions were executed in precisely the order in which they appear in the source.
One use of volatile is for a shared but immutable object is recreated on the fly, with many other threads taking a reference to the object at a particular point in their execution cycle. One needs the other threads to begin using the recreated object once it is published, but does not need the additional overhead of full synchronization and it's attendant contention and cache flushing.
// Declaration
public class SharedLocation {
static public SomeObject someObject=new SomeObject(); // default object
}
// Publishing code
// Note: do not simply use SharedLocation.someObject.xxx(), since although
// someObject will be internally consistent for xxx(), a subsequent
// call to yyy() might be inconsistent with xxx() if the object was
// replaced in between calls.
SharedLocation.someObject=new SomeObject(...); // new object is published
// Using code
private String getError() {
SomeObject myCopy=SharedLocation.someObject; // gets current copy
...
int cod=myCopy.getErrorCode();
String txt=myCopy.getErrorText();
return (cod+" - "+txt);
}
// And so on, with myCopy always in a consistent state within and across calls
// Eventually we will return to the code that gets the current SomeObject.
Speaking to your read-update-write question, specifically. Consider the following unsafe code:
public void updateCounter() {
if(counter==1000) { counter=0; }
else { counter++; }
}
Now, with the updateCounter() method unsynchronized, two threads may enter it at the same time. Among the many permutations of what could happen, one is that thread-1 does the test for counter==1000 and finds it true and is then suspended. Then thread-2 does the same test and also sees it true and is suspended. Then thread-1 resumes and sets counter to 0. Then thread-2 resumes and again sets counter to 0 because it missed the update from thread-1. This can also happen even if thread switching does not occur as I have described, but simply because two different cached copies of counter were present in two different CPU cores and the threads each ran on a separate core. For that matter, one thread could have counter at one value and the other could have counter at some entirely different value just because of caching.
What's important in this example is that the variable counter was read from main memory into cache, updated in cache and only written back to main memory at some indeterminate point later when a memory barrier occurred or when the cache memory was needed for something else. Making the counter volatile
is insufficient for thread-safety of this code, because the test for the maximum and the assignments are discrete operations, including the increment which is a set of non-atomic read+increment+write
machine instructions, something like:
MOV EAX,counter
INC EAX
MOV counter,EAX
Volatile variables are useful only when all operations performed on them are "atomic", such as my example where a reference to a fully formed object is only read or written (and, indeed, typically it's only written from a single point). Another example would be a volatile array reference backing a copy-on-write list, provided the array was only read by first taking a local copy of the reference to it.
Here's a simple lock mechanism, implemented via closure
const createLock = () => {
let lockStatus = false
const release = () => {
lockStatus = false
}
const acuire = () => {
if (lockStatus == true)
return false
lockStatus = true
return true
}
return {
lockStatus: lockStatus,
acuire: acuire,
release: release,
}
}
lock = createLock() // create a lock
lock.acuire() // acuired a lock
if (lock.acuire()){
console.log("Was able to acuire");
} else {
console.log("Was not to acuire"); // This will execute
}
lock.release() // now the lock is released
if(lock.acuire()){
console.log("Was able to acuire"); // This will execute
} else {
console.log("Was not to acuire");
}
lock.release() // Hey don't forget to release
_x000D_
Or install syswin package, which includes a port of su for cygwin: http://sourceforge.net/p/manufacture/wiki/syswin-su/
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
MD5 is a cryptographic (one-way) hash function, so there is no direct way to decode it. The entire purpose of a cryptographic hash function is that you can't undo it.
One thing you can do is a brute-force strategy, where you guess what was hashed, then hash it with the same function and see if it matches. Unless the hashed data is very easy to guess, it could take a long time though.
wtsang02 answer is the best way to go about it, since, Html.fromHtml("") is now deprecated. Here I'm just going to enhance it a little bit for whoever is having problem in dynamically making the first word bold, no matter whats the size of the sentence.
First lets create a method to get the first word:
private String getFirstWord(String input){
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' '){
return input.substring(0, i);
}
}
return input;
}
Now let's say you have a long string like this:
String sentence = "[email protected] want's to be your friend!"
And you want your sentence to be like [email protected] want's to be your friend! All you have to do is- get the firstWord and get the lenght of it to make the firstWord bold, something like this:
String myFirstWord = getFirstWord(sentence);
int start = 0; // bold will start at index 0
int end = myFirstWord.length(); // and will finish at whatever the length of your first word
Now just follow wtsang02 's steps, like this:
SpannableStringBuilder fancySentence = new SpannableStringBuilder(sentence);
fancySentence.setSpan(new android.text.style.StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(fancySentence);
And that's it! Now you should be able to bold a word with any size from long/short sentence. Hope it will help someone, happy coding :)
While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.
Do following steps:
1. Type c:
then press enter
2. cd program files
3. cd "choose your own folder name"
then continue as you wish.
This way you can create batch file and you can mention program files folder.
Building on the answer by @Dion Truter and @Wade Williams, the following shell script will drop all tables, after first showing what it is about to run, and giving you a chance to abort using Ctrl-C.
#!/bin/bash
DB_HOST=xxx
DB_USERNAME=xxx
DB_PASSWORD=xxx
DB_NAME=xxx
CMD="mysql -sN -h ${DB_HOST} -u ${DB_USERNAME} -p${DB_PASSWORD} ${DB_NAME}"
# Generate the drop statements
TMPFILE=/tmp/drop-${RANDOM}.sql
echo 'SET FOREIGN_KEY_CHECKS = 0;' > ${TMPFILE}
${CMD} $@ >> ${TMPFILE} << ENDD
SELECT concat('DROP TABLE IF EXISTS \`', table_name, '\`;')
FROM information_schema.tables
WHERE table_schema = '${DB_NAME}';
ENDD
echo 'SET FOREIGN_KEY_CHECKS = 1;' >> ${TMPFILE}
# Warn what we are about to do
echo
cat ${TMPFILE}
echo
echo "Press ENTER to proceed (or Ctrl-C to abort)."
read
# Run the SQL
echo "Dropping tables..."
${CMD} $@ < ${TMPFILE}
echo "Exit status is ${?}."
rm ${TMPFILE}
Sometimes you can simply typecast:
// this is the value of my $xml
object(SimpleXMLElement)#10227 (1) {
[0]=>
string(2) "en"
}
$s = (string) $xml; // returns "en";
A small refinement of Kyle Burton's answer with improved output formatting:
#!/bin/bash
for user in $(cut -f1 -d: /etc/passwd)
do echo $user && crontab -u $user -l
echo " "
done
Make sure you don't have a minSdkVersion
set in your build.gradle
with a value higher than 8. If you don't specify it at all, it's supposed to use the value in your AndroidManfiest.xml
, which seems to already be properly set.
the css property of <hr>
are :
hr {
-moz-border-bottom-colors: none;
-moz-border-image: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
border-color: #EEEEEE -moz-use-text-color #FFFFFF;
border-style: solid none;
border-width: 1px 0;
margin: 18px 0;
}
It correspond to a 1px horizontal line with a very light grey and vertical margin of 18px.
and because <hr>
is inside a <div>
without class the width depends on the content of the <div>
if you would like the <hr>
to be full width, replace <div>
with <div class='row'><div class='span12'>
(with according closing tags).
If you expect something different, describe what you expect by adding a comment.
Ok, if anyone ever reads this: the best option is to add four
s at each extra level of indentation, it would seem!
so:
<select>_x000D_
<optgroup label="Level One">_x000D_
<option> A.1 </option>_x000D_
<optgroup label=" Level Two">_x000D_
<option> A.B.1 </option>_x000D_
</optgroup>_x000D_
<option> A.2 </option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.
Complete code:
String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for( int i = 0; i < textArray.length; i++ )
{
TextView textView = new TextView(this);
textView.setText(textArray[i]);
linearLayout.addView(textView);
}
Actually, The save command is only on instance of Document class. That have a lot of methods and attribute. So you can use lean() function to reduce work load. Refer here. https://hashnode.com/post/why-are-mongoose-mongodb-odm-lean-queries-faster-than-normal-queries-cillvawhq0062kj53asxoyn7j
Another problem with save function, that will make conflict data in with multi-save at a same time. Model.Update will make data consistently. So to update multi items in array of document. Use your familiar programming language and try something like this, I use mongoose in that:
User.findOne({'_id': '4d2d8deff4e6c1d71fc29a07'}).lean().exec()
.then(usr =>{
if(!usr) return
usr.events.forEach( e => {
if(e && e.profile==10 ) e.handled = 0
})
User.findOneAndUpdate(
{'_id': '4d2d8deff4e6c1d71fc29a07'},
{$set: {events: usr.events}},
{new: true}
).lean().exec().then(updatedUsr => console.log(updatedUsr))
})
You can do something like
for(var k in result) {
console.log(k, result[k]);
}
which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use
typeof result[k] === "object"
to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.
I've been using matlab for many years in my research. It's great for linear algebra and has a large set of well-written toolboxes. The most recent versions are starting to push it into being closer to a general-purpose language (better optimizers, a much better object model, richer scoping rules, etc.).
This past summer, I had a job where I used Python + numpy instead of Matlab. I enjoyed the change of pace. It's a "real" language (and all that entails), and it has some great numeric features like broadcasting arrays. I also really like the ipython environment.
Here are some things that I prefer about Matlab:
If I didn't have such a large existing codebase, I'd seriously consider switching to Python + numpy.
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
A Super key is a set or one of more columns to uniquely identify rows in a table.
Candidate keys are selected from the set of super keys, the only thing we take care while selecting candidate key is: It should not have any redundant attribute. That’s the reason they are also termed as minimal super key.
In Employee
table there are Three Columns : Emp_Code,Emp_Number,Emp_Name
Super keys:
All of the following sets are able to uniquely identify rows of the employee table.
{Emp_Code}
{Emp_Number}
{Emp_Code, Emp_Number}
{Emp_Code, Emp_Name}
{Emp_Code, Emp_Number, Emp_Name}
{Emp_Number, Emp_Name}
Candidate Keys:
As I stated above, they are the minimal super keys with no redundant attributes.
{Emp_Code}
{Emp_Number}
Primary key:
Primary key is being selected from the sets of candidate keys by database designer. So Either {Emp_Code}
or {Emp_Number}
can be the primary key.
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
one more option I could think of
private static boolean isPositive(Object numberObject) {
Long number = Long.valueOf(numberObject.toString());
return Math.sqrt((number * number)) != number;
}
private static boolean isPositive(Object numberObject) {
Long number = Long.valueOf(numberObject.toString());
long signedLeftShifteredNumber = number << 1; // Signed left shift
long unsignedRightShifterNumber = signedLeftShifteredNumber >>> 1; // Unsigned right shift
return unsignedRightShifterNumber == number;
}
You can include the branch to track when setting up remotes, to keep things working as you might expect:
git remote add --track master origin [email protected]:group/project.git # git
git remote add --track master origin [email protected]:group/project.git # git w/IP
git remote add --track master origin http://github.com/group/project.git # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/ # local
git remote add --track master origin G:/group/project/ # local, Win
This keeps you from having to manually edit your git config or specify branch tracking manually.
Even I run npm install -g npm@4
, it is not ok for me.
Finally, I download and install the old node.js version.
https://nodejs.org/download/release/v7.10.1/
It is npm version 4.
You can choose any version here https://nodejs.org/download/release/
You can create "everywhere" custom search engine right from the Google Custom Search homepage ( http://www.google.com/cse/ ). You should just click 'advanced', during adding new engine. There you can provide Schema.org site type. 'Thing' is most generic type, which covers all the web.
Here is a demo to illustrate the difference:
document.querySelectorAll("button")[0].addEventListener('click', e=>{
e.stopPropagation();
alert(1);
});
document.querySelectorAll("button")[1].addEventListener('click', e=>{
e.stopImmediatePropagation();
alert(1);
});
document.querySelectorAll("button")[0].addEventListener('click', e=>{
alert(2);
});
document.querySelectorAll("button")[1].addEventListener('click', e=>{
alert(2);
});
_x000D_
<div onclick="alert(3)">
<button>1...2</button>
<button>1</button>
</div>
_x000D_
Notice that you can attach multiple event handlers to an event on an element.
The easiest way is
find . | grep test
here find will list all the files in the (.) ie current directory, recursively. And then it is just a simple grep. all the files which name has "test" will appeared.
you can play with grep as per your requirement. Note : As the grep is generic string classification, It can result in giving you not only file names. but if a path has a directory ('/xyz_test_123/other.txt') would also comes to the result set. cheers
What is it?
Javascript is a prototypal language which means it uses prototypes for 'inheritance'. the instanceof
operator tests if a constructor function's prototype
propertype is present in the __proto__
chain of an object. This means that it will do the following (assuming that testObj is a function object):
obj instanceof testObj;
obj.__proto__ === testObj.prototype
>> if this is true
instanceof
will return true
.obj.__proto__.__proto__ === testObj.prototype
>> if this is true
instanceof
will return true
.testObj.prototype
then instanceof
operator will return false
.function Person(name) {_x000D_
this.name = name;_x000D_
}_x000D_
var me = new Person('Willem');_x000D_
_x000D_
console.log(me instanceof Person); // true_x000D_
// because: me.__proto__ === Person.prototype // evaluates true_x000D_
_x000D_
console.log(me instanceof Object); // true_x000D_
// because: me.__proto__.__proto__ === Object.prototype // evaluates true_x000D_
_x000D_
console.log(me instanceof Array); // false_x000D_
// because: Array is nowhere on the prototype chain
_x000D_
What problems does it solve?
It solved the problem of conveniently checking if an object derives from a certain prototype. For example, when a function recieves an object which can have various prototypes. Then, before using methods from the prototype chain, we can use the instanceof
operator to check whether the these methods are on the object.
function Person1 (name) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
function Person2 (name) {_x000D_
this.name = name;_x000D_
}_x000D_
_x000D_
Person1.prototype.talkP1 = function () {_x000D_
console.log('Person 1 talking');_x000D_
}_x000D_
_x000D_
Person2.prototype.talkP2 = function () {_x000D_
console.log('Person 2 talking');_x000D_
}_x000D_
_x000D_
_x000D_
function talk (person) {_x000D_
if (person instanceof Person1) {_x000D_
person.talkP1();_x000D_
}_x000D_
_x000D_
if (person instanceof Person2) {_x000D_
person.talkP2();_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
const pers1 = new Person1 ('p1');_x000D_
const pers2 = new Person2 ('p2');_x000D_
_x000D_
talk(pers1);_x000D_
talk(pers2);
_x000D_
Here in the talk()
function first is checked if the prototype is located on the object. After this the appropriate method is picked to execute. Not doing this check could result in executing a method which doesn't exist and thus a reference error.
When is it appropriate and when not?
We kind of already went over this. Use it when you are in need of checking the prototype of an object before doing something with it.
You have many alternatives, for example:
Alternative 1:
git rebase -i <YourCommitId>~1
Change YourCommitId for the number of the commit which you want to revert back to.
Alternative 2:
git reset --hard YourCommitId
git push <origin> <branch> --force
Change YourCommitId for the number of the commit which you want to revert back to.
I don't recommend this option because you can lost your work in progress.
Alternative 3:
git reset --soft HEAD~1
You can keep your work and only undo the commit.
You could use the tr
instead:
$p =~ tr/fo//d;
will delete every f and every o from $p
. In your case it should be:
$p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d
tr/SEARCHLIST/REPLACEMENTLIST/cdsr
Transliterates all occurrences of the characters found (or not found if the
/c
modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.[…]
If the
/d
modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
After many tries I found that you should use createNativeQuery
And you can send parameters using #
replacement
In my example
String UPDATE_lOGIN_TABLE_QUERY = "UPDATE OMFX.USER_LOGIN SET LOGOUT_TIME = SYSDATE WHERE LOGIN_ID = #loginId AND USER_ID = #userId";
Query query = em.createNativeQuery(logQuery);
query.setParameter("userId", logDataDto.getUserId());
query.setParameter("loginId", logDataDto.getLoginId());
query.executeUpdate();
your folder name is scripts..
and you are Referencing it like ../script/login.js
Also make sure that script folder is in your project directory
Thanks
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
With this command I had poor image quality
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4
With this, almost without delay, I got good image quality.
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi
Well, to answer the immediate question:
>>> s = "http://www.domain.com/?s=some&two=20"
The rfind
method returns the index of right-most substring:
>>> s.rfind("&")
29
You can take all elements up to a given index with the slicing operator:
>>> "foobar"[:4]
'foob'
Putting the two together:
>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'
If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two
from the above query string:
First, parse the URL as a whole:
>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')
Take out just the query string:
>>> query_s = parse_result.query
>>> query_s
's=some&two=20'
Turn it into a dict
:
>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']
Remove the 'two'
key from the dict:
>>> del query_d['two']
>>> query_d
{'s': ['some']}
Put it back into a query string:
>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'
And now stitch the URL back together:
>>> result = urlparse.urlunsplit((
parse_result.scheme, parse_result.netloc,
parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'
The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two
argument, even if it was put earlier in the query string ("two=20&s=some"
), this would still do the right thing. It might be overkill depending on what you want to do.
I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.
Do not forget to open and close connection. follow this link for more under standing.
You need httpclient.jar and httpcore.jar. You can download them from here.
http://archive.apache.org/dist/httpcomponents/httpclient/binary/
You are copying all files to a single file called TEST_BACKUP_FOLDER
try this:
md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER
You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.
private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
data.toScreen(); // prints to screen some values
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2
>>>
There is a bug in using of the subprocess.PIPE. For the huge output use this:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print tempf.read()
Any user whose login shell setting in /etc/passwd
is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells
is probably as good as you can get.
Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false
as their shell -- this will just log them out immediately.
find <path> -xdev -type f -name *.txt -exec ls -l {} \;
This will list the files and give details about attributes.
Use Directory.GetDirectories
to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.
var directories = Directory.GetDirectories("your_directory_path");
By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.
Avoiding an UnauthorizedAccessException
It's easily possible that you'll get an UnauthorizedAccessException
if you hit a directory to which you don't have access.
You may have to create your own method that handles the exception, like this:
public class CustomSearcher
{
public static List<string> GetDirectories(string path, string searchPattern = "*",
SearchOption searchOption = SearchOption.AllDirectories)
{
if (searchOption == SearchOption.TopDirectoryOnly)
return Directory.GetDirectories(path, searchPattern).ToList();
var directories = new List<string>(GetDirectories(path, searchPattern));
for (var i = 0; i < directories.Count; i++)
directories.AddRange(GetDirectories(directories[i], searchPattern));
return directories;
}
private static List<string> GetDirectories(string path, string searchPattern)
{
try
{
return Directory.GetDirectories(path, searchPattern).ToList();
}
catch (UnauthorizedAccessException)
{
return new List<string>();
}
}
}
And then call it like this:
var directories = CustomSearcher.GetDirectories("your_directory_path");
This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException
, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.
Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
Add a linefeed ("\n") to the output:
<textarea>Hello
Bybye</textarea>
Will have a newline in it.
This Solved my problem: Open your VS Project
Double click on Package.appxmanifest
Go to Packaging tab
click choose certificate
click configure certificate
select from file and use example.pfx that unity or anything else created
If you can overlook the height of TextBlock, it's better for you to use this:
<TextBlock Height="{Binding}" Text="Your text"
TextWrapping="Wrap" VerticalAlignment="Center" Width="28"/>
I just use <iframe src="about:blank" ...></iframe>
and it works fine.
Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:
Especially note how adding the binding function as a class method works, but the referencing scope is incorrect.
#!/usr/bin/python -u
import types
import inspect
## dynamically adding methods to a unique instance of a class
# get a list of a class's method type attributes
def listattr(c):
for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:
print m[0], m[1]
# externally bind a function as a method of an instance of a class
def ADDMETHOD(c, method, name):
c.__dict__[name] = types.MethodType(method, c)
class C():
r = 10 # class attribute variable to test bound scope
def __init__(self):
pass
#internally bind a function as a method of self's class -- note that this one has issues!
def addmethod(self, method, name):
self.__dict__[name] = types.MethodType( method, self.__class__ )
# predfined function to compare with
def f0(self, x):
print 'f0\tx = %d\tr = %d' % ( x, self.r)
a = C() # created before modified instnace
b = C() # modified instnace
def f1(self, x): # bind internally
print 'f1\tx = %d\tr = %d' % ( x, self.r )
def f2( self, x): # add to class instance's .__dict__ as method type
print 'f2\tx = %d\tr = %d' % ( x, self.r )
def f3( self, x): # assign to class as method type
print 'f3\tx = %d\tr = %d' % ( x, self.r )
def f4( self, x): # add to class instance's .__dict__ using a general function
print 'f4\tx = %d\tr = %d' % ( x, self.r )
b.addmethod(f1, 'f1')
b.__dict__['f2'] = types.MethodType( f2, b)
b.f3 = types.MethodType( f3, b)
ADDMETHOD(b, f4, 'f4')
b.f0(0) # OUT: f0 x = 0 r = 10
b.f1(1) # OUT: f1 x = 1 r = 10
b.f2(2) # OUT: f2 x = 2 r = 10
b.f3(3) # OUT: f3 x = 3 r = 10
b.f4(4) # OUT: f4 x = 4 r = 10
k = 2
print 'changing b.r from {0} to {1}'.format(b.r, k)
b.r = k
print 'new b.r = {0}'.format(b.r)
b.f0(0) # OUT: f0 x = 0 r = 2
b.f1(1) # OUT: f1 x = 1 r = 10 !!!!!!!!!
b.f2(2) # OUT: f2 x = 2 r = 2
b.f3(3) # OUT: f3 x = 3 r = 2
b.f4(4) # OUT: f4 x = 4 r = 2
c = C() # created after modifying instance
# let's have a look at each instance's method type attributes
print '\nattributes of a:'
listattr(a)
# OUT:
# attributes of a:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FD88>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FD88>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FD88>>
print '\nattributes of b:'
listattr(b)
# OUT:
# attributes of b:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FE08>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FE08>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FE08>>
# f1 <bound method ?.f1 of <class __main__.C at 0x000000000237AB28>>
# f2 <bound method ?.f2 of <__main__.C instance at 0x000000000230FE08>>
# f3 <bound method ?.f3 of <__main__.C instance at 0x000000000230FE08>>
# f4 <bound method ?.f4 of <__main__.C instance at 0x000000000230FE08>>
print '\nattributes of c:'
listattr(c)
# OUT:
# attributes of c:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002313108>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002313108>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002313108>>
Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.
def y(self, x):
pass
d = C()
for i in range(1,5):
ADDMETHOD(d, y, 'f%d' % i)
print '\nattributes of d:'
listattr(d)
# OUT:
# attributes of d:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002303508>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002303508>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002303508>>
# f1 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f2 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f3 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f4 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
Use %0D%0A
for a line break in your body
Example (Demo):
<a href="mailto:[email protected]?subject=Suggestions&body=name:%0D%0Aemail:">test</a>?
^^^^^^
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
You're supposed to use setImageResource
instead of setBackgroundResource
.
What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.
From Microsoft documentation:
In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.
I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified
can be misleading in some special cases.
In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.
So in fact the message The system cannot find the file specified
was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.
All you need to do is simply
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
Instead of JSONObject , you can use ObjectMapper to convert java object to json string
ObjectMapper mapper = new ObjectMapper();
String requestBean = mapper.writeValueAsString(yourObject);
Can add muted
tag.
<video autoplay muted>
<source src="video.webm" type="video/webm" />
<source src="video.mp4" type="video/mp4" />
</video>
reference https://developers.google.com/web/updates/2016/07/autoplay
The following website has both right click and view source disabled.
They fooled you. Just scroll down in view-source.
Furthermore, employing such tactics marks you as unprofessional. Don’t do it.
Whenever I build applications that require such functionality, I always use the Windows Task Scheduler through a simple .NET library that I found.
Please see my answer to a similar question for some sample code and more explanation.
document.getElementsByClassName
returns a NodeList
, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()
or if you want plain JS try :
function toggle_by_class(cls, on) {
var lst = document.getElementsByClassName(cls);
for(var i = 0; i < lst.length; ++i) {
lst[i].style.display = on ? '' : 'none';
}
}
In Sass we can write:
background-color: rgba(#ff0000, 0.5);
as it was suggested in Hex representation of a color with alpha channel?
You can still use filter, moving to an outside function the element modification (iterating just once)
def do_the_magic(x):
do_action(x)
return check(x)
# you can get a different filtered list
filter(do_the_magic,yourList)
# or have it modified in place (as suggested by Steven Rumbalski, see comment)
yourList[:] = itertools.ifilter(do_the_magic, yourList)
As one of the answers above says: " then drag the formula fill handle." This KEY feature is not mentioned in MS's explanation, nor in others here. I spent over an hour trying to follow the various instructions, to no avail. This is because you have to click and hold near the bottom of the cell just right (and at least on my computer that is not at all easy) so that a sort of "handle" appears. Once you're luck enough to get that, then carefully slide ["drag"] your cursor down to the lowermost of the cells you want to be multiplied by the constant. The products should show up in each cell as you move down. Just dragging down will give you only the answer in the first cell and a lot of white space.
If you read the Keras documentation entry for Dense
, you will see that this call:
Dense(16, input_shape=(5,3))
would result in a Dense
network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x)
transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])]
with shape (5, 16)
. In order to have the behavior you specify you may first Flatten
your input to a 15-d vector and then apply Dense
:
model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')
EDIT: As some people struggled to understand - here you have an explaining image:
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
I recently encountered a memory leak situation caused in a way by log4j.
Log4j has this mechanism called Nested Diagnostic Context(NDC) which is an instrument to distinguish interleaved log output from different sources. The granularity at which NDC works is threads, so it distinguishes log outputs from different threads separately.
In order to store thread specific tags, log4j's NDC class uses a Hashtable which is keyed by the Thread object itself (as opposed to say the thread id), and thus till the NDC tag stays in memory all the objects that hang off of the thread object also stay in memory. In our web application we use NDC to tag logoutputs with a request id to distinguish logs from a single request separately. The container that associates the NDC tag with a thread, also removes it while returning the response from a request. The problem occurred when during the course of processing a request, a child thread was spawned, something like the following code:
pubclic class RequestProcessor {
private static final Logger logger = Logger.getLogger(RequestProcessor.class);
public void doSomething() {
....
final List<String> hugeList = new ArrayList<String>(10000);
new Thread() {
public void run() {
logger.info("Child thread spawned")
for(String s:hugeList) {
....
}
}
}.start();
}
}
So an NDC context was associated with inline thread that was spawned. The thread object that was the key for this NDC context, is the inline thread which has the hugeList object hanging off of it. Hence even after the thread finished doing what it was doing, the reference to the hugeList was kept alive by the NDC context Hastable, thus causing a memory leak.
Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.
No hardcoded value other than the scroll time, best suited for small scroll spaces
.marquee {_x000D_
width: 100%;_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
display: inline-flex; _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
display: flex; _x000D_
flex-basis: 100%;_x000D_
animation: marquee-reset;_x000D_
animation-play-state: paused; _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
animation: marquee 2s linear infinite;_x000D_
animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
50% {_x000D_
transform: translate(-100%, 0);_x000D_
}_x000D_
50.001% {_x000D_
transform: translate(100%, 0);_x000D_
}_x000D_
100% {_x000D_
transform: translate(0%, 0);_x000D_
}_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
0% {_x000D_
transform: translate(0%, 0);_x000D_
} _x000D_
}
_x000D_
<span class="marquee">_x000D_
<span>This is the marquee text</span>_x000D_
</span>
_x000D_
You can use groups (indicated with '('
and ')'
) to capture parts of the string. The match object's group()
method then gives you the group's contents:
>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0) # the entire match
'name my_user_name is valid'
>>> match.group(1) # the first parenthesized subgroup
'my_user_name'
In Python 3.6+ you can also index into a match object instead of using group()
:
>>> match[0] # the entire match
'name my_user_name is valid'
>>> match[1] # the first parenthesized subgroup
'my_user_name'
iOS 4.3.2's User Agent, which came out this week, is:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5
Refer to this answer: How can we play YouTube embeded code in an Android application using webview?
It uses WebViews
and loads an iframe
in it... and yes it works.
Use ProcessInfo.RedirectStandardOutput to redirect the output when creating your console process.
Then you can use Process.StandardOutput to read the program output.
The second link has a sample code how to do it.
functools.cache
is released in Python 3.9 (docs):
from functools import cache
@cache
def factorial(n):
return n * factorial(n-1) if n else 1
In previous versions, one of the early answers is still a valid solution using lru_cache
as an ordinary cache without limit and lru feature. (docs)
If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound.
Here is a prettier version of it:
cache = lru_cache(maxsize=None)
@cache
def func(param1):
pass
At a theoretical level, they are no different semantically. You can implement a mutex using semaphores or vice versa (see here for an example). In practice, the implementations are different and they offer slightly different services.
The practical difference (in terms of the system services surrounding them) is that the implementation of a mutex is aimed at being a more lightweight synchronisation mechanism. In oracle-speak, mutexes are known as latches and semaphores are known as waits.
At the lowest level, they use some sort of atomic test and set mechanism. This reads the current value of a memory location, computes some sort of conditional and writes out a value at that location in a single instruction that cannot be interrupted. This means that you can acquire a mutex and test to see if anyone else had it before you.
A typical mutex implementation has a process or thread executing the test-and-set instruction and evaluating whether anything else had set the mutex. A key point here is that there is no interaction with the scheduler, so we have no idea (and don't care) who has set the lock. Then we either give up our time slice and attempt it again when the task is re-scheduled or execute a spin-lock. A spin lock is an algorithm like:
Count down from 5000:
i. Execute the test-and-set instruction
ii. If the mutex is clear, we have acquired it in the previous instruction
so we can exit the loop
iii. When we get to zero, give up our time slice.
When we have finished executing our protected code (known as a critical section) we just set the mutex value to zero or whatever means 'clear.' If multiple tasks are attempting to acquire the mutex then the next task that happens to be scheduled after the mutex is released will get access to the resource. Typically you would use mutexes to control a synchronised resource where exclusive access is only needed for very short periods of time, normally to make an update to a shared data structure.
A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would. Semaphores are incremented and decremented and used to block tasks until something else is ready. See Producer/Consumer Problem for a simple example of this. Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1. Posting to a semaphore has the effect of waking up a waiting process.
A basic semaphore algorithm looks like:
(somewhere in the program startup)
Initialise the semaphore to its start-up value.
Acquiring a semaphore
i. (synchronised) Attempt to decrement the semaphore value
ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.
Posting a semaphore
i. (synchronised) Increment the semaphore value
ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable.
iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.
In the case of a binary semaphore the main practical difference between the two is the nature of the system services surrounding the actual data structure.
EDIT: As evan has rightly pointed out, spinlocks will slow down a single processor machine. You would only use a spinlock on a multi-processor box because on a single processor the process holding the mutex will never reset it while another task is running. Spinlocks are only useful on multi-processor architectures.
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
//smaller the number more accurate result will
if (gps_loc.getAccuracy() > net_loc.getAccuracy())
finalLoc = net_loc;
else
finalLoc = gps_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = gps_loc;
} else if (net_loc != null) {
finalLoc = net_loc;
}
}
As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.
You can use this function:
function postForm(path, params, method) {
method = method || 'post';
var form = document.createElement('form');
form.setAttribute('method', method);
form.setAttribute('action', path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});
Maybe you are trying to set it in Apache's php.ini
, but your CLI (Command Line Interface) php.ini
is not good.
Find your php.ini
file with the following command:
php -i | grep php.ini
And then search for date.timezone
and set it to "Europe/Amsterdam"
. all valid timezone will be found here http://php.net/manual/en/timezones.php
Another way (if the other does not work), search for the file AppKernel.php
, which should be under the folder app
of your Symfony project directory. Overwrite the __construct
function below in the class AppKernel
:
<?php
class AppKernel extends Kernel
{
// Other methods and variables
// Append this init function below
public function __construct($environment, $debug)
{
date_default_timezone_set( 'Europe/Paris' );
parent::__construct($environment, $debug);
}
}
You could try:
$j('div.contextualError.ckgcellphone').css('display')
I was testing a CORS web service on my dev machine and was getting the "Access is denied" error message in only IE. Firefox and Chrome worked fine. It turns out this was caused by my use of localhost in the ajax call! So my browser URL was something like:
http://my_computer.my_domain.local/CORS_Service/test.html
and my ajax call inside of test.html was something like:
//fails in IE
$.ajax({
url: "http://localhost/CORS_Service/api/Controller",
...
});
Everything worked once I changed the ajax call to use my computer IP instead of localhost.
//Works in IE
$.ajax({
url: "http://192.168.0.1/CORS_Service/api/Controller",
...
});
The IE dev tools window "Network" tab also shows CORS Preflight OPTIONS request followed by the XMLHttpRequest GET, which is exactly what I expected to see.
This was the easiest for me on a Windows Server: In VisualSVN right-click your repository, then select Properties... and then the Hooks tab.
Select Pre-revision property change hook, click Edit.
I needed to be able to change the Author - it often happens on remote computers used by multiple people, that by mistake we check-in using someone else's stored credentials.
Here is the modified community wiki script to paste:
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5
:: Only allow the author to be changed, but not message ("svn:log"), etc.
if /I not "%propertyName%" == "svn:author" goto ERROR_PROPNAME
:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION
:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:author messages are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:author messages are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:author revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
To help performance you should try to only alter the DOM once, even more so if you are adding many options.
var html = '';
for (var i = 0, len = data.length; i < len; ++i) {
html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}
$('#select').append(html);
use sth like
<input type="text" name="yourName" placeholder="A new value" />
It's hard to say without seeing the rest of your CSS, but try adding !important
in front of the border color, to make it like so:
#refundReasonMenu #nav li:last-child
{
border-bottom: 1px solid #b5b5b5 !important;
}
You can use Flexible, in this case the person.name could be a long name (Labels and BlankSpace are custom classes that return widgets) :
new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Flexible(
child: Labels.getTitle_2(person.name,
color: StyleColors.COLOR_BLACK)),
BlankSpace.column(3),
Labels.getTitle_1(person.likes())
]),
BlankSpace.row(3),
Labels.getTitle_2(person.shortDescription),
],
)
Java doesn't have a Random generator between two values in the same way that Python does. It actually only takes one value in to generate the Random. What you need to do, then, is add ONE CERTAIN NUMBER to the number generated, which will cause the number to be within a range. For instance:
package RandGen;
import java.util.Random;
public class RandGen {
public static Random numGen =new Random();
public static int RandNum(){
int rand = Math.abs((100)+numGen.nextInt(100));
return rand;
}
public static void main(String[]Args){
System.out.println(RandNum());
}
}
This program's function lies entirely in line 6 (The one beginning with "int rand...". Note that Math.abs() simply converts the number to absolute value, and it's declared as an int, that's not really important. The first (100) is the number I am ADDING to the random one. This means that the new output number will be the random number + 100. numGen.nextInt() is the value of the random number itself, and because I put (100) in its parentheses, it is any number between 1 and 100. So when I add 100, it becomes a number between 101 and 200. You aren't actually GENERATING a number between 100 and 200, you are adding to the one between 1 and 100.
Bootstrap's functionality appears to have changed slightly since v4 has been released. The .dropdown-menu
item appears to also now get the .show
class in addition to the .dropdown
. I adapted Andrei's answer to also toggle the class on the .dropdown-menu
. Note that the CSS is no longer necessary and the HTML is the same except I updated the links to the current versions and the nav class changed to navbar-expand-md
.
$('body').on('mouseenter mouseleave', '.dropdown', function (e) {_x000D_
var dropdown = $(e.target).closest('.dropdown');_x000D_
var menu = $('.dropdown-menu', dropdown);_x000D_
dropdown.addClass('show');_x000D_
menu.addClass('show');_x000D_
setTimeout(function () {_x000D_
dropdown[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');_x000D_
menu[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');_x000D_
}, 300);_x000D_
});
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-faded">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Pricing</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<a class="dropdown-item" href="#">Action</a>_x000D_
<a class="dropdown-item" href="#">Another action</a>_x000D_
<a class="dropdown-item" href="#">Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
In order to run the python script, we need to tell the shell three things:
The shebang #!
accomplishes (1.). The shebang begins with a #
because the #
character is a comment marker in many scripting languages. The contents of the shebang line are therefore automatically ignored by the interpreter.
The env
command accomplishes (2.) and (3.). To quote "grawity,"
A common use of the
env
command is to launch interpreters, by making use of the fact that env will search $PATH for the command it is told to launch. Since the shebang line requires an absolute path to be specified, and since the location of various interpreters (perl, bash, python) may vary a lot, it is common to use:
#!/usr/bin/env perl
instead of trying to guess whether it is /bin/perl, /usr/bin/perl, /usr/local/bin/perl, /usr/local/pkg/perl, /fileserver/usr/bin/perl, or /home/MrDaniel/usr/bin/perl on the user's system...On the other hand, env is almost always in /usr/bin/env. (Except in cases when it isn't; some systems might use /bin/env, but that's a fairly rare occassion and only happens on non-Linux systems.)
This worked for me:
curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
I could see the value in backend using
print request.cookies
exec has memory limitation of buffer size of 512k. In this case it is better to use spawn. With spawn one has access to stdout of executed command at run time
var spawn = require('child_process').spawn;
var prc = spawn('java', ['-jar', '-Xmx512M', '-Dfile.encoding=utf8', 'script/importlistings.jar']);
//noinspection JSUnresolvedFunction
prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
var str = data.toString()
var lines = str.split(/(\r?\n)/g);
console.log(lines.join(""));
});
prc.on('close', function (code) {
console.log('process exit code ' + code);
});
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
This will match yyyy-mm-dd
and also yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
Check shared library dependencies of a program executable
To find out what libraries a particular executable depends on, you can use ldd command. This command invokes dynamic linker to find out library dependencies of an executable.
> $ ldd /path/to/program
Note that it is NOT recommended to run ldd with any untrusted third-party executable because some versions of ldd may directly invoke the executable to identify its library dependencies, which can be security risk.
Instead, a safer way to show library dependencies of an unknown application binary is to use the following command.
$ objdump -p /path/to/program | grep NEEDED
After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.
So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.
Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!
How they are concatenated? It is quite easy. Put them one after another in the same file.
You can get more help on this here.
I believe this might help you.
This is a common problem with GoDaddy virtual server hosting when you bring up a new website.
Assuming you have SSH access to the server (you have to enable it on cPanel), login to your account. Upon successful login, you will be placed in the home directory for your account. The DocumentRoot for your website is located in a subdirectory named public_html. GoDaddy defaults the permissions for this directory to 750, but those permissions are inadequate to allow Apache to read the files for website. You need to change the permissions for this directory to 755 (chmod 755 public_html).
Copy the files for your website into the public_html directory (both scp and rsync work for copying files to a GoDaddy Linux server).
Next, make sure all of the files under public_html are world readable. To do this, use this command:
cd public_html
chmod -R o+r *
If you have other subdirectories (like css, js, and img), make sure they are world accessible by enabling both read and execute for world access:
chmod o+rx css
chmod o+rx img
chmod o+rx js
Last, you will need to have a .htaccess file in the public_html file. GoDaddy enforces a rule that prohibits the site for loading if you do not have a .htaccess file in your public_html directory. You can use vi to create this file ("vi .htaccess"). Enter the following lines in the file:
Order allow,deny
Allow from all
Require all granted
This config will work for both Apache 2.2 and Apache 2.4. Save the file (ZZ), and then make sure the file has permissions of 644:
chmod 644 .htaccess
Works like a charm.
You should use some HTML parsing library like lxml
:
from lxml import etree
s = """<table>
<tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>d</td><td>e</td><td>f</td></tr>
<tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
print dict(zip(headers, values))
prints
{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}
Here my approach,it may be useful to others.
public static void compareArrays(int[] array1, int[] array2) {
if (array1.length != array2.length)
{
System.out.println("Not Equal");
}
else
{
int temp = 0;
for (int i = 0; i < array2.length; i++) { //Take any one of the array size
temp^ = array1[i] ^ array2[i]; //with help of xor operator to find two array are equal or not
}
if( temp == 0 )
{
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
}
}
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
Just do tr
delete:
tr -d "\r" <infile.txt >outfile.txt
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
There are little difference in command of adding AND changing DNS-IPs:
To Add:
Syntax:
netsh interface ipv4 add dnsserver "Network Interface Name" dns.server.ip index=1(for primary)2(for secondary)
Eg:
netsh interface ipv4 add dnsserver "Ethernet" 8.8.8.8 index=1
netsh interface show interface
To Set/Change: (as OP asked this)
Syntax:
netsh interface ipv4 set dnsservers "Network Interface Name" static dns.server.ip primary
Eg:
netsh interface ipv4 set dnsservers "Wi-Fi" static 8.8.4.4 primary
netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
Last parameter can be none
:disable DNS, both
:set for primary and secondary DNS both, primary: for primary DNS only. You can notice here we are not using index-parameter as we did in adding DNS.
In the place of static
you can type dhcp
to make DNS setting automatic, but further parameter will not be required.
Note: Tested in windows 8,8.1 & 10.
There is also a property resourceRef
of JndiObjectFactoryBean
that is, when set to true
, used to automatically prepend the string java:comp/env/
if it is not already present.
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/loc"/>
<property name="resourceRef" value="true"/>
</bean>
I had same problem when I added Owin to an existing web project. I eventually found the problem was due to the following in the web.config file.
<assemblies>
<remove assembly="*" />
<add assembly="System.Web.Mvc" />
<add assembly="System.Web.WebPages" />
...
</assemblies>
The remove assembly="*" was causing the problem. When I remove this line the Owin startup code ran. I eventually change it to the following and it worked perfectly
<assemblies>
<remove assembly="*" />
<add assembly="Microsoft.Owin.Host.SystemWeb" />
<add assembly="System.Web.Mvc" />
<add assembly="System.Web.WebPages" />
<add assembly="System.Web.Helpers" />
...
</assemblies>
I think he's using Python 3.0 and you're using Python 2.6.
Extending the answer by David Vavra,create a file ~/.gradle/gradle.properties and add
RELEASE_STORE_FILE=/path/to/.keystore
RELEASE_KEY_ALIAS=XXXXX
RELEASE_STORE_PASSWORD=XXXXXXXXX
RELEASE_KEY_PASSWORD=XXXXXXXXX
Then in build.gradle
signingConfigs {
release {
}
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
}
}
// make this optional
if ( project.hasProperty("RELEASE_KEY_ALIAS") ) {
signingConfigs {
release {
storeFile file(RELEASE_STORE_FILE)
storePassword RELEASE_STORE_PASSWORD
keyAlias RELEASE_KEY_ALIAS
keyPassword RELEASE_KEY_PASSWORD
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
Give a smaller length for your email string like :
$table->string('email',128)->unique(); //In create user table
And
$table->string('email',128)->index(); // create password resets table
This will definitely work.
TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".
So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.
In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".
It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.
Let's rephrase your question to this:
The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.
To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).
The following is an introduction/overview, but you might find this excellent article also informative.
WHAT GIT IS, AND WHAT IT'S FOR
A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.
A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.
The basic idea is to create a book so we can easily look backwards in time,
When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.
SNAPSHOTS AND TRACKING
tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)
In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.
Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.
Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.
One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.
For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.
This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.
COMMITS
A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:
A commit is the most important part of a well organized photo album.
THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES
Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.
The git family tree structure is modeled on our own, human family trees.
In what follows to help understand links in a simple way, I'll refer to:
You should understand this instinctively, as it is based on the tree of life:
Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.
With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.
With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.
Line diagram of a simple, single parent chain linking backwards in time:
(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)
BRANCHES
branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)
A git branch also refers to two things:
More than one child pointing --at a--> parent, is what git calls "branching".
NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.
The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".
In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.
Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)
ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.
The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)
(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)
So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".
So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.
The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".
The master branch always exists.
Line diagram of: Commit1 with 2 children (or what we call a git "branch"):
parent children
+-- Commit <-- Commit <-- Commit (Branch named 'Tom')
/
v
(older) ... <-- Commit1 <-- Commit (Branch named 'master')
Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.
So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.
MERGING
Children have one or more parents.
With just one parent this is just a simple parent <-- child commit.
With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.
Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):
parents child
... <-- Commit
v
\
(older) ... <-- Commit1 <-- Commit2
REMOTE
This word is also used to mean 2 different things:
remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)
(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.
A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)
You can setup multiple remotes if you want to pull or push to multiple remote repositories.
Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).
origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)
Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.
upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia
upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)
This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.
REMOTE TRACKING BRANCH
A remote-tracking-branch is first, just a branch name, like any other branch name.
It points at a local growing tip, i.e. a recent commit in your local git repository.
But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.
remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)
Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.
Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.
TRACKING IN ACTION
First we begin tracking a file with git.
Here are the basic commands involved with file tracking:
$ mkdir mydir && cd mydir && git init # create a new git repository
$ git branch # this initially reports no branches
# (IMHO this is a bug!)
$ git status -bs # -b = branch; -s = short # master branch is empty
## No commits yet on master
# ...
$ touch foo # create a new file
$ vim foo # modify it (OPTIONAL)
$ git add foo; commit -m 'your description' # start tracking foo
$ git rm --index foo; commit -m 'your description' # stop tracking foo
$ git rm foo; commit -m 'your description' # stop tracking foo & also delete foo
REMOTE TRACKING IN ACTION
$ git pull # Essentially does: get fetch; git merge # to update our clone
There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.
You can write following codes to achieve this task:
SELECT ... FROM ... WHERE ...
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'
It export the result to CSV and then export it to excel sheet.
You could use a library such as node-uuid for this to make sure you get unique ids.
Install using:
npm install node-uuid --save
Then in your react component add the following:
import {default as UUID} from "node-uuid";
import {default as React} from "react";
export default class MyComponent extends React.Component {
componentWillMount() {
this.id = UUID.v4();
},
render() {
return (
<div>
<label htmlFor={this.id}>My label</label>
<input id={this.id} type="text"/>
</div>
);
}
}
You can not really add the x-iframe in your HTML body as it has to be provided by the site owner and it lies within the server rules.
What you can probably do is create a PHP file which loads the content of target URL and iframe that php URL, this should work smoothly.
A bonus would be if I can detect the specific version(s) of Excel that is(/are) installed.
I know the question has been asked and answered a long time ago, but this same question has kept me busy until I made this observation:
To get the build number (e.g. 15.0.4569.1506
), probe HKLM\SOFTWARE\Microsoft\Office\[VER]\Common\ProductVersion::LastProduct
, where [VER]
is the major version number (12.0 for Office 2007, 14.0 for Office 2010, 15.0 for Office 2013).
On a 64-bit Windows, you need to insert Wow6432Node
between the SOFTWARE
and Microsoft
crumbs, irrespective of the bitness of the Office installation.
On my machines, this gives the version information of the originally installed version. For Office 2010 for instance, the numbers match the ones listed here, and they differ from the version reported in File > Help
, which reflects patches applied by hotfixes.
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark"
and the property in code is FirstName
then use the Select method as follows
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project. http://tclap.sourceforge.net/
A similar library is available for C as well. http://argtable.sourceforge.net/
This is how I do it, with a README.md file in each directory:
/data/*
!/data/README.md
!/data/input/
/data/input/*
!/data/input/README.md
!/data/output/
/data/output/*
!/data/output/README.md
What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...
use two line of code to convert array to list if you use it in integer value you must use autoboxing type for primitive data type
Integer [] arr={1,2};
Arrays.asList(arr);
Another option is:
Create a shortcut to the Eclipse.exe. Open the shortcut and change the target to:
"C:\Program Files\eclipse\eclipse.exe" -vm "c:\Program Files\Java\jdk1.7.0_04\bin\javaw.exe"
For your installation, make sure the locations point to the correct Eclipse installation directory and the correct javaw.exe
installation directory.
(The 64/32 bit versions of Eclipse and Java need to be the same, of course.)
A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.
I know you wanted "free", but I'd seriously consider getting the data from csidata.com for about $300/year, if I were you.
It's what yahoo uses to supply their data.
It comes with a decent API, and the data is (as far as I can tell) very clean.
You get 10 years of history when you subscribe, and then nightly updates afterward.
They also take care of all sorts of nasty things like splits and dividends for you. If you haven't yet discovered the joy that is data-cleaning, you won't realize how much you need this, until the first time your ATS (Automated Trading System) thinks some stock is really really cheap, only because it split 2:1 and you didn't notice.
If you don't want to have to worry about Null value issues like checking for null every time you use it or wrapping it up in some logic, and you also don't want to have to worry about offset time issues, then this is how I solved the problem:
startDate = startDate <= DateTime.MinValue.AddSeconds(1) ? keepIt : resetIt
I just check that the defaulted value is less than a day after the beginning of time. Works like a charm.
Edit 2021: If you need to check milliseconds of the beginning of time then just add ticks instead, but also maybe carbon dating is what you are really looking for. Still not sure carbon dating would even be as accurate as you need if you need accuracy to the tick.