You need to push the container down the navbar.
Please find my working fiddle here http://jsfiddle.net/meetravi/aXCMW/1/
<header>
<h2 class="title">Test</h2>
</header>
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li class="active"><a href="#">Test1</a></li>
<li><a href="#">Test2</a></li>
<li><a href="#">Test3</a></li>
<li><a href="#">Test4</a></li>
<li><a href="#">Test5</a></li>
</ul>
</div>
</div>
<div class="container">
</div>
I'm new to stack overflow and new to front end development. This is what worked for me. So I did not want list items to be displayed.
.hidden {_x000D_
display:none;_x000D_
} _x000D_
_x000D_
#loginButton{_x000D_
_x000D_
margin-right:2px;_x000D_
_x000D_
}
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" 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_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active hidden">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item hidden">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item hidden">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="loginButton"><a href="#">Log In</a></button>_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"><a href="#">Register</a></button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>
_x000D_
i use this code for navbar on bootstrap 3.2.0, the image should be at most 50px high, or else it will bleed the standard bs navbar.
Notice that i purposely do not use the class='navbar-brand' as that introduces padding on the image
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="" href="/"><img src='img/anyWidthx50.png'/></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Active Link</a></li>
<li><a href="#">More Links</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</div>
I would suggest you just evenly space them as shown in this answer here
.navbar ul {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: nowrap; /* assumes you only want one row */
}
Updated for Bootstrap 4.1+
Bootstrap 4 the navbar now uses flexbox so the Website Name
can be centered using mx-auto
. The left and right side menus don't require floats.
<nav class="navbar navbar-expand-md navbar-fixed-top navbar-dark bg-dark main-nav">
<div class="container">
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
</ul>
<ul class="nav navbar-nav mx-auto">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Rates</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Navbar center with mx-auto
Demo
If the Navbar only has a single navbar-nav
, then justify-content-center
can also be used to center.
In the solution above, the Website Name
is centered relative to the left and right navbar-nav
so if the width of these adjacent navs are different the Website Name
is no longer centered.
To resolve this, one of the flexbox workarounds for absolute centering can be used...
Option 1 - Use position:absolute;
Since it's ok to use absolute positioning in flexbox, one option is to use this on the item to be centered.
.abs-center-x {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Navbar center with absolute position Demo
Option 2 - Use flexbox nesting
Finally, another option is to make the centered item also display:flexbox
(using d-flex
) and center justified. In this case each navbar component must have flex-grow:1
As of Bootstrap 4 Beta, the Navbar is now display:flex
. Bootstrap 4.1.0 includes a new flex-fill
class to make each nav section fill the width:
<nav class="navbar navbar-expand-sm navbar-dark bg-dark main-nav">
<div class="container justify-content-center">
<ul class="nav navbar-nav flex-fill w-100 flex-nowrap">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">More</a>
</li>
</ul>
<ul class="nav navbar-nav flex-fill justify-content-center">
<li class="nav-item"><a class="nav-link" href="#">Center</a></li>
</ul>
<ul class="nav navbar-nav flex-fill w-100 justify-content-end">
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
Navbar center with flexbox nesting Demo
Prior to Bootstrap 4.1.0 you can add the flex-fill class like this...
.flex-fill {
flex:1
}
As of 4.1 flex-fill
is included in Bootstrap.
Bootstrap 4 Navbar center demos
More centering demos
Center links on desktop, left align on mobile
Related:
How to center nav-items in Bootstrap?
Bootstrap NavBar with left, center or right aligned items
How move 'nav' element under 'navbar-brand' in my Navbar
Use following html
<link rel="stylesheet" href="app/components/directives/navBar/navBar.scss"/>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav">
<li><h5><a href="#/">Home</a></h5></li>
<li>|</li>
<li><h5><a href="#products">About</a></h5></li>
<li>|</li>
<li><h5><a href="#">Contacts</a></h5></li>
<li>|</li>
<li><h5><a href="#cart">Cart</a></h5></li>
</ul>
</div><!-- /.container-fluid -->
</nav>
And css
.navbar-nav {
width: 100%;
text-align: center;
}
.navbar-nav > li {
float: none;
display: inline-block;
}
.navbar-default {
background-color: white;
border-color: white;
}
.navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus{
background-color:white;
}
Modify according to your needs
.navbar-right {
margin-left:auto;
margin-right:auto;
max-width :40%;
float:none !important;
}
just copy this code and change max-width
as you like
I set .navbar-brand { min-height: inherit }
which solved the issue for me (thanks @creimers for inspiration).
It took me a while, but I discovered that including the following was what made it possible to change the navbar color:
.navbar{
background-image: none;
}
For a direct change, you can use Bootstrap classes in the <a>
tag (it won't work in the <div>
):
<h4 class="text-center"><a class="text-warning" href="#">Your text</a></h4>
This should work for alpha 6. The key is the class "mr-auto" on the left nav, which will push the right nav to the right. You also need to add navbar-toggleable-md or it will stack in a column instead of a row. Note I didn't add the remaining toggle items (e.g. toggle button), I added just enough to get it to formatted as requested. Here are more complete examples https://v4-alpha.getbootstrap.com/examples/navbars/.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="nav navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link on the Right</a>
</li>
</ul>
</div>
</nav>
</body>
You must use code as this:
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="logo" rel="home" href="#" title="Buy Sell Rent Everyting">
<img style=""
src="/img/transparent-white-logo.png">
</a>
</div>
Class of A tag must be "logo" not navbar-brand.
Use Come thing link this , This is Based on Bootstrap 3.0
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus {
background-color: #977EBD;
color: #FFFFFF;
}
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
background-color: #977EBD;
color: #FFFFFF;
}
A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml
extension. For instance this would be your index.shtml
file:
<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>
Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).
If the problem you face is the menu breaking into multiple lines, you can try one of the following:
1) Try to reduce the number of menu items or their length, like removing menu items or shortening the words.
2) Reducing the padding between the menu items, like this:
.navbar .nav > li > a {
padding: 10px 15px 10px; /* Change here the second value for padding-left and padding right */
}
Default padding is 15px both sides (left and right).
If you prefer to change each individual side use:
padding-left: 7px;
padding-right: 8px;
This setting affects the dropdown list too.
This doesn't answer the question but it could help others who don't want to mess with the CSS or using LESS variables. The two common approaches to solve this problem.
The following solution worked for me in Bootstrap 3.3.4:
CSS:
/*no collapse*/
.navbar-collapse.collapse.off {
display: block!important;
}
.navbar-collapse.collapse.off ul {
margin: 0;
padding: 0;
}
.navbar-nav.no-collapse>li,
.navbar-nav.no-collapse {
float: left !important;
}
.navbar-right.no-collapse {
float: right!important;
}
then add the .no-collapse class to each of the lists and the .off class to the main container. Here is an example written in jade:
nav.navbar.navbar-default.navbar-fixed-top
.container-fluid
.collapse.navbar-collapse.off
ul.nav.navbar-nav.no-collapse
li
a(href='#' class='glyph')
i(class='glyphicon glyphicon-info-sign')
ul.nav.navbar-nav.navbar-right.no-collapse
li.dropdown
a.dropdown-toggle(href='#', data-toggle='dropdown' role='button' aria-expanded='false')
| Tools
span.caret
ul.dropdown-menu(role='menu')
li
a(href='#') Tool #1
li
a(href='#')
| Logout
You can justify the navbar contents by using:
@media (min-width: 768px){
.navbar-nav{
margin: 0 auto;
display: table;
table-layout: fixed;
float: none;
}
}
See this live: http://jsfiddle.net/panchroma/2fntE/
Good luck!
Working solution:
Bootstrap 3.0 by default has a 15px padding on top and bottom, so we just need to override it!
For example:
.navbar-nav > li > a {padding-top:10px !important; padding-bottom:10px !important;}
.navbar {min-height:40px !important}
In bootstrap.css line 4784 we see:
.navbar-inverse .navbar-inner {
background-color: #FFFFFFF;
background-image: -moz-linear-gradient(top, #222222, #111111);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111));
background-image: -webkit-linear-gradient(top, #222222, #111111);
background-image: -o-linear-gradient(top, #222222, #111111);
background-image: linear-gradient(to bottom, #222222, #111111);
background-repeat: repeat-x;
border-color: #252525;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0);
}
You need to remove all the 'background-image' property declarations to get the desired effect.
I just did this successfully by using the following CSS code.
@media(max-width:1000px) {
.navbar-collapse.collapse {
display: none !important;
}
.navbar-collapse {
overflow-x: visible !important;
}
.navbar-collapse.in {
overflow-y: auto !important;
}
.collapse.in {
display: block !important;
}
}
The simplest solution:
Just divide the navbar
into columns: for instance, if you have 24 columns over all, 12 are going to be empty and 12 are going to contrain the navbar:
<nav class="navbar navbar-default">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-12">
<ul class="nav navbar-nav" align="center">
<li><a href="#">Home</a></li>
<li><a href="#">First Link</a></li>
<li><a href="#">Second Link</a></li>
<li><a href="#">Third Link</a></li>
<li><a href="#">Fourth Link</a></li>
</ul>
</div>
</div>
</nav>
Thanks to @Pylinux. I have used his technique and also modified it to support "one" level of drop down menu (sub ul/li), as that is what I needed. See it in action in the fiddle link below.
Updated Fiddle based on pylinux's answer - http://jsfiddle.net/abhatia/en4qxw6g/
I made the following three changes, in order to support one level drop down menu:
1. Added a class value of dd (dropdown) for "a" element under li which needs to have sub ul list.
<li><a class="dd">This link points to #/fun5</a>
<ul>
<li><a href="#/fun6?some=data">This link points to #/fun6</a>
</li>
<li><a href="#/fun7?some=data">This link points to #/fun7</a>
</li>
<li><a href="#/fun8?some=data">This link points to #/fun8</a>
</li>
<li><a href="#/fun9?some=data">This link points to #/fun9</a>
</li>
</ul>
</li>
2. Updated Javascript to add the following new logic.
if(angular.element(li).parent().parent().children('a').hasClass("dd"))
{angular.element(li).parent().parent().children('a.dd').addClass('active');}
3. Updated CSS to the add the following:
a.active {background-color:red;}
Hopefully this will be helpful to someone looking to implement single level dropdown menu.
I'd go with
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == this.WindowState)
{
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon1.Visible = false;
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
Use this format of querying
let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));
Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
.where('category')
.in(arr)
.exec();
Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.
The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload')
def upload():
key_1 = request.args.get('key1')
key_2 = request.args.get('key2')
print(key_1)
#--> value1
print(key_2)
#--> value2
After params, let's now see how to get the headers:
header_1 = request.headers.get('header1')
header_2 = request.headers.get('header2')
print(header_1)
#--> header_value1
print(header_2)
#--> header_value2
Now let's see how to get the body
file_name = request.files['file'].filename
ref_id = request.form['referenceId']
print(ref_id)
#--> WWB9838yb3r47484
so we fetch the uploaded files with request.files and text with request.form
In asp.net core this works differerently:
public class SomeOtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;
public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void TestSet()
{
_session.SetString("Test", "Ben Rules!");
}
public void TestGet()
{
var message = _session.GetString("Test");
}
}
Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/
As per the official documents, it's not anymore advisable to use matrix class since it will be removed in the future.
https://numpy.org/doc/stable/reference/generated/numpy.matrix.html
As other answers already state that you can achieve all the operations with NumPy arrays.
For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions
@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{
... html for form
}
here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form
$("#btnSubmitFileUpload").click(function(e){
e.preventDefault();
$("#frmUploadTrainingMedia").submit();
});
here is the callback referenced in the AjaxOptions
function displayUploadMediaMsg(d){
var rslt = $.parseJSON(d.responseText);
if (rslt.statusCode == 200){
$().toastmessage("showSuccessToast", rslt.status);
}
else{
$().toastmessage("showErrorToast", rslt.status);
}
}
in the controller method for MVC it looks like this
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// there is only one file ... do something with it
}
return Json(new
{
statusCode = 200,
status = "File uploaded",
file = "",
}, "text/html");
}
else
{
return Json(new
{
statusCode = 400,
status = "Unable to upload file",
file = "",
}, "text/html");
}
}
primitives dont have null value. default have for an int is 0.
if(person.getId()==0){}
Default values for primitives in java:
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
Objects have null as default value.
String (or any object)--->null
1.) I need to check if the object is not null; Is the following expression correct;
if (person == null){
}
the above piece of code checks if person is null. you need to do
if (person != null){ // checks if person is not null
}
and
if(person.equals(null))
The above code would throw NullPointerException when person is null.
Pipe the content of your
Get-ChildItem -recurse | Get-Content | Select-String -pattern "dummy"
to fl *
You will see that the path is already being returned as a property of the objects.
IF you want just the path, use select path
or select -unique path
to remove duplicates:
Get-ChildItem -recurse | Get-Content | Select-String -pattern "dummy" | select -unique path
For IE11 example (browser type=Trident version=7.0):
image.style.transform = "rotate(270deg)";
Here's how I did it at school. I forgot why it is not a good idea.
EDIT:
@Darius Bacon: cites a "Beautiful Code" book which contains an explanation why the belowed code is not a good idea.
#!/usr/bin/env python
from __future__ import division
epsilon = 1e-6
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
class LineSegment:
"""
>>> ls = LineSegment(Point(0,0), Point(2,4))
>>> Point(1, 2) in ls
True
>>> Point(.5, 1) in ls
True
>>> Point(.5, 1.1) in ls
False
>>> Point(-1, -2) in ls
False
>>> Point(.1, 0.20000001) in ls
True
>>> Point(.1, 0.2001) in ls
False
>>> ls = LineSegment(Point(1, 1), Point(3, 5))
>>> Point(2, 3) in ls
True
>>> Point(1.5, 2) in ls
True
>>> Point(0, -1) in ls
False
>>> ls = LineSegment(Point(1, 2), Point(1, 10))
>>> Point(1, 6) in ls
True
>>> Point(1, 1) in ls
False
>>> Point(2, 6) in ls
False
>>> ls = LineSegment(Point(-1, 10), Point(5, 10))
>>> Point(3, 10) in ls
True
>>> Point(6, 10) in ls
False
>>> Point(5, 10) in ls
True
>>> Point(3, 11) in ls
False
"""
def __init__(self, a, b):
if a.x > b.x:
a, b = b, a
(self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)
self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None
def __contains__(self, c):
return (self.x0 <= c.x <= self.x1 and
min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and
(not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))
def y(self, x):
return self.slope * (x - self.x0) + self.y0
if __name__ == '__main__':
import doctest
doctest.testmod()
If you are a beginner, it is better you first go through some basic tutorials and after that learn about naming conventions. I have gone through the following to learn Angular, some of which are very effective.
Tutorials :
Details of application structure and naming conventions can be found in a variety of places. I've gone through 100's of sites and I think these are among the best:
On Mac you need cmd + / to comment and uncomment.
In Java 8+, you can create an IntStream
in the range of 0
to myArray.length
and check that all values are true
in the corresponding (primitive) array with something like,
return IntStream.range(0, myArray.length).allMatch(i -> myArray[i]);
This is quite simple.
yourtextfield.frame = CGRectMake (yourXAxis, yourYAxis, yourWidth, yourHeight);
Declare your textfield as a gloabal property & change its frame where ever you want to do it in your code.
Happy Coding!
if you are using spring and jackson combination you can do it as following. I'm following @gregwhitaker as suggested but implementing in spring style.
<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
<property name="lenient" value="false" />
</bean>
</property>
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
NON_NULL
</value>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref bean="objectMapper" />
</property>
<property name="targetMethod">
<value>enable</value>
</property>
<property name="arguments">
<value type="com.fasterxml.jackson.databind.SerializationFeature">
INDENT_OUTPUT
</value>
</property>
</bean>
public String appendNewStringToExisting(String exisitingString, String newString, int number) {
StringBuilder builder = new StringBuilder(exisitingString);
for(int iDx = 0; iDx < number; iDx++){
builder.append(newString);
}
return builder.toString();
}
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
Because, in Python, integers are immutable (int's += actually returns a different object).
Also, with ++/-- you need to worry about pre- versus post- increment/decrement, and it takes only one more keystroke to write x+=1
. In other words, it avoids potential confusion at the expense of very little gain.
if (combo1.SelectedIndex > -1)
{
// do something
}
if any item is selected selected index will be greater than -1
NoClassDefFoundError doesn't give much of a clue as to what went wrong inside the static block. It is good practice to always have a block like this inside of static { ... } initialization code:
static {
try {
... your init code here
} catch (Throwable t) {
LOG.error("Failure during static initialization", t);
throw t;
}
}
There is a simple workaround that doesn't require you to change any code, and it works in Laravel 4 just as well.
You just use an assignment operator (=
) in the expression passed to an @if
statement, instead of (for instance) an operator such as ==
.
@if ($variable = 'any data, be it string, variable or OOP') @endif
Then you can use it anywhere you can use any other variable
{{ $variable }}
The only downside is your assignment will look like a mistake to someone not aware that you're doing this as a workaround.
var nationality = $("#dancerCountry").val();
should work. Are you sure that the element selector is working properly? Perhaps you should try:
var nationality = $('select[name="dancerCountry"]').val();
It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/
Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value
. You have to wrap in the input in a <form>
tag like with the proper name
attribute, like shown below:
<form name="FormName">
<input type="hidden" name="checkyear" id="checkyear" value="">
</form>
Have you considered using the jQuery Library? Here are the docs for .val()
function.
I also think having a separate "version" for normal execution and as a service is the way to go, but is it really required to dedicate a separate command line switch for that purpose?
Couldn't you just do:
public static int Main(string[] args)
{
if (!Environment.UserInteractive)
{
// Startup as service.
}
else
{
// Startup as application
}
}
That would have the "benefit", that you can just start your app via doubleclick (OK, if you really need that) and that you can just hit F5 in Visual Studio (without the need to modify the project settings to include that /console
Option).
Technically, the Environment.UserInteractive
checks if the WSF_VISIBLE
Flag is set for the current window station, but is there any other reason where it would return false
, apart from being run as a (non-interactive) service?
In Ubuntu 18.04, below are the steps that I followed.
python3 -m pip install --upgrade pip
For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.
hash -r pip
To catch different patterns it is helpful to query with different patterns.
'[\d]+[.,\d]+'
'[\d]*[.][\d]+'
'[\d]+'
(Note: Put complex patterns first else simple patterns will return chunks of the complex catch instead of the complex catch returning the full catch).
p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
Below, we'll confirm a pattern is present with re.search()
, then return an iterable list of catches. Finally, we'll print each catch using bracket notation to subselect the match object return value from the match object.
s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
if re.search(p, s) is not None:
for catch in re.finditer(p, s):
print(catch[0]) # catch is a match object
Returns:
33
42
32
30
444.4
12,001
Just use string methods .replace()
if they occur throughout, or .strip()
if they only occur at the start and/or finish:
a = '"sajdkasjdsak" "asdasdasds"'
a = a.replace('"', '')
'sajdkasjdsak asdasdasds'
# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'
# or, if they only occur at start...
a = a.lstrip('\"')
# or, if they only occur at end...
a = a.rstrip('\"')
Android Emulator Shortcuts
Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
1. Main Device Keys
Home Home Button
F2 Left Softkey / Menu / Settings button (or Page up)
Shift+f2 Right Softkey / Star button (or Page down)
Esc Back Button
F3 Call/ dial Button
F4 Hang up / end call button
F5 Search Button
2. Other Device Keys
Ctrl+F5 Volume up (or + on numeric keyboard with Num Lock off) Ctrl+F6 Volume down (or + on numeric keyboard with Num Lock off) F7 Power Button Ctrl+F3 Camera Button
Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
F8 Toggle cell network
F9 Toggle code profiling
Alt+Enter Toggle fullscreen mode
F6 Toggle trackball mode
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
Add z-index:-1
and position:relative
to .content
#header {_x000D_
background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
height: 128px;_x000D_
}_x000D_
.content {_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
z-index: -1;_x000D_
position:relative;_x000D_
}_x000D_
.td-main {_x000D_
text-align: center;_x000D_
padding: 80px 10px 80px 10px;_x000D_
border: 1px solid #A02422;_x000D_
background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
<div id="header">_x000D_
<div id="header-inner">_x000D_
<table class="content">_x000D_
<col width="400px" />_x000D_
<tr>_x000D_
<td>_x000D_
<table class="content">_x000D_
<col width="400px" />_x000D_
<tr>_x000D_
<td>_x000D_
<div class="logo-class"></div>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td id="menu"></td>_x000D_
</tr>_x000D_
</table>_x000D_
<table class="content">_x000D_
<col width="120px" />_x000D_
<col width="160px" />_x000D_
<col width="120px" />_x000D_
<tr>_x000D_
<td class="td-main">text</td>_x000D_
<td class="td-main">text</td>_x000D_
<td class="td-main">text</td>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<!-- header-inner -->_x000D_
</div>_x000D_
<!-- header -->_x000D_
</body>
_x000D_
A couple of years ago, location
did not work for me in IE and location.href
did (and both worked in other browsers). Since then I have always just used location.href
and never had trouble again. I can't remember which version of IE that was.
For my use-case, I required id generation that was guaranteed to be unique globally; without exception. I struggled with the problem for a while, and came up with a solution called tuid (Truly Unique ID). It generates an id with the first 32 characters being system-generated and the remaining digits representing milliseconds since epoch. In situations where I need to generate id's on client-side javascript, it works well. Have a look:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
curr_year = curr_year.toString().substr(2,2);
document.write(curr_date+"-"+curr_month+"-"+curr_year);
You can change this as your need..
Onfous And onblur Text box with javascript
<input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';" onblur="if(this.value=='') this.value='A new value';"/>
You can use input.value = JSON.stringify(obj)
to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)
The JSON object is available on modern browsers or you can use the json2.js library from json.org
If you are seeing an error like the following:
diff: /../Podfile.lock: No such file or directory diff: /Manifest.lock: No such file or directory error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
Then there's a problem with Cocoapods in your project. Sometimes cocoapods can get out of sync and you need to re-initiate cocoapods. You should be able to resolve this error by:
When you are creating an object of intent, you can take advantage of following two methods for passing objects between two activities.
You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.
Here is a small snippet of code I am using
CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);
And in newly started activity code will be something like this...
Bundle b = this.getIntent().getExtras();
if (b != null)
mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
As far as I know, this is a work-in-progress. They want to do it, but it's not released yet. See 1377 (the "new" 495 that was mentioned by @Andy).
I ended up implementing the "generate .yml as part of CI" approach as proposed by @Thomas.
I had the same problem with PHP. I solved it by changing "localhost" to "127.0.0.1" in database connection parameters like someone suggested here: https://serverfault.com/a/444338/62739 . I think it may work for you too, give it a try.
export HADOOP_HOME=/home/hadoop/hadoop-2.4.1
export PATH=$HADOOP_HOME/bin:$PATH
export HADOOP_PREFIX=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_PREFIX
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_PREFIX/lib/native
export HADOOP_CONF_DIR=$HADOOP_PREFIX/etc/hadoop
export HADOOP_HDFS_HOME=$HADOOP_PREFIX
export HADOOP_MAPRED_HOME=$HADOOP_PREFIX
export HADOOP_YARN_HOME=$HADOOP_PREFIX
export JAVA_LIBRARY_PATH=$HADOOP_HOME/lib/native:$JAVA_LIBRARY_PATH
there is a very useful online tool for this, just automatically transform the table into divs:
http://www.html-cleaner.com/features/replace-html-table-tags-with-divs/
And the video that explains it: https://www.youtube.com/watch?v=R1ArAee6wEQ
I'm using this on a daily basis. I hope it helps ;)
Too Long; Don't Read: The difference is whether the source (local) or the destination address/port is being set. In short, bind()
set the source and connect()
set the destination. Regardless of TCP or UDP.
bind()
bind()
set the socket's local (source) address. This is the address where packets are received. Packets sent by the socket carry this as the source address, so the other host will know where to send back its packets.
If receive is not needed the socket source address is useless. Protocols like TCP require receiving enabled in order to send properly, as the destination host send back a confirmation when one or more packets have arrived (i.e. acknowledgement).
connect()
connect()
triggers the TCP code to try to establish a connection to the other side.connect()
only set a default address to where packets are sent when no address is specified. When connect()
is not used, sendto()
or sendmsg()
must be used containing the destination address.When connect()
or a send function is called, and no address is bound, Linux automatically bind the socket to a random port. For technical details, take a look at inet_autobind()
in Linux kernel source code.
Okay, so if you don't have LINQ, you could hard-code it:
public int FindMaxAge(List<MyType> list)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxAge = int.MinValue;
foreach (MyType type in list)
{
if (type.Age > maxAge)
{
maxAge = type.Age;
}
}
return maxAge;
}
Or you could write a more general version, reusable across lots of list types:
public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxValue = int.MinValue;
foreach (T item in list)
{
int value = projection(item);
if (value > maxValue)
{
maxValue = value;
}
}
return maxValue;
}
You can use this with:
// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });
// C# 3
int maxAge = FindMaxValue(list, x => x.Age);
Or you could use LINQBridge :)
In each case, you can return the if block with a simple call to Math.Max
if you want. For example:
foreach (T item in list)
{
maxValue = Math.Max(maxValue, projection(item));
}
You can toggle the class of the i
element within the clicked anchor like
<i class="fa fa-plus-circle"></i>
then
$('#category-tabs li a').click(function(){
$(this).next('ul').slideToggle('500');
$(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});
Demo: Fiddle
If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
var unsaved = false;
$(":input").change(function () {
unsaved = true;
});
function unloadPage() {
if (unsaved) {
alert("You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?");
}
}
window.onbeforeunload = unloadPage;
Java conveniently has the instanceof
operator (JLS 15.20.2) to test if a given object is of a given type.
if (x instanceof List<?>) {
List<?> list = (List<?>) x;
// do something with list
} else if (x instanceof Collection<?>) {
Collection<?> col = (Collection<?>) x;
// do something with col
}
One thing should be mentioned here: it's important in these kinds of constructs to check in the right order. You will find that if you had swapped the order of the check in the above snippet, the code will still compile, but it will no longer work. That is the following code doesn't work:
// DOESN'T WORK! Wrong order!
if (x instanceof Collection<?>) {
Collection<?> col = (Collection<?>) x;
// do something with col
} else if (x instanceof List<?>) { // this will never be reached!
List<?> list = (List<?>) x;
// do something with list
}
The problem is that a List<?>
is-a Collection<?>
, so it will pass the first test, and the else
means that it will never reach the second test. You have to test from the most specific to the most general type.
I found this (WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link) to contain the rest of the details which are missing from @Andrew's answer.
The one thing I found very useful was that the worker thread couldn't access the MainWindow's controls (in it's own method), however when using a delegate inside the main windows event handler it was possible.
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
pd.Close();
// Get a result from the asynchronous worker
T t = (t)args.Result
this.ExampleControl.Text = t.BlaBla;
};
I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
The UDF approach is my preference compared to brittle substr
values.
#!/usr/bin/env python3
import sqlite3
from dateutil import parser
from pprint import pprint
def date_parse(s):
''' Converts a string to a date '''
try:
t = parser.parse(s, parser.parserinfo(dayfirst=True))
return t.strftime('%Y-%m-%d')
except:
return None
def dict_factory(cursor, row):
''' Helper for dict row results '''
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def main():
''' Demonstrate UDF '''
with sqlite3.connect(":memory:") as conn:
conn.row_factory = dict_factory
setup(conn)
##################################################
# This is the code that matters. The rest is setup noise.
conn.create_function("date_parse", 1, date_parse)
cur = conn.cursor()
cur.execute(''' select "date", date_parse("date") as parsed from _test order by 2; ''')
pprint(cur.fetchall())
##################################################
def setup(conn):
''' Setup some values to parse '''
cur = conn.cursor()
# Make a table
sql = '''
create table _test (
"id" integer primary key,
"date" text
);
'''
cur.execute(sql)
# Fill the table
dates = [
'2/1/03', '03/2/04', '4/03/05', '05/04/06',
'6/5/2007', '07/6/2008', '8/07/2009', '09/08/2010',
'2-1-03', '03-2-04', '4-03-05', '05-04-06',
'6-5-2007', '07-6-2008', '8-07-2009', '09-08-2010',
'31/12/20', '31-12-2020',
'BOMB!',
]
params = [(x,) for x in dates]
cur.executemany(''' insert into _test ("date") values(?); ''', params)
if __name__ == "__main__":
main()
This will give you these results:
[{'date': 'BOMB!', 'parsed': None},
{'date': '2/1/03', 'parsed': '2003-01-02'},
{'date': '2-1-03', 'parsed': '2003-01-02'},
{'date': '03/2/04', 'parsed': '2004-02-03'},
{'date': '03-2-04', 'parsed': '2004-02-03'},
{'date': '4/03/05', 'parsed': '2005-03-04'},
{'date': '4-03-05', 'parsed': '2005-03-04'},
{'date': '05/04/06', 'parsed': '2006-04-05'},
{'date': '05-04-06', 'parsed': '2006-04-05'},
{'date': '6/5/2007', 'parsed': '2007-05-06'},
{'date': '6-5-2007', 'parsed': '2007-05-06'},
{'date': '07/6/2008', 'parsed': '2008-06-07'},
{'date': '07-6-2008', 'parsed': '2008-06-07'},
{'date': '8/07/2009', 'parsed': '2009-07-08'},
{'date': '8-07-2009', 'parsed': '2009-07-08'},
{'date': '09/08/2010', 'parsed': '2010-08-09'},
{'date': '09-08-2010', 'parsed': '2010-08-09'},
{'date': '31/12/20', 'parsed': '2020-12-31'},
{'date': '31-12-2020', 'parsed': '2020-12-31'}]
The SQLite equivalent of anything this robust is a tangled weave of substr
and instr
calls that you should avoid.
LINQ is a query tool (Q = Query) - so there is no magic LINQ way to update just the single row, except through the (object-oriented) data-context (in the case of LINQ-to-SQL). To update data, you need to fetch it out, update the record, and submit the changes:
using(var ctx = new FooContext()) {
var obj = ctx.Bars.Single(x=>x.Id == id);
obj.SomeProp = 123;
ctx.SubmitChanges();
}
Or write an SP that does the same in TSQL, and expose the SP through the data-context:
using(var ctx = new FooContext()) {
ctx.UpdateBar(id, 123);
}
How to use a clock and do assertions
This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.
The key idea is that the process
blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.
library ieee;
use ieee.std_logic_1164.all;
entity counter_tb is
end counter_tb;
architecture behav of counter_tb is
constant width : natural := 2;
constant clk_period : time := 1 ns;
signal clk : std_logic := '0';
signal data : std_logic_vector(width-1 downto 0);
signal count : std_logic_vector(width-1 downto 0);
type io_t is record
load : std_logic;
data : std_logic_vector(width-1 downto 0);
count : std_logic_vector(width-1 downto 0);
end record;
type ios_t is array (natural range <>) of io_t;
constant ios : ios_t := (
('1', "00", "00"),
('0', "UU", "01"),
('0', "UU", "10"),
('0', "UU", "11"),
('1', "10", "10"),
('0', "UU", "11"),
('0', "UU", "00"),
('0', "UU", "01")
);
begin
counter_0: entity work.counter port map (clk, load, data, count);
process
begin
for i in ios'range loop
load <= ios(i).load;
data <= ios(i).data;
wait until falling_edge(clk);
assert count = ios(i).count;
end loop;
wait;
end process;
process
begin
for i in 1 to 2 * ios'length loop
wait for clk_period / 2;
clk <= not clk;
end loop;
wait;
end process;
end behav;
The counter would look like this:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned
entity counter is
generic (
width : in natural := 2
);
port (
clk, load : in std_logic;
data : in std_logic_vector(width-1 downto 0);
count : out std_logic_vector(width-1 downto 0)
);
end entity counter;
architecture rtl of counter is
signal cnt : unsigned(width-1 downto 0);
begin
process(clk) is
begin
if rising_edge(clk) then
if load = '1' then
cnt <= unsigned(data);
else
cnt <= cnt + 1;
end if;
end if;
end process;
count <= std_logic_vector(cnt);
end architecture rtl;
Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches
Here is how I've always done it:
public static string Serialize(object obj) {
using(MemoryStream memoryStream = new MemoryStream())
using(StreamReader reader = new StreamReader(memoryStream)) {
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}
public static object Deserialize(string xml, Type toType) {
using(Stream stream = new MemoryStream()) {
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
DataContractSerializer deserializer = new DataContractSerializer(toType);
return deserializer.ReadObject(stream);
}
}
A static variable inside a function has a lifespan as long as your program runs. It won't be allocated every time your function is called and deallocated when your function returns.
Try with these commands that have been useful with those errors
path\project\storage\framework\views...
php artisan view:clear
path\project\storage\framework/sessions...
php artisan config:cache
Use CultureInfo
class to change your culture info.
var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);
I do not find NoControlUpgrade=1
on my vbp project.
Instead, I develop on both xp and windows7 x64. When I moved the project from window 7 to xp, the error occurred.
From what I find out, these are different:
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCX
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0; MSCOMCTL.OCX
I just changed the #2,1
back to #2.0
on the vbp file and it can run immediately.
These kind of problems occurred before, so hope Microsoft explain and solve them accordingly.
Thanks.
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
If you use location.hostname
you will get your domain.com part. Then location.pathname
will give you /path/folder. I would split location.pathname
by / and reassemble the URL. But unless you need the querystring, you can just redirect to ..
to go a directory above.
I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).
Also in Logic Friday the expression A | B
just returns 3 entries in truth table; I expected 4.
I don't think there is a "apache-common-like" tool to compare maps since the equality of 2 maps is very ambiguous and depends on the developer needs and the map implementation...
For exemple if you compare two hashmaps in java: - You may want to just compare key/values are the same - You may also want to compare if the keys are ordered the same way - You may also want to compare if the remaining capacity is the same ... You can compare a lot of things!
What such a tool would do when comparing 2 different map implementations such that: - One map allow null keys - The other throw runtime exception on map2.get(null)
You'd better to implement your own solution according to what you really need to do, and i think you already got some answers above :)
Just put type="button"
<button type="button"><b>Cancel</b></button>
Because your button is inside a form it is taking default value as submit and type="cancel" doesn't exist.
I use Marked 2 on Mac OS X. It supports the following syntax for including other files.
<<[chapters/chapter1.md]
<<[chapters/chapter2.md]
<<[chapters/chapter3.md]
<<[chapters/chapter4.md]
Sadly, you can't feed that to pandoc as it doesn't understand the syntax. However, writing a script to strip the syntax out to construct a pandoc command line is easy enough.
You can use DateTime.Now.ToShortDateString()
like so:
var test = $"<b>Date of this report:</b> {DateTime.Now.ToShortDateString()}";
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
<httpCookies httpOnlyCookies="true"/>
I am a quite newbie to python and I was having same issue. (windows x64 os) I have solved, doing below steps
If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:
/**
* The interface defines all abstract methods and extends the concrete base class
*/
interface IAnimal extends Animal {
speak() : void;
}
/**
* The abstract base class only defines concrete methods & properties.
*/
class Animal {
private _impl : IAnimal;
public name : string;
/**
* Here comes the clever part: by letting the constructor take an
* implementation of IAnimal as argument Animal cannot be instantiated
* without a valid implementation of the abstract methods.
*/
constructor(impl : IAnimal, name : string) {
this.name = name;
this._impl = impl;
// The `impl` object can be used to delegate functionality to the
// implementation class.
console.log(this.name + " is born!");
this._impl.speak();
}
}
class Dog extends Animal implements IAnimal {
constructor(name : string) {
// The child class simply passes itself to Animal
super(this, name);
}
public speak() {
console.log("bark");
}
}
var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"
Since the Animal
class requires an implementation of IAnimal
it's impossible to construct an object of type Animal
without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal
, not Animal
. E.g.:
//This works
function letTheIAnimalSpeak(animal: IAnimal) {
console.log(animal.name + " says:");
animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
console.log(animal.name + " says:");
animal.speak();
}
The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.
You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.
Class for the type of object you receive:
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
Code:
static void Main(string[] args)
{
string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";
User user = JsonConvert.DeserializeObject<User>(json);
Console.ReadKey();
}
this is a very simple way to parse your json.
I've had this happen on VS after I changed the file's line endings. Changing them back to Windows CR LF fixed the issue.
Try to call object like this:
(<any>Object).dosomething
This error has come because you have declared them as optional using ?
. Now Typescript does strict check and it won't allow doing anything that may be undefined
. Therefore, you can use (<any>yourObject)
here.
We could use built-in function repr()
or string interpolation fr'{}'
escape all backwardslashs \
in Python 3.7.*
repr('my_string')
or fr'{my_string}'
Check the Link: https://docs.python.org/3/library/functions.html#repr
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
The only solution that worked for me was
yarn global add ngrok
yarn global add exp
with npm I was getting permission errors etc..
if(Request::ajax())
Looks to be the right answer. http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax
data = "firstName and favoriteFood"
mandatory_fields = ['firstName', 'lastName', 'age']
# for each
for field in mandatory_fields:
if field not in data:
print("Error, missing req field {0}".format(field));
# still fine, multiple if statements
if ('firstName' not in data or
'lastName' not in data or
'age' not in data):
print("Error, missing a req field");
# not very readable, list comprehension
missing_fields = [x for x in mandatory_fields if x not in data]
if (len(missing_fields)>0):
print("Error, missing fields {0}".format(", ".join(missing_fields)));
This is an old question, but its one I found while searching as well.
If you installed with brew
then the solution would actually be the this:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
One other thing. You may need to specify the -L option as well - eg
-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz
or you may end up with an error like
ld: cannot find -lbaz
Everytime docker successfully executes a RUN
command from a Dockerfile, a new layer in the image filesystem is committed. Conveniently you can use those layers ids as images to start a new container.
Take the following Dockerfile:
FROM busybox
RUN echo 'foo' > /tmp/foo.txt
RUN echo 'bar' >> /tmp/foo.txt
and build it:
$ docker build -t so-2622957 .
Sending build context to Docker daemon 47.62 kB
Step 1/3 : FROM busybox
---> 00f017a8c2a6
Step 2/3 : RUN echo 'foo' > /tmp/foo.txt
---> Running in 4dbd01ebf27f
---> 044e1532c690
Removing intermediate container 4dbd01ebf27f
Step 3/3 : RUN echo 'bar' >> /tmp/foo.txt
---> Running in 74d81cb9d2b1
---> 5bd8172529c1
Removing intermediate container 74d81cb9d2b1
Successfully built 5bd8172529c1
You can now start a new container from 00f017a8c2a6
, 044e1532c690
and 5bd8172529c1
:
$ docker run --rm 00f017a8c2a6 cat /tmp/foo.txt
cat: /tmp/foo.txt: No such file or directory
$ docker run --rm 044e1532c690 cat /tmp/foo.txt
foo
$ docker run --rm 5bd8172529c1 cat /tmp/foo.txt
foo
bar
of course you might want to start a shell to explore the filesystem and try out commands:
$ docker run --rm -it 044e1532c690 sh
/ # ls -l /tmp
total 4
-rw-r--r-- 1 root root 4 Mar 9 19:09 foo.txt
/ # cat /tmp/foo.txt
foo
When one of the Dockerfile command fails, what you need to do is to look for the id of the preceding layer and run a shell in a container created from that id:
docker run --rm -it <id_last_working_layer> bash -il
Once in the container:
If you really need to experiment in the actual layer that failed instead of working from the last working layer, see Drew's answer.
In my case even after uninstalling all 2005 related components it didn't worked. I had to resort to a brute force way and remove following registry keys
32 Bit OS: HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\90
64 Bit OS: HKLM\Software\Wow6432Node\Microsoft\Microsoft SQL Server\90
Usually I do this:
<div>
<p>
<img src='1.jpg' align='left' />
Text Here
<p>
</div>
If it helps anyone, I tried everything above (https w/token mode) - and still nothing was working. I got no errors, but nothing would be installed in node_modules or package_lock.json. If I changed the token or any letter in the repo name or user name, etc. - I'd get an error. So I knew I had the right token and repo name.
I finally realized it's because the name of the dependency I had in my package.json didn't match the name in the package.json of the repo I was trying to pull. Even npm install --verbose doesn't say there's any problem. It just seems to ignore the dependency w/o error.
So i also had a small list where i clearly had the possibility of introducing non-unique values.
I searched for the existence of a unique list of some sort, but then realized that testing the existence of the element before adding it works just fine.
if(not new_element in my_list):
my_list.append(new_element)
I don't know if there are caveats to this simple approach, but it solves my problem.
Use a temp table to insert the range of values, then select the min/max of the temp table from within a stored procedure or UDF. This is a basic construct, so feel free to revise as needed.
For example:
CREATE PROCEDURE GetMinSpeed() AS
BEGIN
CREATE TABLE #speed (Driver NVARCHAR(10), SPEED INT);
'
' Insert any number of data you need to sort and pull from
'
INSERT INTO #speed (N'Petty', 165)
INSERT INTO #speed (N'Earnhardt', 172)
INSERT INTO #speed (N'Patrick', 174)
SELECT MIN(SPEED) FROM #speed
DROP TABLE #speed
END
http://vim.wikia.com/wiki/Search_and_replace
Try this search and replace:
:%s/foo/bar/gc
Change each 'foo' to 'bar', but ask for confirmation first.
Press y or n to change or keep your text.
I found a solution while tinkering around.
People who directly wanna see the results:
With click: https://jsfiddle.net/dt52jazg/
With Hover: https://jsfiddle.net/7gkufLsh/1/
Below is the code:
HTML
<ul class="list">
<li>Hey</li>
<li>This</li>
<li>is</li>
<li>just</li>
<li>a</li>
<li>test</li>
</ul>
<button class="click-me">
Click me
</button>
CSS
.list li {
min-height: 0;
max-height: 0;
opacity: 0;
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.active li {
min-height: 20px;
opacity: 1;
}
JS
(function() {
$('.click-me').on('click', function() {
$('.list').toggleClass('active');
});
})();
Please let me know whether there is any problem with this solution 'coz I feel there would be no restriction of max-height with this solution.
Multiprogramming - A computer running more than one program at a time (like running Excel and Firefox simultaneously)
Multiprocessing - A computer using more than one CPU at a time
Multiprogramming - More than one task/program/job/process can reside into the main memory at one point of time. This ability of the OS is called multiprogramming.
Multitasking: More than one task/program/job/process can reside into the same CPU at one point of time. This ability of the OS is called multitasking.
Multiusers System - a computer system in which multiple terminals connect to a host computer that handles processing tasks.
The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).
It's too late and its working fine in Xcode 7.3.1
if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
//is empty
}
Use DispatchGroup
s to achieve this. You can either get notified when the group's enter()
and leave()
calls are balanced:
func myFunction() {
var a: Int?
let group = DispatchGroup()
group.enter()
DispatchQueue.main.async {
a = 1
group.leave()
}
// does not wait. But the code in notify() gets run
// after enter() and leave() calls are balanced
group.notify(queue: .main) {
print(a)
}
}
or you can wait:
func myFunction() {
var a: Int?
let group = DispatchGroup()
group.enter()
// avoid deadlocks by not using .main queue here
DispatchQueue.global(attributes: .qosDefault).async {
a = 1
group.leave()
}
// wait ...
group.wait()
print(a) // you could also `return a` here
}
Note: group.wait()
blocks the current queue (probably the main queue in your case), so you have to dispatch.async
on another queue (like in the above sample code) to avoid a deadlock.
For anyone still looking into this in order to learn specifically what a stack is, the term "stack" is referring to a "solution stack." A solution stack is simply a complete set of software to address a given problem, usually by combining to provide the platform or infrastructure necessary. This term is the parent of both "server stack" and "web stack." Accordingly, a LAMP stack is a specific and complete set of software specifically aimed at serving dynamic content over the web.
Some extra reading:
https://www.techopedia.com/definition/28154/solution-stack https://en.wikipedia.org/wiki/Solution_stack
package com.idal.cib;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class DBJsonConverter {
static ArrayList<String> data = new ArrayList<String>();
static Connection conn = null;
static PreparedStatement ps = null;
static ResultSet rs = null;
static String path = "";
static String driver="";
static String url="";
static String username="";
static String password="";
static String query="";
@SuppressWarnings({ "unchecked" })
public static void dataLoad(String path) {
JSONObject obj1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
conn = DatabaseConnector.getDbConnection(driver, url, username,
password);
try {
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
ArrayList<String> columnNames = new ArrayList<String>();
if (rs != null) {
ResultSetMetaData columns = rs.getMetaData();
int i = 0;
while (i < columns.getColumnCount()) {
i++;
columnNames.add(columns.getColumnName(i));
}
while (rs.next()) {
JSONObject obj = new JSONObject();
for (i = 0; i < columnNames.size(); i++) {
data.add(rs.getString(columnNames.get(i)));
{
for (int j = 0; j < data.size(); j++) {
if (data.get(j) != null) {
obj.put(columnNames.get(i), data.get(j));
}else {
obj.put(columnNames.get(i), "");
}
}
}
}
jsonArray.add(obj);
obj1.put("header", jsonArray);
FileWriter file = new FileWriter(path);
file.write(obj1.toJSONString());
file.flush();
file.close();
}
ps.close();
} else {
JSONObject obj2 = new JSONObject();
obj2.put(null, null);
jsonArray.add(obj2);
obj1.put("header", jsonArray);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
rs.close();
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@SuppressWarnings("static-access")
public static void main(String[] args) {
// TODO Auto-generated method stub
driver = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@localhost:1521:database";
username = "user";
password = "password";
path = "path of file";
query = "select * from temp_employee";
DatabaseConnector dc = new DatabaseConnector();
dc.getDbConnection(driver,url,username,password);
DBJsonConverter formatter = new DBJsonConverter();
formatter.dataLoad(path);
}
}
package com.idal.cib;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
static Connection conn1 = null;
public static Connection getDbConnection(String driver, String url,
String username, String password) {
// TODO Auto-generated constructor stub
try {
Class.forName(driver);
conn1 = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn1;
}
}
From angular's documentation,
ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit
onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude
The major difference between them is when used with ng-include.
<div ng-include="partialViewUrl" onload="myFunction()"></div>
In this case, myFunction is called everytime the partial view is loaded.
<div ng-include="partialViewUrl" ng-init="myFunction()"></div>
Whereas, in this case, myFunction is called only once when the parent view is loaded.
On Xcode Version 8.1 (8B62) it can be done directly in Attributes Inspector. Select the textField and then choose the appropriate option from Clear Button drop down box, which is located in Attributes Inspector.
This is what I use:
import sys
# cs = case sensitive
# ys = whatever you want to be "yes" - string or tuple of strings
# prompt('promptString') == 1: # only y
# prompt('promptString',cs = 0) == 1: # y or Y
# prompt('promptString','Yes') == 1: # only Yes
# prompt('promptString',('y','yes')) == 1: # only y or yes
# prompt('promptString',('Y','Yes')) == 1: # only Y or Yes
# prompt('promptString',('y','yes'),0) == 1: # Yes, YES, yes, y, Y etc.
def prompt(ps,ys='y',cs=1):
sys.stdout.write(ps)
ii = raw_input()
if cs == 0:
ii = ii.lower()
if type(ys) == tuple:
for accept in ys:
if cs == 0:
accept = accept.lower()
if ii == accept:
return True
else:
if ii == ys:
return True
return False
You might want to check out:
git gui blame <filename>
Gives you a nice graphical display of changes like "git blame" but with clickable links per line, to move into earlier commits. Hover over the links to get a popup with commit details. Not my credits... found it here:
http://zsoltfabok.com/blog/2012/02/git-blame-line-history/
git gui
is a graphical Tcl/Tc interface to git. Without any other params it starts a pretty simple but useful graphical app for committing files, hunks or even single lines and other similar commands like amend, revert, push... It's part of the git stock suite. On windows it is included in the installer. On debian - I don't know about other *nix systems - it has to be installed separately:
apt-get install git-gui
From the docs:
https://git-scm.com/docs/git-gui
DESCRIPTION
A Tcl/Tk based graphical user interface to Git. git gui focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories.
Unlike gitk, git gui focuses on commit generation and single file annotation and does not show project history. It does however supply menu actions to start a gitk session from within git gui.
git gui is known to work on all popular UNIX systems, Mac OS X, and Windows (under both Cygwin and MSYS). To the extent possible OS specific user interface guidelines are followed, making git gui a fairly native interface for users.
COMMANDS
blame
Start a blame viewer on the specified file on the given version (or working directory if not specified).
browser
Start a tree browser showing all files in the specified commit. Files selected through the browser are opened in the blame viewer.
citool
Start git gui and arrange to make exactly one commit before exiting and returning to the shell. The interface is limited to only commit actions, slightly reducing the application’s startup time and simplifying the menubar.
version
Display the currently running version of git gui.
Following
$(document).ready(function() {
});
can be replaced
$(window).bind("load", function() {
// insert your code here
});
There is once more way which i'm using to increase the page load time.
$(document).ready(function() {
$(window).load(function() {
//insert all your ajax callback code here.
//Which will run only after page is fully loaded in background.
});
});
Run the following commands in the terminal:
rm -Rf /Applications/Android\ Studio.app
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/com.google.android.*
rm -Rf ~/Library/Preferences/com.android.*
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Caches/AndroidStudio*
rm -Rf ~/.AndroidStudio*
rm -Rf ~/.gradle
rm -Rf ~/.android
rm -Rf ~/Library/Android*
rm -Rf /usr/local/var/lib/android-sdk/
To delete all projects:
rm -Rf ~/AndroidStudioProjects
I also tried this answer but was not entirely happy with the result. I kept googling around and finally found a Nuget Package that helped me to manage the result I wanted, anno 2021. I would like to share it with the former developers of Stack Overflow.
I used this Nuget Package Gu.WPF.Geometry found via this Github Repository. All credits for develoment should go to Johan Larsson, the owner of this package.
How I used it? I wanted to have the commands as buttons below the zoombox, as shown here in MachineLayoutControl.xaml
.
<UserControl
x:Class="MyLib.MachineLayoutControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:csmachinelayoutdrawlib="clr-namespace:CSMachineLayoutDrawLib"
xmlns:effects="http://gu.se/Geometry">
<UserControl.Resources>
<ResourceDictionary Source="Resources/ResourceDictionaries/AllResourceDictionariesCombined.xaml" />
</UserControl.Resources>
<Grid Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border
Grid.Row="0"
Margin="0,0"
Padding="0"
BorderThickness="1"
Style="{StaticResource Border_Head}"
Visibility="Visible">
<effects:Zoombox
x:Name="ImageBox"
IsManipulationEnabled="True"
MaxZoom="10"
MinZoom="0.1"
Visibility="{Binding Zoombox_Visibility}">
<ContentControl Content="{Binding Viewing_Canvas}" />
</effects:Zoombox>
</Border>
<StackPanel
Grid.Column="1"
Margin="10"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Command="effects:ZoomCommands.Increase"
CommandParameter="2.0"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom In"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.Decrease"
CommandParameter="2.0"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom Out"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.Uniform"
CommandTarget="{Binding ElementName=ImageBox}"
Content="See Full Machine"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.UniformToFill"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom To Machine Width"
Style="{StaticResource StyleForResizeButtons}" />
</StackPanel>
</Grid>
</UserControl>
In the underlying Viewmodel, I had the following relevant code:
public Visibility Zoombox_Visibility { get => movZoombox_Visibility; set { movZoombox_Visibility = value; OnPropertyChanged(nameof(Zoombox_Visibility)); } }
public Canvas Viewing_Canvas { get => mdvViewing_Canvas; private set => mdvViewing_Canvas = value; }
Also, I wanted that immediately on loading, the Uniform to Fill Command was executed, this is something that I managed to do in the code-behind MachineLayoutControl.xaml.cs
. You see that I only set the Zoombox to visible if the command is executed, to avoid "flickering" when the usercontrol is loading.
public partial class MachineLayoutControl : UserControl
{
#region Constructors
public MachineLayoutControl()
{
InitializeComponent();
Loaded += MyWindow_Loaded;
}
#endregion Constructors
#region EventHandlers
private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.ApplicationIdle,
new Action(() =>
{
ZoomCommands.Uniform.Execute(null, ImageBox);
((MachineLayoutControlViewModel)DataContext).Zoombox_Visibility = Visibility.Visible;
}));
}
#endregion EventHandlers
}
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
You can use the python sorting functions' key
parameter to sort the index array instead.
>>> s = [2, 3, 1, 4, 5, 3]
>>> sorted(range(len(s)), key=lambda k: s[k])
[2, 0, 1, 5, 3, 4]
>>>
I'm not familiar enough with Glide, but it looks like if you know the target size, you can use something like this:
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
It looks like you can pass -1,-1
, and get a full size image (purely based on tests, can't see it documented).
Note into(int,int)
returns a FutureTarget<Bitmap>
, so you have to wrap this in a try-catch block covering ExecutionException
and InterruptedException
. Here's a more complete example implementation, tested and working:
class SomeActivity extends Activity {
private Bitmap theBitmap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// onCreate stuff ...
final ImageView image = (ImageView) findViewById(R.id.imageView);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Looper.prepare();
try {
theBitmap = Glide.
with(SomeActivity.this).
load("https://www.google.es/images/srpr/logo11w.png").
asBitmap().
into(-1,-1).
get();
} catch (final ExecutionException e) {
Log.e(TAG, e.getMessage());
} catch (final InterruptedException e) {
Log.e(TAG, e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void dummy) {
if (null != theBitmap) {
// The full bitmap should be available here
image.setImageBitmap(theBitmap);
Log.d(TAG, "Image loaded");
};
}
}.execute();
}
}
Following Monkeyless' suggestion in the comment below (and this appears to be the official way too), you can use a SimpleTarget
, optionally coupled with override(int,int)
to simplify the code considerably. However, in this case the exact size must be provided (anything below 1 isn't accepted):
Glide
.with(getApplicationContext())
.load("https://www.google.es/images/srpr/logo11w.png")
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
image.setImageBitmap(resource); // Possibly runOnUiThread()
}
});
as suggested by @hennry if you required the same image then use new SimpleTarget<Bitmap>()
executes a command and never returns.
It's like a return
statement in a function.
If the command is not found exec
returns false.
It never returns true, because if the command is found it never returns at all.
There is also no point in returning STDOUT
, STDERR
or exit status of the command.
You can find documentation about it in perlfunc
,
because it is a function.
executes a command and your Perl script is continued after the command has finished.
The return value is the exit status of the command.
You can find documentation about it in perlfunc
.
like system
executes a command and your perl script is continued after the command has finished.
In contrary to system
the return value is STDOUT
of the command.
qx//
is equivalent to backticks.
You can find documentation about it in perlop
, because unlike system
and exec
it is an operator.
What is missing from the above is a way to execute a command asynchronously.
That means your perl script and your command run simultaneously.
This can be accomplished with open
.
It allows you to read STDOUT
/STDERR
and write to STDIN
of your command.
It is platform dependent though.
There are also several modules which can ease this tasks.
There is IPC::Open2
and IPC::Open3
and IPC::Run
, as well as
Win32::Process::Create
if you are on windows.
A nice handy overview table from the Bash Hackers Wiki:
Syntax | Effective result |
---|---|
$* |
$1 $2 $3 … ${N} |
$@ |
$1 $2 $3 … ${N} |
"$*" |
"$1c$2c$3c…c${N}" |
"$@" |
"$1" "$2" "$3" … "${N}" |
where c
in the third row is the first character of $IFS
, the Input Field Separator, a shell variable.
If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*"
trick with the input field separator set to tab IFS=$'\t'
.
Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.
var width = 960,_x000D_
height = 500,_x000D_
json = {_x000D_
"nodes": [{_x000D_
"x": 100,_x000D_
"r": 20,_x000D_
"label": "Node 1",_x000D_
"color": "red"_x000D_
}, {_x000D_
"x": 200,_x000D_
"r": 25,_x000D_
"label": "Node 2",_x000D_
"color": "blue"_x000D_
}, {_x000D_
"x": 300,_x000D_
"r": 30,_x000D_
"label": "Node 3",_x000D_
"color": "green"_x000D_
}]_x000D_
};_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
.attr("width", width)_x000D_
.attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
.append("pattern")_x000D_
.attr({_x000D_
"id": "stripes",_x000D_
"width": "8",_x000D_
"height": "8",_x000D_
"fill": "red",_x000D_
"patternUnits": "userSpaceOnUse",_x000D_
"patternTransform": "rotate(60)"_x000D_
})_x000D_
.append("rect")_x000D_
.attr({_x000D_
"width": "4",_x000D_
"height": "8",_x000D_
"transform": "translate(0,0)",_x000D_
"fill": "grey"_x000D_
});_x000D_
_x000D_
function plotChart(json) {_x000D_
/* Define the data for the circles */_x000D_
var elem = svg.selectAll("g myCircleText")_x000D_
.data(json.nodes)_x000D_
_x000D_
/*Create and place the "blocks" containing the circle and the text */_x000D_
var elemEnter = elem.enter()_x000D_
.append("g")_x000D_
.attr("class", "node-group")_x000D_
.attr("transform", function(d) {_x000D_
return "translate(" + d.x + ",80)"_x000D_
})_x000D_
_x000D_
/*Create the circle for each block */_x000D_
var circleInner = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", function(d) {_x000D_
return d.color;_x000D_
});_x000D_
_x000D_
var circleOuter = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", "url(#stripes)");_x000D_
_x000D_
/* Create the text for each block */_x000D_
elemEnter.append("text")_x000D_
.text(function(d) {_x000D_
return d.label_x000D_
})_x000D_
.attr({_x000D_
"text-anchor": "middle",_x000D_
"font-size": function(d) {_x000D_
return d.r / ((d.r * 10) / 100);_x000D_
},_x000D_
"dy": function(d) {_x000D_
return d.r / ((d.r * 25) / 100);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
Output:
Below is the link to codepen
also:
Thanks, Manish Kumar
My solution: https://gist.github.com/pangui/86b5e0610b53ddf28f94 It prevents double click but accepts more clicks after 1 second. Hope it helps.
Here is the code:
jQuery.fn.preventDoubleClick = function() {
$(this).on('click', function(e){
var $el = $(this);
if($el.data('clicked')){
// Previously clicked, stop actions
e.preventDefault();
e.stopPropagation();
}else{
// Mark to ignore next click
$el.data('clicked', true);
// Unmark after 1 second
window.setTimeout(function(){
$el.removeData('clicked');
}, 1000)
}
});
return this;
};
For merging first branch to second one:
on first branch: git merge secondBranch
on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch
Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)
I do like this,you can have a try
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
Although not as straightforward as isinstance(x, list)
one could use as well:
this_is_a_list=[1,2,3]
if type(this_is_a_list) == type([]):
print("This is a list!")
and I kind of like the simple cleverness of that
I'd say don't use angular/js as you can simply use css instead:
In your css, add the class:
.capitalize {
text-transform: capitalize;
}
Then, simply wrap the expression (for ex) in your html:
<span class="capitalize">{{ uppercase_expression }}</span>
No js needed ;)
I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:
<div id="fb-root"></div>
<script>(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>
Then add this to your HTML tag:
xmlns:fb="http://ogp.me/ns/fb#"
Try this mate, you can chuck it in the body like so...
[HttpPost]
[Route("~/API/ChangeTheNameIfNeeded")]
public bool SampleCall([FromBody]JObject data)
{
var firstName = data["firstName"].ToString();
var lastName= data["lastName"].ToString();
var email = data["email"].ToString();
var obj= data["toLastName"].ToObject<SomeObject>();
return _someService.DoYourBiz(firstName, lastName, email, obj);
}
Another example:
[
[
{
"@id":1,
"deviceId":1,
"typeOfDevice":"1",
"state":"1",
"assigned":true
},
{
"@id":2,
"deviceId":3,
"typeOfDevice":"3",
"state":"Excelent",
"assigned":true
},
{
"@id":3,
"deviceId":4,
"typeOfDevice":"júuna",
"state":"Excelent",
"assigned":true
},
{
"@id":4,
"deviceId":5,
"typeOfDevice":"nffjnff",
"state":"Regular",
"assigned":true
},
{
"@id":5,
"deviceId":6,
"typeOfDevice":"44",
"state":"Excelent",
"assigned":true
},
{
"@id":6,
"deviceId":7,
"typeOfDevice":"rr",
"state":"Excelent",
"assigned":true
},
{
"@id":7,
"deviceId":8,
"typeOfDevice":"j",
"state":"Excelent",
"assigned":true
},
{
"@id":8,
"deviceId":9,
"typeOfDevice":"55",
"state":"Excelent",
"assigned":true
},
{
"@id":9,
"deviceId":10,
"typeOfDevice":"5",
"state":"Excelent",
"assigned":true
},
{
"@id":10,
"deviceId":11,
"typeOfDevice":"5",
"state":"Excelent",
"assigned":true
}
],
1
]
$.each(data[0], function(i, item) {
data[0][i].deviceId + data[0][i].typeOfDevice + data[0][i].state + data[0][i].assigned
});
Use http://www.jsoneditoronline.org/ to understand the JSON code better
I landed on this page trying to figure out a sane way to validate strings as "valid" urls. I share here my solution using python3. No extra libraries required.
See https://docs.python.org/2/library/urlparse.html if you are using python2.
See https://docs.python.org/3.0/library/urllib.parse.html if you are using python3 as I am.
import urllib
from pprint import pprint
invalid_url = 'dkakasdkjdjakdjadjfalskdjfalk'
valid_url = 'https://stackoverflow.com'
tokens = [urllib.parse.urlparse(url) for url in (invalid_url, valid_url)]
for token in tokens:
pprint(token)
min_attributes = ('scheme', 'netloc') # add attrs to your liking
for token in tokens:
if not all([getattr(token, attr) for attr in min_attributes]):
error = "'{url}' string has no scheme or netloc.".format(url=token.geturl())
print(error)
else:
print("'{url}' is probably a valid url.".format(url=token.geturl()))
ParseResult(scheme='', netloc='', path='dkakasdkjdjakdjadjfalskdjfalk', params='', query='', fragment='')
ParseResult(scheme='https', netloc='stackoverflow.com', path='', params='', query='', fragment='')
'dkakasdkjdjakdjadjfalskdjfalk' string has no scheme or netloc.
'https://stackoverflow.com' is probably a valid url.
Here is a more concise function:
from urllib.parse import urlparse
min_attributes = ('scheme', 'netloc')
def is_valid(url, qualifying=min_attributes):
tokens = urlparse(url)
return all([getattr(tokens, qualifying_attr)
for qualifying_attr in qualifying])
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; }
is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
int result = 0;
for (int i=0; i < positiveInteger; i++)
{
result = startingNumber + 1;
cout << result;
}
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
import java.util.Scanner;
class SwiCas {
public static void main(String as[]) {
Scanner s= new Scanner(System.in);
char a=s.next().charAt(0);//this line shows how to take character input in java
switch(a) {
case 'a':
System.out.println("Vowel....");
break;
case 'e':
System.out.println("Vowel....");
break;
case 'i':
System.out.println("Vowel....");
break;
case 'o':
System.out.println("Vowel....");
break;
case 'u':
System.out.println("Vowel....");
break;
case 'A':
System.out.println("Vowel....");
break;
case 'E':
System.out.println("Vowel....");
break;
case 'I':
System.out.println("Vowel....");
break;
case 'O':
System.out.println("Vowel....");
break;
case 'U':
System.out.println("Vowel....");
break;
default:
System.out.println("Consonants....");
}
}
}
There are 2 causes:
1- store procedure name When you declare store procedure in code make sure you do not exec or execute keyword for example:
C#
string sqlstr="sp_getAllcustomers";// right way to declare it.
string sqlstr="execute sp_getAllCustomers";//wrong way and you will get that error message.
From this code:
MSDBHelp.ExecuteNonQuery(sqlconexec, CommandType.StoredProcedure, sqlexec);
CommandType.StoreProcedure
will look for only store procedure name and ExecuteNonQuery
will execute the store procedure behind the scene.
2- connection string:
Another cause is the wrong connection string. Look inside the connection string and make sure you have the connection especially the database name and so on.
I used the solution of mockinterface, though the sed -i didn't quite work I solved it by deleting the line by hand with vim:
sudo vim /var/lib/sss/pubconf/known_hosts
You can use any other text editor you want, but probably you'll need to show your administrative privileges
If you are using sourcetree: Repository -> Repository Settings --> Advanced --> uncheck "Use global user settings" box
worked great for me.
Inside ContentPlaceholder, put the placeholder control.For Example like this,
<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
<asp:PlaceHolder ID="metatags" runat="server">
</asp:PlaceHolder>
</asp:Content>
Code Behind:
HtmlMeta hm1 = new HtmlMeta();
hm1.Name = "Description";
hm1.Content = "Content here";
metatags.Controls.Add(hm1);
You can modify the .form-control:focus
color without altering the bootstrap style in this way:
.form-control:focus {
border-color: #28a745;
box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
}
.form-control:focus
and copy the parameters that you want to modify into your css. In this case is border-color
and box-shadow
.border-color
. In this case I choose to pick up the same green the bootstrap uses for their .btn-success
class, by searching for that particular class in the bootstrap.css page mentioned in the step 1.box-shadow
parameter without altering the fourth RGBA parameter (0.25) that bootstrap has for transparency.Yes, you should use semicolons after every statement in JavaScript.
I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm
Which works nicely. :)
If you want to be sure, that you are scrolling to the end after *ngFor is done, you can use this.
<div #myList>
<div *ngFor="let item of items; let last = last">
{{item.title}}
{{last ? scrollToBottom() : ''}}
</div>
</div>
scrollToBottom() {
this.myList.nativeElement.scrollTop = this.myList.nativeElement.scrollHeight;
}
Important here, the "last" variable defines if you are currently at the last item, so you can trigger the "scrollToBottom" method
Think of ob_start()
as saying "Start remembering everything that would normally be outputted, but don't quite do anything with it yet."
For example:
ob_start();
echo("Hello there!"); //would normally get printed to the screen/output to browser
$output = ob_get_contents();
ob_end_clean();
There are two other functions you typically pair it with: ob_get_contents()
, which basically gives you whatever has been "saved" to the buffer since it was turned on with ob_start()
, and then ob_end_clean()
or ob_flush()
, which either stops saving things and discards whatever was saved, or stops saving and outputs it all at once, respectively.
For renaming recursively I use the following commands:
find -iname \*.* | rename -v "s/ /-/g"
Here are available options if it helps anyone for on_delete
CASCADE, DO_NOTHING, PROTECT, SET, SET_DEFAULT, SET_NULL
Use the stringInsert function rather than the putinplace function. I was using the later function to parse a mysql query. Although the output looked alright, the query resulted in a error which took me a while to track down. The following is my version of the stringInsert function requiring only one parameter.
function stringInsert($str,$insertstr,$pos)
{
$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
return $str;
}
Unicode is a fairly complex standard. Don’t be too afraid, but be prepared for some work! [2]
Because a credible resource is always needed, but the official report is massive, I suggest reading the following:
A brief explanation:
Computers read bytes and people read characters, so we use encoding standards to map characters to bytes. ASCII was the first widely used standard, but covers only Latin (7 bits/character can represent 128 different characters). Unicode is a standard with the goal to cover all possible characters in the world (can hold up to 1,114,112 characters, meaning 21 bits/character max. Current Unicode 8.0 specifies 120,737 characters in total, and that's all).
The main difference is that an ASCII character can fit to a byte (8 bits), but most Unicode characters cannot. So encoding forms/schemes (like UTF-8 and UTF-16) are used, and the character model goes like this:
Every character holds an enumerated position from 0 to 1,114,111 (hex: 0-10FFFF) called code point.
An encoding form maps a code point to a code unit sequence. A code unit is the way you want characters to be organized in memory, 8-bit units, 16-bit units and so on. UTF-8 uses 1 to 4 units of 8 bits, and UTF-16 uses 1 or 2 units of 16 bits, to cover the entire Unicode of 21 bits max. Units use prefixes so that character boundaries can be spotted, and more units mean more prefixes that occupy bits. So, although UTF-8 uses 1 byte for the Latin script it needs 3 bytes for later scripts inside Basic Multilingual Plane, while UTF-16 uses 2 bytes for all these. And that's their main difference.
Lastly, an encoding scheme (like UTF-16BE or UTF-16LE) maps (serializes) a code unit sequence to a byte sequence.
character: p
code point: U+03C0
encoding forms (code units):
UTF-8: CF 80
UTF-16: 03C0
encoding schemes (bytes):
UTF-8: CF 80
UTF-16BE: 03 C0
UTF-16LE: C0 03
Tip: a hex digit represents 4 bits, so a two-digit hex number represents a byte
Also take a look at Plane maps in Wikipedia to get a feeling of the character set layout
This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this
automatically gets set to the global scope. This can be confusing because you expect this
to have the same value as in the outer function.
var car = {};
car.starter = {};
car.start = function(){
var that = this;
// you can access car.starter inside this method with 'this'
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to the global scope
// 'this.starter' is undefined, so we use 'that' instead.
that.starter.active = true;
// you could also use car.starter, but using 'that' gives
// us more consistency and flexibility
};
activateStarter();
};
This is specifically a problem when you create a function as a method of an object (like car.start
in the example) then create a function inside that method (like activateStarter
). In the top level method this
points to the object it is a method of (in this case, car
) but in the inner function this
now points to the global scope. This is a pain.
Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that
is used. It's an easily recognizable convention for overcoming a shortcoming in the language.
Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.
You should use the new HttpClient
. You can find more information here.
http
.get<any>('url', {observe: 'response'})
.subscribe(resp => {
console.log(resp.headers.get('X-Token'));
});
While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me:
It is noteworthy, that in order to parse through a 2-digit year, e.g. '90' rather than '1990', a %y
is required instead of a %Y
.
If parsing with a pre-defined format still doesn't work for you, try using the flag infer_datetime_format=True
, for example:
yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)
Be advised that this solution is slower than using a pre-defined format.
I've found the liquibase.database.typeconversion.core.AbstractTypeConverter
class.
It lists all types that can be used:
protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
// Translate type to database-specific type, if possible
DataType returnTypeName = null;
if (dataTypeName.equalsIgnoreCase("BIGINT")) {
returnTypeName = getBigIntType();
} else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
returnTypeName = getNumberType();
} else if (dataTypeName.equalsIgnoreCase("BLOB")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
returnTypeName = getBooleanType();
} else if (dataTypeName.equalsIgnoreCase("CHAR")) {
returnTypeName = getCharType();
} else if (dataTypeName.equalsIgnoreCase("CLOB")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
returnTypeName = getCurrencyType();
} else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
returnTypeName = getDateType();
} else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
returnTypeName = getDoubleType();
} else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
returnTypeName = getFloatType();
} else if (dataTypeName.equalsIgnoreCase("INT")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
returnTypeName = getLongBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
returnTypeName = getSmallIntType();
} else if (dataTypeName.equalsIgnoreCase("TEXT")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
returnTypeName = getTimeType();
} else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
returnTypeName = getTinyIntType();
} else if (dataTypeName.equalsIgnoreCase("UUID")) {
returnTypeName = getUUIDType();
} else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
returnTypeName = getVarcharType();
} else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
returnTypeName = getNVarcharType();
} else {
return new CustomType(columnTypeString,0,2);
}
This can be done very elegantly with Ray.
To parallelize your example, you'd need to define your functions with the @ray.remote
decorator, and then invoke them with .remote
.
import ray
ray.init()
# Define the functions.
@ray.remote
def solve1(a):
return 1
@ray.remote
def solve2(b):
return 2
# Start two tasks in the background.
x_id = solve1.remote(0)
y_id = solve2.remote(1)
# Block until the tasks are done and get the results.
x, y = ray.get([x_id, y_id])
There are a number of advantages of this over the multiprocessing module.
These function calls can be composed together, e.g.,
@ray.remote
def f(x):
return x + 1
x_id = f.remote(1)
y_id = f.remote(x_id)
z_id = f.remote(y_id)
ray.get(z_id) # returns 4
Note that Ray is a framework I've been helping develop.
remove this in your manifest file
xmlns:tools="http://schemas.android.com/tools"
SHOW TABLES LIKE 'TableName'
If you have ANY results, the table exists.
To use this approach in PDO:
$pdo = new \PDO(/*...*/);
$result = $pdo->query("SHOW TABLES LIKE 'tableName'");
$tableExists = $result !== false && $result->rowCount() > 0;
To use this approach with DEPRECATED mysql_query
$result = mysql_query("SHOW TABLES LIKE 'tableName'");
$tableExists = mysql_num_rows($result) > 0;
Note: The answer below was written in 2010. Here many years later, both keyCode
and which
are deprecated in favor of key
(for the logical key) and code
(for the physical placement of the key). But note that IE doesn't support code
, and its support for key
is based on an older version of the spec so isn't quite correct. As I write this, the current Edge based on EdgeHTML and Chakra doesn't support code
either, but Microsoft is rolling out its Blink- and V8- based replacement for Edge, which presumably does/will.
Some browsers use keyCode
, others use which
.
If you're using jQuery, you can reliably use which
as jQuery standardizes things; More here.
If you're not using jQuery, you can do this:
var key = 'which' in e ? e.which : e.keyCode;
Or alternatively:
var key = e.which || e.keyCode || 0;
...which handles the possibility that e.which
might be 0
(by restoring that 0
at the end, using JavaScript's curiously-powerful ||
operator).
If you're using Ubuntu, you can put a shell script in one of these folders: /etc/cron.daily
, /etc/cron.hourly
, /etc/cron.monthly
or /etc/cron.weekly
.
For more detail, check out this post: https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job
just replace your line with this
notificationManager.notify(Unique_Integer_Number, notification);
hope it will help you.
On Ubuntu, I was running Python 3 and I had to install
sudo apt-get install python3-dev
If you want to use a version of Python that is not linked to python3, install the associated python3.x-dev package. For example:
sudo apt-get install python3.5-dev
Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().
"hello " + str(10) + " world" = "hello 10 world"
Hope that helps!
Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.
attr_accessor
is getter
, setter
method.
whereas attr_accessible
is to say that particular attribute is accessible or not. that's it.
I wish to add we should use Strong parameter instead of attr_accessible
to protect from mass asignment.
Cheers!
If using Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
Example:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
I know its very late to answer this but hope this may help anyone.
you can create button like radio button using IBOutletCollection
. create one IBOutletCollection property in our .h file.
@property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *ButtonArray;
connect all button with this IBOutletCollection and make one IBAction method for all three button.
- (IBAction)btnTapped:(id)sender {
for ( int i=0; i < [self.ButtonArray count]; i++) {
[[self.ButtonArray objectAtIndex:i] setImage:[UIImage
imageNamed:@"radio-off.png"]
forState:UIControlStateNormal];
}
[sender setImage:[UIImage imageNamed:@"radio-on.png"]
forState:UIControlStateNormal];
}
you need not to delete all your profiles.I had same issue and fixed it by installing the missing certificates. You might forgot to install the required certificate for the provisioning profile you are using for code signing.
GIFs store colors as one of x number of possible colors in a palette. Read about the gif limited color palette. So PIL is giving you the palette index, rather than the color information of that palette color.
Edit: Removed link to a blog post solution that had a typo. Other answers do the same thing without the typo.
If you want to move from c:\
and you want to go to c:\Documents and settings
, write on console: c:\Documents\[space]+tab
and cygwin will autocomplete it as c:\Documents\ and\ settings/
I am changing your id to current-month (having no space)
alert($('#current-month').attr('month'));
alert($('#current-month').attr('year'));
You need to use Iterator
and call remove()
on iterator
instead of using for
loop.
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyType')
--stuff
sys.types... they aren't schema-scoped objects so won't be in sys.objects
Update, Mar 2013
You can use TYPE_ID too
The width is being restricted by the size of the body. If you make the width of the body larger you will see it stays on one line with the background color.
To maintain the minimum width: min-width:100%
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Try this:
if (Boolean.TRUE.equals(yourValue)) { ... }
As additional benefit this is null-safe.
Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended
const rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
{_x000D_
country: elem.country,_x000D_
launches: elem.launches+10_x000D_
} _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
In my Notepad++ 7.2.2
, the Preferences
section it's a bit different.
The option is located at: Settings
/ Preferences
/ Language
/ Replace by space
as in the Screenshot.
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.
DFS is more space-efficient than BFS, but may go to unnecessary depths.
Their names are revealing: if there's a big breadth (i.e. big branching factor), but very limited depth (e.g. limited number of "moves"), then DFS can be more preferrable to BFS.
It should be mentioned that there's a less-known variant that combines the space efficiency of DFS, but (cummulatively) the level-order visitation of BFS, is the iterative deepening depth-first search. This algorithm revisits some nodes, but it only contributes a constant factor of asymptotic difference.
Use the java.lang.Math class, and specifically for absolute value and square root:, the abs()
and sqrt()
methods.
The C++ String Toolkit Library (Strtk) has the following solution to your problem:
#include <string>
#include <deque>
#include <vector>
#include "strtk.hpp"
int main()
{
std::string int_string = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
std::vector<int> int_list;
strtk::parse(int_string,",",int_list);
std::string double_string = "123.456|789.012|345.678|901.234|567.890";
std::deque<double> double_list;
strtk::parse(double_string,"|",double_list);
return 0;
}
More examples can be found Here
In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.
Good Luck with your project
If your using Visual Studio just run the application with Crtl + F5 instead of F5. This will leave the console open when it's finished executing.
It's not relative to performance...
You set async to false, when you need that ajax request to be completed before the browser passes to other codes:
<script>
// ...
$.ajax(... async: false ...); // Hey browser! first complete this request,
// then go for other codes
$.ajax(...); // Executed after the completion of the previous async:false request.
</script>
This is not the exact answer for your question, but this may help you
public class JsonParser {
private static DefaultHttpClient httpClient = ConnectionManager.getClient();
public static List<Club> getNearestClubs(double lat, double lon) {
// YOUR URL GOES HERE
String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
List<Club> ret = new ArrayList<Club>();
HttpResponse response = null;
HttpGet getMethod = new HttpGet(getUrl);
try {
response = httpClient.execute(getMethod);
// CONVERT RESPONSE TO STRING
String result = EntityUtils.toString(response.getEntity());
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(result);
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
long id = jo.getLong("id");
String name = jo.getString("name");
String address = jo.getString("address");
String country = jo.getString("country");
String zip = jo.getString("zip");
double clat = jo.getDouble("lat");
double clon = jo.getDouble("lon");
String url = jo.getString("url");
String number = jo.getString("number");
// CONVERT DATA FIELDS TO CLUB OBJECT
Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
ret.add(c);
}
} catch (Exception e) {
e.printStackTrace();
}
// RETURN LIST OF CLUBS
return ret;
}
}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:
JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
%d
is for integers use %f
instead, it works for both float
and double
types:
double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000
Another way is to edit the .gitconfig
(create one if not exist), for instance:
vim ~/.gitconfig
and then add:
[color]
diff = auto
status = auto
branch = auto
The first 2 examples act very differently if you are REPLACING them by something. If you match on this:
str = str.replace(/^(7|8|9)/ig,'');
you would replace 7 or 8 or 9 by the empty string.
If you match on this
str = str.replace(/^[7|8|9]/ig,'');
you will replace 7
or 8
or 9
OR THE VERTICAL BAR!!!! by the empty string.
I just found this out the hard way.
My solution:
int mkrdir(const char *path, int index, int permission)
{
char bf[NAME_MAX];
if(*path == '/')
index++;
char *p = strchr(path + index, '/');
int len;
if(p) {
len = MIN(p-path, sizeof(bf)-1);
strncpy(bf, path, len);
bf[len]=0;
} else {
len = MIN(strlen(path)+1, sizeof(bf)-1);
strncpy(bf, path, len);
bf[len]=0;
}
if(access(bf, 0)!=0) {
mkdir(bf, permission);
if(access(bf, 0)!=0) {
return -1;
}
}
if(p) {
return mkrdir(path, p-path+1, permission);
}
return 0;
}
I checked all above answers in practice with my page on iOS (iPhone 6, iOS 10.0.2), but with no success. This is my working solution:
$(window).bind('gesturestart touchmove', function(event) {
event = event.originalEvent || event;
if (event.scale !== 1) {
event.preventDefault();
document.body.style.transform = 'scale(1)'
}
});
Hey Having trouble viewing documents produced on Windows?
You can try a fine solution easy:
yum install curl cabextract xorg-x11-font-utils fontconfig
After this I need reboot my system CentOS6.
GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".
Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:
CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;
because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:
CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;
You dont have a function named assign()
, but a method with this name. PHP is not Java and in PHP you have to make clear, if you want to call a function
assign()
or a method
$object->assign()
In your case the call to the function resides inside another method. $this
always refers to the object, in which a method exists, itself.
$this->assign()
I think this is solved by Tillito:
Entity Framework and SQL Server View
I'll quote his entry below:
We had the same problem and this is the solution:
To force entity framework to use a column as a primary key, use ISNULL.
To force entity framework not to use a column as a primary key, use NULLIF.
An easy way to apply this is to wrap the select statement of your view in another select.
Example:
SELECT
ISNULL(MyPrimaryID,-999) MyPrimaryID,
NULLIF(AnotherProperty,'') AnotherProperty
FROM ( ... ) AS temp
answered Apr 26 '10 at 17:00 by Tillito
It is also possible to use enumeration.
typedef enum {
typeNo1 = 1,
typeNo2,
typeNo3,
typeNo4,
NumOfTypes = typeNo4
} TypeOfSomething;
This is working fine for me
I have add dependency
compile 'commons-codec:commons-codec:1.9'
ref: http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9
my function
public String encode(String key, String data) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.
Here is an example of how this works:
class Foo {
Foo(String str) { }
}
class Bar extends Foo {
Bar(String str) {
// Here I am explicitly calling the superclass
// constructor - since constructors are not inherited
// you must chain them like this.
super(str);
}
}
appendChild
is a pure javascript method where as append
is a jQuery method.
See here: Git doesn't clone all branches on subsequent clones?
If you really want this by pulling branches instead of push --mirror
, you can have a look here:
"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones
This answer provides detailed steps on how to achieve that relatively easily:
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
I ran into a similar error
"from: can't read /var/mail/django.test.utils"
when trying to run a command
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
in the tutorial at https://docs.djangoproject.com/en/1.8/intro/tutorial05/
after reading the answer by Tamás I realized I was not trying this command in the python shell but in the termnial (this can happen to those new to linux)
solution was to first enter in the python shell with the command python and when you get these >>> then run any python commands
Ideally you need to have .d.ts
file for typings to let Linting
work.
But It seems that d3gauge
doesn't have one, you can Ask the developers to provide and hope they will listen.
Alternatively, you can solve this specific issue by doing this
declare var drawGauge: any;
import '../../../../js/d3gauge.js';
export class MemMonComponent {
createMemGauge() {
new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js
}
}
If you use it in multiple files, you can create a d3gauage.d.ts
file with the content below
declare var drawGauge: any;
and reference it in your boot.ts
(bootstrap) file at the top, like this
///<reference path="../path/to/d3gauage.d.ts"/>
It's the Return or Enter key on keyboard.
since df.save(path, source, mode)
is deprecated, (http://spark.apache.org/docs/1.5.0/api/scala/index.html#org.apache.spark.sql.DataFrame)
use df.write.format(source).mode("overwrite").save(path)
where df.write is DataFrameWriter
'source' can be ("com.databricks.spark.avro" | "parquet" | "json")
I solved the problem by using the Rnd() function:
Function RollD6() As UInteger
RollD6 = (Math.Floor(6 * Rnd())) + 1
Return RollD6
End Function
When the form loads, I use the Randomize() method to make sure I don't always get the same sequence of random numbers from run to run.
In SQL Server 2008:
Try this
data to load:
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>
get a utf8 to base64 convertor and convert the "svg" string to:
PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=
and the CSP is
img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=
ifdef $(HAVE_CLIENT) libtest_LIBS = \ $(top_builddir)/libclient.la else ifdef $(HAVE_SERVER) libtest_LIBS = \ $(top_builddir)/libserver.la else libtest_LIBS = endif endif
NOTE: DO NOT indent the if then it don't work!
Syntax:
class Sample
{
public:
int Sam_x;
int Sam_y;
Sample(): Sam_x(1), Sam_y(2) /* Classname: Initialization List */
{
// Constructor body
}
};
Need of Initialization list:
class Sample
{
public:
int Sam_x;
int Sam_y;
Sample() */* Object and variables are created - i.e.:declaration of variables */*
{ // Constructor body starts
Sam_x = 1; */* Defining a value to the variable */*
Sam_y = 2;
} // Constructor body ends
};
in the above program, When the class’s constructor is executed, Sam_x and Sam_y are created. Then in constructor body, those member data variables are defined.
Use cases:
In C, variables must be defined during creation. the same way in C++, we must initialize the Const and Reference variable during object creation by using Initialization list. if we do initialization after object creation (Inside constructor body), we will get compile time error.
Member objects of Sample1 (base) class which do not have default constructor
class Sample1
{
int i;
public:
Sample1 (int temp)
{
i = temp;
}
};
// Class Sample2 contains object of Sample1
class Sample2
{
Sample1 a;
public:
Sample2 (int x): a(x) /* Initializer list must be used */
{
}
};
While creating object for derived class which will internally calls derived class constructor and calls base class constructor (default). if base class does not have default constructor, user will get compile time error. To avoid, we must have either
1. Default constructor of Sample1 class
2. Initialization list in Sample2 class which will call the parametric constructor of Sample1 class (as per above program)
Class constructor’s parameter name and Data member of a Class are same:
class Sample3 {
int i; /* Member variable name : i */
public:
Sample3 (int i) /* Local variable name : i */
{
i = i;
print(i); /* Local variable: Prints the correct value which we passed in constructor */
}
int getI() const
{
print(i); /*global variable: Garbage value is assigned to i. the expected value should be which we passed in constructor*/
return i;
}
};
As we all know, local variable having highest priority then global variable if both variables are having same name. In this case, the program consider "i" value {both left and right side variable. i.e: i = i} as local variable in Sample3() constructor and Class member variable(i) got override. To avoid, we must use either
1. Initialization list
2. this operator.
@alvas's answer does the job but it can be done way faster. Assuming that you have documents
: a list of strings.
from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize
stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation
for doc in documents:
list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]
Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2
times faster, which is significant if you need to operate through many documents.
For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.
P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]
inside of a loop.
When using the new ruby, the image folder will go to asset folder on folder app
after placing your images in image folder, use
<%=image_tag("example_image.png", alt: "Example Image")%>
Note that there are multiple iPad Pros, each with a different Viewports: When emulating an iPad Pro via the Chrome developer tools, the iPad Pro (12.9") is the default option. If you want to emulate one of the other iPad Pros (10.5" or 9.7") with a different viewport, you'll need to add a custom emulated device with the correct specs.
You can search devices, viewports, and their respective CSS media queries at: http://vizdevices.yesviz.com/devices.php.
For instance, the iPad Pro (12.9") would have the following media queries:
/* Landscape */
@media only screen and (min-width: 1366px) and (orientation: landscape) { /* Your Styles... */ }
/*Portrait*/
@media only screen and (min-width: 1024px) and (orientation: portrait) { /* Your Styles... */ }
Whereas the iPad Pro (10.5") will have:
/* Landscape */
@media only screen and (min-device-width: 1112px) and (orientation: landscape) { /* Your Styles... */ }
/*Portrait*/
@media only screen and (min-device-width: 834px) and (orientation: portrait) { /* Your Styles... */ }