I prefer going the long route. These are the checks I follow to avoid using a try-except clause -
Here, DATA
is the suspect variable -
DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty
Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :
http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html
Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....
As none of the other answers worked for me, I decided to post this as an answer for others looking for a solution who also found the same problem. Both the html and body needed to be set with min-height
or the gradient would not fill the body height.
I found Stephen P's comment to provide the correct answer to this.
html {
/* To make use of full height of page*/
min-height: 100%;
margin: 0;
}
body {
min-height: 100%;
margin: 0;
}
When I have the html (or the html and body) height set to 100%,
html {
height: 100%;
margin: 0;
}
body {
min-height: 100%;
margin: 0;
}
Many say it is not possible, I would go one step further and say it is not meaningfull.
A static member is something that does not relate to any instance, only to the class.
A virtual member is something that does not relate directly to any class, only to an instance.
So a static virtual member would be something that does not relate to any instance or any class.
Suppose we have a df_data data frame as below
> df_data
ID MONTH-YEAR VALUE
1 110 JAN.2012 1000
2 111 JAN.2012 2000
3 121 FEB.2012 3000
4 131 FEB.2012 4000
5 141 MAR.2012 5000
To count number of rows in df_data grouped by MONTH-YEAR column, you can use:
> summary(df_data$`MONTH-YEAR`)
FEB.2012 JAN.2012 MAR.2012
2 2 1
summary function will create a table from the factor argument, then create a vector for the result (line 7 & 8)
Variable definitions right:
$ => SCSS, SASS
-- => CSS
@ => LESS
All answers is good but question a little different than answers
"about Sass. How is SCSS different from CSS" : scss is well formed CSS3 syntax. uses sass preprocessor to create that.
and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.
Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.
The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.
What Is A CSS Preprocessor?
CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.
Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.
Sass – Syntactically Awesome Style Sheets
Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.
Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.
Syntax Declaration: Sass vs SCSS
Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.
Sass SYNTAX
$font-color: #fff
$bg-color: #00f
#box
color: $font-color
background: $bg-color
SCSS SYNTAX
$font-color: #fff;
$bg-color: #00f;
#box{
color: $font-color;
background: $bg-color;
}
In both cases, be it Sass or SCSS, the compiled CSS code will be the same –
#box {
color: #fff;
background: #00f;
Usage of Sass
Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.
LESS – Leaner Style Sheets
LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.
@font-color: #fff;
@bg-color: #00f
#box{
color: @font-color;
background: @bg-color;
}
COMPILED CSS
#box {
color: #fff;
background: #00f;
}
Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat
Stylus
The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.
Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.
STYLUS SYNTAX WRITTEN LIKE NATIVE CSS
font-color = #fff;
bg-color = #00f;
#box {
color: font-color;
background: bg-color;
}
OR
STYLUS SYNTAX WITHOUT CURLY BRACES
font-color = #fff;
bg-color = #00f;
#box
color: font-color;
background: bg-color;
OR
STYLUS SYNTAX WITHOUT COLONS AND SEMICOLONS
font-color = #fff
bg-color = #00f
#box
color font-color
background bg-color
There is a better why to determine type of an image. with exif_imagetype
If you use this function, you can tell image's real extension.
with this function filename's extension is completely irrelevant, which is good.
function setHeaderContentType(string $filePath): void
{
$numberToContentTypeMap = [
'1' => 'image/gif',
'2' => 'image/jpeg',
'3' => 'image/png',
'6' => 'image/bmp',
'17' => 'image/ico'
];
$contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
if ($contentType === null) {
throw new Exception('Unable to determine content type of file.');
}
header("Content-type: $contentType");
}
You can add more types from the link.
Hope it helps.
input[readonly]
{
background-color:blue;
}
https://curtistimson.co.uk/post/css/style-readonly-attribute-css/
Just read it in to MATLAB in one block
fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);
You can then process it using logical addressing
ind50 = data{2}>=50 ;
ind50 is then an index of the rows where column 2 is greater than 50. So
data{1}(ind50)
will list all the strings for the rows of interest.
Then just use fprintf
to write out your data to the new file
This is how you can achieve this.
upstream {
nodeapp 127.0.0.1:8080;
}
server {
listen 80;
# The host name to respond to
server_name cdn.domain.com;
location /(.*) {
proxy_pass http://nodeapp/$1$is_args$args;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Real-Port $server_port;
proxy_set_header X-Real-Scheme $scheme;
}
}
You can also use this configuration to load balance amongst multiple Node processes like so:
upstream {
nodeapp 127.0.0.1:8081;
nodeapp 127.0.0.1:8082;
nodeapp 127.0.0.1:8083;
}
Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.
Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I don't need to configure WINS anymore. Feel free to add the WINS code if you need it.
For the case anybody likes to use the refactored/modernized code I put it back into the community here.
/// <summary>
/// Helper class to set networking configuration like IP address, DNS servers, etc.
/// </summary>
public class NetworkConfigurator
{
/// <summary>
/// Set's a new IP Address and it's Submask of the local machine
/// </summary>
/// <param name="ipAddress">The IP Address</param>
/// <param name="subnetMask">The Submask IP Address</param>
/// <param name="gateway">The gateway.</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetIP(string ipAddress, string subnetMask, string gateway)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
{
using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
{
// Set new IP address and subnet if needed
if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
{
if (!String.IsNullOrEmpty(ipAddress))
{
newIP["IPAddress"] = new[] { ipAddress };
}
if (!String.IsNullOrEmpty(subnetMask))
{
newIP["SubnetMask"] = new[] { subnetMask };
}
managementObject.InvokeMethod("EnableStatic", newIP, null);
}
// Set mew gateway if needed
if (!String.IsNullOrEmpty(gateway))
{
using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
{
newGateway["DefaultIPGateway"] = new[] { gateway };
newGateway["GatewayCostMetric"] = new[] { 1 };
managementObject.InvokeMethod("SetGateways", newGateway, null);
}
}
}
}
}
}
}
/// <summary>
/// Set's the DNS Server of the local machine
/// </summary>
/// <param name="nic">NIC address</param>
/// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
/// <remarks>Requires a reference to the System.Management namespace</remarks>
public void SetNameservers(string nic, string dnsServers)
{
using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (var networkConfigs = networkConfigMng.GetInstances())
{
foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
{
using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
{
newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
}
}
}
}
}
I think what you're asking about is how to create responsive spacing between rows
or col-xx-xx
classes.
You can definitely do this with the col-xx-offset-xx
class:
<div class="col-xs-4">
</div>
<div class="col-xs-7 col-xs-offset-1">
</div>
As for adding margin
or padding
directly to elements, there are some simple ways to do this depending on your element. You can use btn-lg
or label-lg
or well-lg
. If you're ever wondering, how can i give this alittle padding. Try adding the primary class name
+ lg
or sm
or md
depending on your size needs:
<button class="btn btn-success btn-lg btn-block">Big Button w/ Display: Block</button>
If it takes a long time to fail, then enlarge the wait_timeout
variable.
If it fails right away, enlarge the max_allowed_packet
variable; it it still doesn't work, make sure the command is valid SQL. Mine had unescaped quotes which screwed everything up.
Also, if feasible, consider limiting the number of inserts of a single SQL command to, say, 1000. You can create a script that creates multiple statements out of a single one by reintroducing the INSERT... part every n inserts.
It sounds like you want a StackPanel
where the final element uses up all the remaining space. But why not use a DockPanel
? Decorate the other elements in the DockPanel
with DockPanel.Dock="Top"
, and then your help control can fill the remaining space.
XAML:
<DockPanel Width="200" Height="200" Background="PowderBlue">
<TextBlock DockPanel.Dock="Top">Something</TextBlock>
<TextBlock DockPanel.Dock="Top">Something else</TextBlock>
<DockPanel
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Margin="10">
<GroupBox
DockPanel.Dock="Right"
Header="Help"
Width="100"
Background="Beige"
VerticalAlignment="Stretch"
VerticalContentAlignment="Stretch"
Height="Auto">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap" />
</GroupBox>
<StackPanel DockPanel.Dock="Left" Margin="10"
Width="Auto" HorizontalAlignment="Stretch">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</DockPanel>
</DockPanel>
If you are on a platform without DockPanel
available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:
<Grid Width="200" Height="200" Background="PowderBlue">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<TextBlock>Something</TextBlock>
<TextBlock>Something else</TextBlock>
</StackPanel>
<Grid Height="Auto" Grid.Row="1" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<GroupBox
Width="100"
Height="Auto"
Grid.Column="1"
Background="Beige"
Header="Help">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap"/>
</GroupBox>
<StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</Grid>
You can create a new queue item to do your removing of the class:
$("#div").addClass("error").delay(1000).queue(function(next){
$(this).removeClass("error");
next();
});
Or using the dequeue method:
$("#div").addClass("error").delay(1000).queue(function(){
$(this).removeClass("error").dequeue();
});
The reason you need to call next
or dequeue
is to let jQuery know that you are done with this queued item and that it should move on to the next one.
For Swift 2.3
extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
self.setAttributedTitle(attributedString, forState: .Normal)
}
}
and in ViewController
@IBOutlet var yourButton: UIButton!
in ViewDidLoad
Method or in your function just write
yourButton.underline()
it will underline the title of your button
You just have to use class="row-eq-height"
with your class="row"
to get equal height columns for previous bootstrap versions.
but with bootstrap 4 this comes natively.
check this link --http://getbootstrap.com.vn/examples/equal-height-columns/
You should use Linking
.
Example from the docs:
class OpenURLButton extends React.Component {
static propTypes = { url: React.PropTypes.string };
handleClick = () => {
Linking.canOpenURL(this.props.url).then(supported => {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log("Don't know how to open URI: " + this.props.url);
}
});
};
render() {
return (
<TouchableOpacity onPress={this.handleClick}>
{" "}
<View style={styles.button}>
{" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
</View>
{" "}
</TouchableOpacity>
);
}
}
Here's an example you can try on Expo Snack:
import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Another solution could be something like following (works depending on your element's display property):
HTML:
<div class="left-align">Left</div>
<div class="right-align">Right</div>
CSS:
.left-align {
margin-left: 0;
margin-right: auto;
}
.right-align {
margin-left: auto;
margin-right: 0;
}
You could create a class that extends the Tkinter Button
class, that will be specialised to close your window by associating the destroy
method to its command
attribute:
from tkinter import *
class quitButton(Button):
def __init__(self, parent):
Button.__init__(self, parent)
self['text'] = 'Good Bye'
# Command to close the window (the destory method)
self['command'] = parent.destroy
self.pack(side=BOTTOM)
root = Tk()
quitButton(root)
mainloop()
This is the output:
And the reason why your code did not work before:
def close_window ():
# root.destroy()
window.destroy()
I have a slight feeling you might got the root from some other place, since you did window = tk()
.
When you call the destroy on the window
in the Tkinter means destroying the whole application, as your window
(root window) is the main window for the application. IMHO, I think you should change your window
to root
.
from tkinter import *
def close_window():
root.destroy() # destroying the main window
root = Tk()
frame = Frame(root)
frame.pack()
button = Button(frame)
button['text'] ="Good-bye."
button['command'] = close_window
button.pack()
mainloop()
In Mongoose: from the document:
To remove a document from a subdocument array we may pass an object with a matching _id.
contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works
See Leonid Beschastny's answer for the correct answer.
I had this problem too (encountered through Macports compilers). Previous versions of Xcode would let you install command line tools through xcode/Preferences, but xcode5 doesn't give a command line tools option in the GUI, that so I assumed it was automatically included now. Try running this command:
xcode-select --install
(as per this answer)
sudo apt-get install libc6-dev
(as per this comment)
apk add libc-dev
Or maybe even easier
grep -R put **/*bills*
The **
glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.
In newer JavaScript standards like ES5 and ES6 you can just say
> Boolean(0) //false
> Boolean(null) //false
> Boolean(undefined) //false
all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say
if (Boolean(myvar)){
// Do something
}
here "null" or "empty string" or "undefined" will be handled efficiently.
In case anyone is looking for recursive.
<?php
echo scanDirectoryImages("images");
/**
* Recursively search through directory for images and display them
*
* @param array $exts
* @param string $directory
* @return string
*/
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))), $exts)
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:100px;max-width:100px" /></a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
It seems that you don't have WRITE permission on /tmp
.
Edit the configuration variable session.save_path with the function session_save_path() to 1 directory above public_html
(so external users wouldn't access the info).
To a first order approximation, a method (in C++ style OO) is another word for a member function, that is a function that is part of a class.
In languages like C/C++ you can have functions which are not members of a class; you don't call a function not associated with a class a method.
Your best option will be to create a simple data structure to model what you have. Then you can store these objects in a simple list and sort/retrieve them any way you wish.
For this case, I'd use the following class:
class Fruit:
def __init__(self, name, color, quantity):
self.name = name
self.color = color
self.quantity = quantity
def __str__(self):
return "Name: %s, Color: %s, Quantity: %s" % \
(self.name, self.color, self.quantity)
Then you can simply construct "Fruit" instances and add them to a list, as shown in the following manner:
fruit1 = Fruit("apple", "red", 12)
fruit2 = Fruit("pear", "green", 22)
fruit3 = Fruit("banana", "yellow", 32)
fruits = [fruit3, fruit2, fruit1]
The simple list fruits
will be much easier, less confusing, and better-maintained.
Some examples of use:
All outputs below is the result after running the given code snippet followed by:
for fruit in fruits:
print fruit
Unsorted list:
Displays:
Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22
Name: apple, Color: red, Quantity: 12
Sorted alphabetically by name:
fruits.sort(key=lambda x: x.name.lower())
Displays:
Name: apple, Color: red, Quantity: 12
Name: banana, Color: yellow, Quantity: 32
Name: pear, Color: green, Quantity: 22
Sorted by quantity:
fruits.sort(key=lambda x: x.quantity)
Displays:
Name: apple, Color: red, Quantity: 12
Name: pear, Color: green, Quantity: 22
Name: banana, Color: yellow, Quantity: 32
Where color == red:
red_fruit = filter(lambda f: f.color == "red", fruits)
Displays:
Name: apple, Color: red, Quantity: 12
As of Select2 4.x, it always returns an array, even for non-multi select lists.
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
For Select2 3.x and lower
Single select:
var data = $('your-original-element').select2('data');
if(data) {
alert(data.text);
}
Note that when there is no selection, the variable 'data' will be null.
Multi select:
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
alert(data[1].text);
alert(data[1].id);
From the 3.x docs:
data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.
data method invoked on a single-select with an unset value will return null, while a data method invoked on an empty multi-select will return [].
StartDate < EndDate
When I tested this, I tried using the position property and it worked perfectly.
HTML
<div class="main">
<div class="body">
//add content here
</body>
</div>
CSS
.main{
position: relative;
}
.body{
position: absolute;
height: 100%;
}
Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.
Array can be initialized as :
let emptyArray = [String]()
It shows that its an array of type string
The type of the emptyArray variable is inferred to be [String] from the type of the initializer.
For Creating the array of type string with elements
var groceryList: [String] = ["Eggs", "Milk"]
groceryList has been initialized with two items
The groceryList variable is declared as “an array of string values”, written as [String]. This particular array has specified a value type of String, it is allowed to store String values only.
There are various properities of array like :
- To check if array has elements (If array is empty or not)
isEmpty property( Boolean ) for checking whether the count property is equal to 0:
if groceryList.isEmpty {
print("The groceryList list is empty.")
} else {
print("The groceryList is not empty.")
}
- Appending(adding) elements in array
You can add a new item to the end of an array by calling the array’s append(_:) method:
groceryList.append("Flour")
groceryList now contains 3 items.
Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):
groceryList += ["Baking Powder"]
groceryList now contains 4 items
groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
groceryList now contains 7 items
you can do this too with animation, its very simple
$('html, body').animate({
scrollTop: $('footer').offset().top
//scrollTop: $('#your-id').offset().top
//scrollTop: $('.your-class').offset().top
}, 'slow');
hope helps, thank you
for windows users: In case of you can't remove .lock
file and it gives you the following:
And you know that eclipse is already closed, just open Task Manager then processes then end precess
for all eclipse.exe occurrences in the processes list.
Try
contact.ContactType = differentContactType;
or
contact.ContactTypeId = 3;
You are trying to set the Id of the ContactType (of the Contact) to 3.
so its true, just add a primary key
Note: be sure that when you're updating your EF diagram from the database that you're pointing to the right database, in my case the connection string was pointing to a local DB instead of the up-to-date Dev DB, schoolboy error i know, but I wanted to post this because it can be very frustrating if you're convinced you've added the primary key and you're still getting the same error
If an element has bootstrap's "hide" class and you want to display it with some sliding effect such as .slideDown()
, you can cheat bootstrap like:
$('#hiddenElement').hide().removeClass('hide').slideDown('fast')
Other answers may have shorter code but this one should be the most efficient and is easy to understand.
/**
* Get key of the max value
*
* @var array $array
* @return mixed
*/
function array_key_max_value($array)
{
$max = null;
$result = null;
foreach ($array as $key => $value) {
if ($max === null || $value > $max) {
$result = $key;
$max = $value;
}
}
return $result;
}
It seems the behavior of defer and async is browser dependent, at least on the execution phase. NOTE, defer only applies to external scripts. I'm assuming async follows same pattern.
In IE 11 and below, the order seems to be like this:
In Edge, Webkit, etc, the async attribute seems to be either ignored or placed at the end:
In newer browsers, the data-pagespeed-no-defer attribute runs before any other external scripts. This is for scripts that don't depend on the DOM.
NOTE: Use defer when you need an explicit order of execution of your external scripts. This tells the browser to execute all deferred scripts in order of placement in the file.
ASIDE: The size of the external javascripts did matter when loading...but had no effect on the order of execution.
If you're worried about the performance of your scripts, you may want to consider minification or simply loading them dynamically with an XMLHttpRequest.
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
You need to first run initdb. It will create the database cluster and the initial setup
See How to configure postgresql for the first time? and http://www.postgresql.org/docs/8.4/static/app-initdb.html
Simple solution in 2 lines of code. Just use the copy constructor. No need to write TrulyObservableCollection etc.
Example:
speakers.list[0].Status = "offline";
speakers.list[0] = new Speaker(speakers.list[0]);
Another method without copy constructor. You can use serialization.
speakers.list[0].Status = "offline";
//speakers.list[0] = new Speaker(speakers.list[0]);
var tmp = JsonConvert.SerializeObject(speakers.list[0]);
var tmp2 = JsonConvert.DeserializeObject<Speaker>(tmp);
speakers.list[0] = tmp2;
If you don't need it to behave as an anchor tag then I would prefer to replace it at all. For example if your anchor tag is like
<a class="MyLink" href="http://www.google.com"><span>My</span> <strong>Link</strong></a>
then using jquery you can do this when you need to display text instead of a link.
var content = $(".MyLink").text(); // or .html()
$(".MyLink").replaceWith("<div>" + content + "</div>")
So this way, we can simply replace anchor tag with a div tag. This is much easier (just 2 lines) and semantically correct as well (because we don't need a link now therefore should not have a link)
"Stack Me 123 Heppa1 oeu".toCharArray()
?
Yes.
ThisWorkbook.RefreshAll
Or, if your Excel version is old enough,
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
For Each Pivot in Sheet.PivotTables
Pivot.RefreshTable
Pivot.Update
Next
Next
if you have no systemctl and started the docker daemon by:
sudo service docker start
you can stop it by:
sudo service docker stop
You can get some information :
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
Fake: We acquire or build a very lightweight implementation of the same functionality as provided by a component that the SUT depends on and instruct the SUT to use it instead of the real.
Stub : This implementation is configured to respond to calls from the SUT with the values (or exceptions) that will exercise the Untested Code (see Production Bugs on page X) within the SUT. A key indication for using a Test Stub is having Untested Code caused by the inability to control the indirect inputs of the SUT
Mock Object that implements the same interface as an object on which the SUT (System Under Test) depends. We can use a Mock Object as an observation point when we need to do Behavior Verification to avoid having an Untested Requirement (see Production Bugs on page X) caused by an inability to observe side-effects of invoking methods on the SUT.
I try to simplify by using : Mock and Stub. I use Mock when it's an object that returns a value that is set to the tested class. I use Stub to mimic an Interface or Abstract class to be tested. In fact, it doesn't really matter what you call it, they are all classes that aren't used in production, and are used as utility classes for testing.
Generalized:
char* subString (const char* input, int offset, int len, char* dest)
{
int input_len = strlen (input);
if (offset + len > input_len)
{
return NULL;
}
strncpy (dest, input + offset, len);
return dest;
}
char dest[80];
const char* source = "hello world";
if (subString (source, 0, 5, dest))
{
printf ("%s\n", dest);
}
With ES6 you can use rest parameters for varagrs
. This takes the argument list and converts it to an array.
function logArgs(...args) {
console.log(args.length)
for(let arg of args) {
console.log(arg)
}
}
You can as long as
The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module documentation goes here
and here
and ...
"""
Why this is a good one:
See also: https://www.python.org/dev/peps/pep-0263/
If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).
There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
function doSomething() {_x000D_
console.log( theId.value );_x000D_
}
_x000D_
<input id="theId" value="test" onclick="doSomething()" />
_x000D_
if DOM element has id then you can use it in js directly
You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!
Technically, ANSI should be the same as US-ASCII. It refers to the ANSI X3.4 standard, which is simply the ANSI organisation's ratified version of ASCII. Use of the top-bit-set characters is not defined in ASCII/ANSI as it is a 7-bit character set.
However years of misuse of the term by the DOS and subsequently Windows community has left its practical meaning as “the system codepage of whatever machine is being used”. The system codepage is also sometimes known as ‘mbcs’, since on East Asian systems that can be a multiple-byte-per-character encoding. Some code pages can even use top-bit-clear bytes as trailing bytes in a multibyte sequence, so it's not even strict compatible with plain ASCII... but even then, it's still called “ANSI”.
On US and Western European default settings, “ANSI” maps to Windows code page 1252. This is not the same as ISO-8859-1 (although it is quite similar). On other machines it could be anything else at all. This makes “ANSI” utterly useless as an external encoding identifier.
To expand on @hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:
<?php if (is_single()): ?>
<p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
<p>This will be shown otherwise.</p>
<?php endif; ?>
To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode
. The appropriate converter is automatically configured.
@PostMapping(value="/process")
public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
System.out.println(payload);
}
Open terminal and run the following:
curl https://api.codetabs.com/v1/loc?github=username/reponame
Jon skeet said:
The documentation seems pretty clear to me: "Base implementation of HttpClient that also implements Closeable" - HttpClient is an interface; CloseableHttpClient is an abstract class, but because it implements AutoCloseable you can use it in a try-with-resources statement.
But then Jules asked:
@JonSkeet That much is clear, but how important is it to close HttpClient instances? If it's important, why is the close() method not part of the basic interface?
Answer for Jules
close need not be part of basic interface since underlying connection is released back to the connection manager automatically after every execute
To accommodate the try-with-resources statement. It is mandatory to implement Closeable. Hence included it in CloseableHttpClient.
Note:
close method in AbstractHttpClient which is extending CloseableHttpClient is deprecated, I was not able to find the source code for that.
Try adding the line c = cv.WaitKey(10)
at the bottom of your repeat()
method.
This waits for 10 ms for the user to enter a key. Even if you're not using the key at all, put this in. I think there just needed to be some delay, so time.sleep(10)
may also work.
In regards to the camera index, you could do something like this:
for i in range(3):
capture = cv.CaptureFromCAM(i)
if capture: break
This will find the index of the first "working" capture device, at least for indices from 0-2. It's possible there are multiple devices in your computer recognized as a proper capture device. The only way I know of to confirm you have the right one is manually looking at your light. Maybe get an image and check its properties?
To add a user prompt to the process, you could bind a key to switching cameras in your repeat loop:
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
def repeat():
global capture #declare as globals since we are assigning to them now
global camera_index
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
c = cv.WaitKey(10)
if(c=="n"): #in "n" key is pressed while the popup window is in focus
camera_index += 1 #try the next camera index
capture = cv.CaptureFromCAM(camera_index)
if not capture: #if the next camera index didn't work, reset to 0.
camera_index = 0
capture = cv.CaptureFromCAM(camera_index)
while True:
repeat()
disclaimer: I haven't tested this so it may have bugs or just not work, but might give you at least an idea of a workaround.
You could try to put a ServletFilter
in front of the webservice and inspect request and response going to / returned from the service.
Although you specifically did not ask for a proxy, sometimes I find tcptrace is enough to see what goes on on a connection. It's a simple tool, no install, it does show the data streams and can write to file too.
An ES6 implementation based on biziclops great answer:
root = {_x000D_
text: "root",_x000D_
children: [{_x000D_
text: "c1",_x000D_
children: [{_x000D_
text: "c11"_x000D_
}, {_x000D_
text: "c12"_x000D_
}]_x000D_
}, {_x000D_
text: "c2",_x000D_
children: [{_x000D_
text: "c21"_x000D_
}, {_x000D_
text: "c22"_x000D_
}]_x000D_
}, ]_x000D_
}_x000D_
_x000D_
console.log("DFS:")_x000D_
DFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
console.log("BFS:")_x000D_
BFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
function BFS(root, getChildren, visit) {_x000D_
let nodesToVisit = [root];_x000D_
while (nodesToVisit.length > 0) {_x000D_
const currentNode = nodesToVisit.shift();_x000D_
nodesToVisit = [_x000D_
...nodesToVisit,_x000D_
...(getChildren(currentNode) || []),_x000D_
];_x000D_
visit(currentNode);_x000D_
}_x000D_
}_x000D_
_x000D_
function DFS(root, getChildren, visit) {_x000D_
let nodesToVisit = [root];_x000D_
while (nodesToVisit.length > 0) {_x000D_
const currentNode = nodesToVisit.shift();_x000D_
nodesToVisit = [_x000D_
...(getChildren(currentNode) || []),_x000D_
...nodesToVisit,_x000D_
];_x000D_
visit(currentNode);_x000D_
}_x000D_
}
_x000D_
If you are behind a firewall you will have to configure the Tortoise client to connect to it. Right click somewhere in your window, select "TortoiseSVN", select "settings", and then select "network" on the left side of the panel. Fill out all the required fields. Good luck.
The adjective Stateful or Stateless refers only to the state of the conversation, it is not in connection with the concept of function which provides the same output for the same input. If so any dynamic web application (with a database behind it) would be a stateful service, which is obviously false. With this in mind if I entrust the task to keep conversational state in the underlying technology (such as a coockie or http session) I'm implementing a stateful service, but if all the necessary information (the context) are passed as parameters I'm implementing a stateless service. It should be noted that even if the passed parameter is an "identifier" of the conversational state (e.g. a ticket or a sessionId) we are still operating under a stateless service, because the conversation is stateless (the ticket is continually passed between client and server), and are the two endpoints to be, so to speak, "stateful".
You can either go for the const char*
solution mentioned above, but then if you need string all the time, you're going to have a lot of overhead.
On the other hand, static string needs dynamic initialization, thus if you want to use its value during another global/static variable's initialization, you might hit the problem of initialization order. To avoid that, the cheapest thing is accessing the static string object through a getter, which checks if your object is initialized or not.
//in a header
class A{
static string s;
public:
static string getS();
};
//in implementation
string A::s;
namespace{
bool init_A_s(){
A::s = string("foo");
return true;
}
bool A_s_initialized = init_A_s();
}
string A::getS(){
if (!A_s_initialized)
A_s_initialized = init_A_s();
return s;
}
Remember to only use A::getS()
. Because any threading can only started by main()
, and A_s_initialized
is initialized before main()
, you don't need locks even in a multithreaded environment. A_s_initialized
is 0 by default (before the dynamic initialization), so if you use getS()
before s is initialized, you call the init function safely.
Btw, in the answer above: "static const std::string RECTANGLE() const" , static functions cannot be const
because they cannot change the state if any object anyway (there is no this pointer).
Try to bypass CORS:
For Chrome: edit shortcut or with cmd: C:\Chrome.exe --disable-web-security
For Firefox: Open Firefox and type about:config into the URL bar. search for: security.fileuri.strict_origin_policy set to false
Imagine a <span>
element inside a <div>
. If you give the <span>
element a height of 100px and a red border for example, it will look like this with
display: inline
display: inline-block
display: block
Code: http://jsfiddle.net/Mta2b/
Elements with display:inline-block
are like display:inline
elements, but they can have a width and a height. That means that you can use an inline-block element as a block while flowing it within text or other elements.
Difference of supported styles as summary:
margin-left
, margin-right
, padding-left
, padding-right
margin
, padding
, height
, width
Use below XML configuration to configure logs into two or more files:
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender2" type="log4net.Appender.RollingFileAppender">
<file value="logs\log1.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="RollingLogFileAppender" />
</root>
<logger additivity="false" name="RollingLogFileAppender2">
<level value="All"/>
<appender-ref ref="RollingLogFileAppender2" />
</logger>
</log4net>
Above XML configuration logs into two different files. To get specific instance of logger programmatically:
ILog logger = log4net.LogManager.GetLogger ("RollingLogFileAppender2");
You can append two or more appender elements inside log4net root element for logging into multiples files.
More info about above XML configuration structure or which appender is best for your application, read details from below links:
https://logging.apache.org/log4net/release/manual/configuration.html https://logging.apache.org/log4net/release/sdk/index.html
You can resize images using CSS just fine if you're modifying an image tag:
<img src="example.png" style="width:2em; height:3em;" />
You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size
.
What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background
Adding a small variation to estani's excellent answer
Local to ISO 8601 with TimeZone and no microsecond info (Python 3):
import datetime, time
utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(microsecond=0, tzinfo=datetime.timezone(offset=utc_offset)).isoformat()
Sample Output:
'2019-11-06T12:12:06-08:00'
Tested that this output can be parsed by both Javascript Date
and C# DateTime
/DateTimeOffset
i use dumpsys to catch if app is crashed and process is still active. situation i used it is to find about remote machine app is crashed or not.
dumpsys | grep myapp | grep "Application Error"
or
adb shell dumpsys | grep myapp | grep Error
or anything that helps...etc
if app is not running you will get nothing as result. When app is stoped messsage is shown on screen by android, process is still active and if you check via "ps" command or anything else, you will see process state is not showing any error or crash meaning. But when you click button to close message, app process will cleaned from process list. so catching crash state without any code in application is hard to find. but dumpsys helps you.
To solve your other problem, where you need to set scrolled
if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:
var timer = 0;
$(window).scroll(function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
scrolled = $(window).scrollTop();
}, 250);
});
Both of them increase the variable i
by one. It's like saying i = i + 1
. The difference is subtle. If you're using it in a loop like this, there's no difference:
for (int i = 0; i < 100; i++) {
}
for (int i = 0; i < 100; ++i) {
}
If you want to know the difference, look at this example:
int a = 0;
int b = a++; // b = 0; a = 1
a = 0;
b = ++a: // b = 1; a = 1
The idea is that ++a
increments a
and returns that value, while a++
returns a's value and then increments a
.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=Vacation2010
SET new=December
for /f "tokens=*" %%f in ('dir /b *.jpg') do (
SET newname=%%f
SET newname=!newname:%old%=%new%!
move "%%f" "!newname!"
)
What this does is it loops over all .jpg files in the folder where the batch file is located and replaces the Vacation2010 with December inside the filenames.
<a href='javascript:void(0);'>some text</a>
static variables are stored in the heap
As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.
On each entry in textbox (event - Handles RestrictedTextBox.TextChanged), you can do a try to caste entered text into integer, if failure occurs, you just reset the value of the text in RestrictedTextBox to last valid entry (which gets constantly updating under the temp1 variable).
Here's how to go about it. In the sub that loads with the form (me.load or mybase.load), initialize temp1 to the default value of RestrictedTextBox.Text
Dim temp1 As Integer 'initialize temp1 default value, you should do this after the default value for RestrictedTextBox.Text was loaded.
If (RestrictedTextBox.Text = Nothing) Then
temp1 = Nothing
Else
Try
temp1 = CInt(RestrictedTextBox.Text)
Catch ex As Exception
temp1 = Nothing
End Try
End If
At any other point in form:
Private Sub textBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles RestrictedTextBox.TextChanged
Try
temp1 = CInt(RestrictedTextBox.Text) 'If user inputs integer, this will succeed and temp will be updated
Catch ex As Exception
RestrictedTextBox.Text = temp1.ToString 'If user inputs non integer, textbox will be reverted to state the state it was in before the string entry
End Try
End Sub
The nice thing about this is that you can use this to restrict a textbox to any type you want: double, uint etc....
Another way to do this in AngularJS is to use a Grid.
The advantage with grids is that the row sorting behavior you are looking for is included by default.
The functionality is well encapsulated. You don't need to add ng-click attributes, or use scope variables to maintain state:
<body ng-controller="MyCtrl">
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
You just add the grid options to your controller:
$scope.gridOptions = {
data: 'myData.employees',
columnDefs: [{
field: 'firstName',
displayName: 'First Name'
}, {
field: 'lastName',
displayName: 'Last Name'
}, {
field: 'age',
displayName: 'Age'
}]
};
Full working snippet attached:
var app = angular.module('myApp', ['ngGrid', 'ngAnimate']);_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
_x000D_
$scope.myData = {_x000D_
employees: [{_x000D_
firstName: 'John',_x000D_
lastName: 'Doe',_x000D_
age: 30_x000D_
}, {_x000D_
firstName: 'Frank',_x000D_
lastName: 'Burns',_x000D_
age: 54_x000D_
}, {_x000D_
firstName: 'Sue',_x000D_
lastName: 'Banter',_x000D_
age: 21_x000D_
}]_x000D_
};_x000D_
_x000D_
$scope.gridOptions = {_x000D_
data: 'myData.employees',_x000D_
columnDefs: [{_x000D_
field: 'firstName',_x000D_
displayName: 'First Name'_x000D_
}, {_x000D_
field: 'lastName',_x000D_
displayName: 'Last Name'_x000D_
}, {_x000D_
field: 'age',_x000D_
displayName: 'Age'_x000D_
}]_x000D_
};_x000D_
});
_x000D_
/*style.css*/_x000D_
.gridStyle {_x000D_
border: 1px solid rgb(212,212,212);_x000D_
width: 400px;_x000D_
height: 200px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myApp">_x000D_
<head lang="en">_x000D_
<meta charset="utf-8">_x000D_
<title>Custom Plunker</title>_x000D_
<link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />_x000D_
<link rel="stylesheet" type="text/css" href="style.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular-animate.js"></script>_x000D_
<script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>_x000D_
<script type="text/javascript" src="main.js"></script>_x000D_
</head>_x000D_
<body ng-controller="MyCtrl">_x000D_
<div class="gridStyle" ng-grid="gridOptions"></div>_x000D_
</body>_x000D_
</html>
_x000D_
You can't without an iteration.
Option 1
Carnet findCarnet(String codeIsIn) {
for(Carnet carnet : listCarnet) {
if(carnet.getCodeIsIn().equals(codeIsIn)) {
return carnet;
}
}
return null;
}
Option 2
Override the equals()
method of Carnet
.
Option 3
Storing your List
as a Map
instead, using codeIsIn
as the key:
HashMap<String, Carnet> carnets = new HashMap<>();
// setting map
Carnet carnet = carnets.get(codeIsIn);
<html>
<div style="width:100%; height:100%; position:fixed; left:0;top:0;overflow:hidden;">
</div>
</html>
Given points (X1,Y1) and (X2,Y2) then:
dX = X1 - X2;
dY = Y1 - Y2;
if (dX*dX + dY*dY > (5*5))
{
//your code
}
Here is a way to do it while passing in an extra argument:
https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)
<div ng-repeat="group in groups">
<li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
<span>{{friend.name}}</span>
<li>
</div>
With the backend:
$scope.weDontLike = function(name) {
return function(friend) {
return friend.name != name;
}
}
.
And yet another way with an in-template filter only:
https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)
<div ng:app>
<div ng-controller="HelloCntl">
<ul>
<li ng-repeat="friend in friends | filter:{name:'!Adam'}">
<span>{{friend.name}}</span>
<span>{{friend.phone}}</span>
</li>
</ul>
</div>
You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.
How do I wrap this line of text
- asked by Peter 2 days ago
Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:
public function up()
{
// Create the table
Schema::create('users', function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('password', 64);
$table->boolean('verified');
$table->string('token', 255);
$table->timestamps();
});
// Insert some stuff
DB::table('users')->insert(
array(
'email' => '[email protected]',
'verified' => true
)
);
}
Continuing with Mecki's suggestion, this article pthread mutex vs pthread spinlock on Alexander Sandler's blog, Alex on Linux shows how the spinlock
& mutexes
can be implemented to test the behavior using #ifdef.
However, be sure to take the final call based on your observation, understanding as the example given is an isolated case, your project requirement, environment may be entirely different.
You can use DataSet.Tables(0).Columns.Contains(name)
to check whether the DataTable
contains a column with a particular name.
string myString = myInt.ToString();
You can find details here To Quickly Format XML using Pretty Print (libXML)
Installing the XML Tools
If you run Notepad++ and look in the Plugins menu, you’ll see that the XML Tools aren’t there:
Download the XML tools from here.
Unzip the file and copy the XMLTools.dll to the Notepad++ plugins folder (in the example above: C:\Program Files (x86)\Notepad++\plugins):
Re-start Notepad++ and you should now see the XMLTools appear in the Plugins menu.
Unzip the ext_libs.zip file and then copy the unzipped DLLs to the Notepad++ installation directory (in the example above: C:\Program Files (x86)\Notepad++).
Re-start Notepad++ and you should finally see the proper XML Tools menu.
The feature I use the most is “Pretty print (XML only – with line breaks)”. This will format any piece of XML with all the proper line spacing.
I have created the following, and it's working on my system. Please try this:
package.json:
{
"name": "test app",
"version": "1.0.0",
"scripts": {
"start": "node script1.js"
}
}
script1.js:
console.log('testing')
From your command line run the following command:
npm start
Additional use case
My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.
"scripts": {
"start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
}
@IBOutlet weak var constraintTxtV: NSLayoutConstraint!
func TextViewDynamicallyIncreaseSize() {
let contentSize = self.txtVDetails.sizeThatFits(self.txtVDetails.bounds.size)
let higntcons = contentSize.height
constraintTxtV.constant = higntcons
}
Very near to TheEye answer, but I change a little thing to make it work:
var num = 192.16;_x000D_
_x000D_
console.log( Math.ceil(num * 10) / 10 );
_x000D_
From phpMyAdmin and other sources you can use:
SET SESSION group_concat_max_len = 99999999;
SELECT GROUP_CONCAT(concat('OPTIMIZE TABLE `', table_name, '`;') SEPARATOR '') AS O
FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_TYPE = 'BASE TABLE'
AND table_name!='dual'
AND TABLE_SCHEMA = '<your databasename>'
Then you can copy & paste the result to a new query or execute it from your own source. If you don't see the whole statement:
The best example of an abstract class is GenericServlet
. GenericServlet
is the parent class of HttpServlet
. It is an abstract class.
When inheriting 'GenericServlet' in a custom servlet class, the service()
method must be overridden.
Your code is correct you just used .div
instead of div
HTML
<div class="ui grid container">
<div class="ui center aligned three column grid">
<div class="column">
</div>
<div class="column">
</div>
</div>
CSS
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}
Check out this Fiddle
or you can use a simple approach and just convert the string's case to substring's case and then use contains method.
It means that the method accepts a variable number of arguments ("varargs") of type JID
. Within the method, recipientJids
is presented.
This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.
It also enables idioms such as sprintf
from C; see String.format()
, for example.
Same as nautic20's answer, just simply use MVC default model binding checkbox list with same name as a collection property of string/int/enum in ViewModel. That is it.
But one issue need to point out. In each checkbox component, you should not put "Id" in it which will affect MVC model binding.
Following code will work for model binding:
<% foreach (var item in Model.SampleObjectList)
{ %>
<tr>
<td><input type="checkbox" name="SelectedObjectIds" value="<%= item.Id%>" /></td>
<td><%= Html.Encode(item.Name)%></td>
</tr>
<% } %>
Following codes will not binding to model (difference here is it assigned id for each checkbox)
<% foreach (var item in Model.SampleObjectList)
{ %>
<tr>
<td><input type="checkbox" name="SelectedObjectIds" id="[some unique key]" value="<%= item.Id%>" /></td>
<td><%= Html.Encode(item.Name)%></td>
</tr>
<% } %>
I've also find this fix that zooms to fit all markers
LatLngList: an array of instances of latLng, for example:
// "map" is an instance of GMap3
var LatLngList = [
new google.maps.LatLng (52.537,-2.061),
new google.maps.LatLng (52.564,-2.017)
],
latlngbounds = new google.maps.LatLngBounds();
LatLngList.forEach(function(latLng){
latlngbounds.extend(latLng);
});
// or with ES6:
// for( var latLng of LatLngList)
// latlngbounds.extend(latLng);
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
When selecting columns in R for a reduced data-set you can often end up with duplicates.
These two lines give the same result. Each outputs a unique data-set with two selected columns only:
distinct(mtcars, cyl, hp);
summarise(group_by(mtcars, cyl, hp));
Simple enough, the IMAP extension is not activated in your PHP installation. It is not enabled by default. If your local installation is running XAMPP on Windows, you have to enable it as described in the XAMPP FAQ:
Where is the IMAP support for PHP?
As default, the IMAP support for PHP is deactivated in XAMPP, because there were some mysterious initialization errors with some home versions like Windows 98. Who works with NT systems, can open the file
"\xampp\php\php.ini"
to active the php exstension by removing the beginning semicolon at the line";extension=php_imap.dll"
. Should be:extension=php_imap.dll
Now restart Apache and IMAP should work. You can use the same steps for every extension, which is not enabled in the default configuration.
If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.
For example:
$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master
Similarly you can clone as if this were a remote repo:
$ git clone ~/repos/myproject.git
Here is one possible solution with variation of binary tree. It adds a field called rightSubTreeSize to each tree node. Keep on inserting number into binary tree in the order they appear in the array. If number goes lhs of node the inversion count for that element would be (1 + rightSubTreeSize). Since all those elements are greater than current element and they would have appeared earlier in the array. If element goes to rhs of a node, just increase its rightSubTreeSize. Following is the code.
Node {
int data;
Node* left, *right;
int rightSubTreeSize;
Node(int data) {
rightSubTreeSize = 0;
}
};
Node* root = null;
int totCnt = 0;
for(i = 0; i < n; ++i) {
Node* p = new Node(a[i]);
if(root == null) {
root = p;
continue;
}
Node* q = root;
int curCnt = 0;
while(q) {
if(p->data <= q->data) {
curCnt += 1 + q->rightSubTreeSize;
if(q->left) {
q = q->left;
} else {
q->left = p;
break;
}
} else {
q->rightSubTreeSize++;
if(q->right) {
q = q->right;
} else {
q->right = p;
break;
}
}
}
totCnt += curCnt;
}
return totCnt;
In python3.7.7, the definition of json.load is as below according to cpython source code:
def load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
json.load actually calls json.loads and use fp.read()
as the first argument.
So if your code is:
with open (file) as fp:
s = fp.read()
json.loads(s)
It's the same to do this:
with open (file) as fp:
json.load(fp)
But if you need to specify the bytes reading from the file as like fp.read(10)
or the string/bytes you want to deserialize is not from file, you should use json.loads()
As for json.loads(), it not only deserialize string but also bytes. If s
is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.
def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
...
"""
if isinstance(s, str):
if s.startswith('\ufeff'):
raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
f'not {s.__class__.__name__}')
s = s.decode(detect_encoding(s), 'surrogatepass')
#pragma mark
is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.
In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.
#pragma mark
is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.
if I have a special tag at the end of my URL like: http://domain.com/?tag=12345 Here is the below code to remove that tag whenever it presents in the URL:
<script>
// Remove URL Tag Parameter from Address Bar
if (window.parent.location.href.match(/tag=/)){
if (typeof (history.pushState) != "undefined") {
var obj = { Title: document.title, Url: window.parent.location.pathname };
history.pushState(obj, obj.Title, obj.Url);
} else {
window.parent.location = window.parent.location.pathname;
}
}
</script>
This gives the idea to remove one or more (or all) parameters from URL
With window.location.pathname you basically get everything before '?' in the url.
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Try enclosing your date into a character string.
select *
from dbo.March2010 A
where A.Date >= '2010-04-01';
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue
annotation using IDENTITY.
@Entity
@Table(name = "client")
data class Client(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)
GL
You might find Perl or Python useful to get data from the serial port. To send data to the server, the solution could be easy if the server is (let's say) an HTTP application or even a popular database. The solution would be not so easy if it is some custom/proprietary TCP application.
$('html').keyup(function(e){
if(e.keyCode == 46) {
alert('Delete key released');
}
});
Source: javascript char codes key codes from www.cambiaresearch.com
Awesome answers above. I recently had a need to generate simulated data and this is what I landed up using. Sharing in-case helpful to others as well,
import logging
__name__ = "DataSimulator"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
import numpy as np
import pandas as pd
def generate_simulated_data(add_anomalies:bool=True, random_state:int=42):
rnd_state = np.random.RandomState(random_state)
time = np.linspace(0, 200, num=2000)
pure = 20*np.sin(time/(2*np.pi))
# concatenate on the second axis; this will allow us to mix different data
# distribution
data = np.c_[pure]
mu = np.mean(data)
sd = np.std(data)
logger.info(f"Data shape : {data.shape}. mu: {mu} with sd: {sd}")
data_df = pd.DataFrame(data, columns=['Value'])
data_df['Index'] = data_df.index.values
# Adding gaussian jitter
jitter = 0.3*rnd_state.normal(mu, sd, size=data_df.shape[0])
data_df['with_jitter'] = data_df['Value'] + jitter
index_further_away = None
if add_anomalies:
# As per the 68-95-99.7 rule(also known as the empirical rule) mu+-2*sd
# covers 95.4% of the dataset.
# Since, anomalies are considered to be rare and typically within the
# 5-10% of the data; this filtering
# technique might work
#for us(https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule)
indexes_furhter_away = np.where(np.abs(data_df['with_jitter']) > (mu +
2*sd))[0]
logger.info(f"Number of points further away :
{len(indexes_furhter_away)}. Indexes: {indexes_furhter_away}")
# Generate a point uniformly and embed it into the dataset
random = rnd_state.uniform(0, 5, 1)
data_df.loc[indexes_furhter_away, 'with_jitter'] +=
random*data_df.loc[indexes_furhter_away, 'with_jitter']
return data_df, indexes_furhter_away
I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.
Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.
Pragma Directives It includes "#pragma comment" in the table you'll see.
HTH
I suspect GCC, for example, has their own set of #pragma's.
With a React Native running in the emulator,
Press ctrl+m (for Linux, I suppose it's the same for Windows and ?+m for Mac OS X)
or run the following in terminal:
adb shell input keyevent 82
Arithmetical (as opposed to algorithmic) solution:
angle = Pi - abs(abs(a1 - a2) - Pi);
No need to add an extra variable to keep track of this. Just use the UIScrollView
's panGestureRecognizer
property like this. Unfortunately, this works only if the velocity isn't 0:
CGFloat yVelocity = [scrollView.panGestureRecognizer velocityInView:scrollView].y;
if (yVelocity < 0) {
NSLog(@"Up");
} else if (yVelocity > 0) {
NSLog(@"Down");
} else {
NSLog(@"Can't determine direction as velocity is 0");
}
You can use a combination of x and y components to detect up, down, left and right.
I wrote small function for myself that works recursively in Postgres 9.4. I had same problem (good they did solve some of this headache in Postgres 9.5). Anyway here is the function (I hope it works well for you):
CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
result JSONB;
v RECORD;
BEGIN
IF jsonb_typeof(val2) = 'null'
THEN
RETURN val1;
END IF;
result = val1;
FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP
IF jsonb_typeof(val2->v.key) = 'object'
THEN
result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
ELSE
result = result || jsonb_build_object(v.key, v.value);
END IF;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;
Here is sample use:
select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
jsonb_update
---------------------------------------------------------------------
{"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)
As you can see it analyze deep down and update/add values where needed.
Since you are using enumerate
hence your i
is actually the index of the key rather than the key itself.
So, you are getting 3
in the first column of the row 3 4
even though there is no key 3
.
enumerate
iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.
Hence, the columns here are the iteration number followed by the key in dictionary enum
Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine.
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
this works for me
There are two problems in your code:
visibility
and not visiblity
..style
property.It's easy to fix. Simple replace this:
document.getElementById("remember").visiblity
with this:
document.getElementById("remember").style.visibility
I got this from some forum. I hope it will be useful for you.
<script type="text/javascript">
function validateFileExtension(fld) {
if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
alert("Invalid image file type.");
fld.form.reset();
fld.focus();
return false;
}
return true;
} </script> </head>
<body> <form ...etc... onsubmit="return
validateFileExtension(this.fileField)"> <p> <input type="file"
name="fileField" onchange="return validateFileExtension(this)">
<input type="submit" value="Submit"> </p> </form> </body>
This is an old thread, but I stumbled across it when trying to solve a similar problem.
For me, I got this particular error relating to the php_wincache.dll
. I was in the process of updating PHP from 5.5.38 to 5.6.31 on a Windows server. For some reason, not all of the DLL files updated with the newest versions. Most did, but some didn't.
So, if you get an error similar to this, make sure all the extensions are in place and updated.
From w3schools.com: Made compatible with Firefox Sept, 2016
<input type="text" onfocusout="myFunction()">
I think this one is simple enough to use:
#!/bin/bash
#
readopt='getopts $opts opt;rc=$?;[ $rc$opt == 0? ]&&exit 1;[ $rc == 0 ]||{ shift $[OPTIND-1];false; }'
opts=vfdo:
# Enumerating options
while eval $readopt
do
echo OPT:$opt ${OPTARG+OPTARG:$OPTARG}
done
# Enumerating arguments
for arg
do
echo ARG:$arg
done
Invocation example:
./myscript -v -do /fizz/someOtherFile -f ./foo/bar/someFile
OPT:v
OPT:d
OPT:o OPTARG:/fizz/someOtherFile
OPT:f
ARG:./foo/bar/someFile
It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.
Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.
If you need it to have as a condition in an other event, I solved it this way:
$('.classname').hover(
function(){$(this).data('hover',true);},
function(){$(this).data('hover',false);}
);
Then in another event, you can easily use it:
if ($(this).data('hover')){
//...
}
(I see some using is(':hover')
to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)
h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:
http://docs.h5py.org/en/latest/quick.html
A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:
In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">
In [6]: h5f.close()
You can then load that data back in using: '
In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()
In [13]: np.allclose(a,b)
Out[13]: True
Definitely check out the docs:
Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save
, np.savez
etc:
This code:
$("#yourFileInput")[0].files[0].size;
Returns the file size for an form input.
On FF 3.6 and later this code should be:
$("#yourFileInput")[0].files[0].fileSize;
Mine were located here on Ubuntu 18.04 when I installed JavaFX using apt install openjfx
(as noted already by @jewelsea above)
/usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.
A simpler way is to use express-http-proxy
run npm run build
to create the bundle.
var proxy = require('express-http-proxy');
var app = require('express')();
//define the path of build
var staticFilesPath = path.resolve(__dirname, '..', 'build');
app.use(express.static(staticFilesPath));
app.use('/api/api-server', proxy('www.api-server.com'));
Use "/api/api-server" from react code to call the API.
So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)
A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
Your function worked for me after changing its declaration to this ...
Function processArr(Arr As Variant) As String
You could also consider a ParamArray
like this ...
Function processArr(ParamArray Arr() As Variant) As String
'Dim N As Variant
Dim N As Long
Dim finalStr As String
For N = LBound(Arr) To UBound(Arr)
finalStr = finalStr & Arr(N)
Next N
processArr = finalStr
End Function
And then call the function like this ...
processArr("foo", "bar")
For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.
Try something like
convert -density 300 image.eps -resize 1024x1024 image.jpg
Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.
The order of the arguments matters! The -density X
argument needs to go before image.eps
because you want to affect the resolution that the input file is rendered at.
This is not super obvious in the manpage for convert
, but is hinted at:
SYNOPSIS
convert [input-option] input-file [output-option] output-file
From the python documentation, here's the function you want:
def my_import(name):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
The reason a simple __import__
won't work is because any import of anything past the first dot in a package string is an attribute of the module you're importing. Thus, something like this won't work:
__import__('foo.bar.baz.qux')
You'd have to call the above function like so:
my_import('foo.bar.baz.qux')
Or in the case of your example:
klass = my_import('my_package.my_module.my_class')
some_object = klass()
EDIT: I was a bit off on this. What you're basically wanting to do is this:
from my_package.my_module import my_class
The above function is only necessary if you have a empty fromlist. Thus, the appropriate call would be like this:
mod = __import__('my_package.my_module', fromlist=['my_class'])
klass = getattr(mod, 'my_class')
Make sure you have project_id
in the fillable
property of your Comment
model.
I had the same issue, And this was the reason.
JIT-Just in time the word itself says when it's needed (on demand)
The source code is completely converted into machine code
The source code will be converted into assembly language like structure [for ex IL (intermediate language) for C#, ByteCode for java].
The intermediate code is converted into machine language only when the application needs that is required codes are only converted to machine code.
In JIT not all the code is converted into machine code first a part of the code that is necessary will be converted into machine code then if a method or functionality called is not in machine then that will be turned into machine code... it reduces burden on the CPU.
As the machine code will be generated on run time....the JIT compiler will produce machine code that is optimised for running machine's CPU architecture.
If you're looking for one that doesn't rely on Flash then dropzonejs is a good shout. It supports multiple files and drag and drop.
System variables usually require a restart to become effective. Does it still not work after a restart?
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.
If elem.find()
is not working for you, check that you are including JQuery script before angular script....
You can use the confirmed validation rule.
$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'required|confirmed|min:6',
]);
What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:
In my build.xml:
<target name="printclasspath">
<pathconvert property="classpathProp" refid="project.class.path"/>
<echo>${classpathProp}</echo>
</target>
In another script called 'run.sh':
export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \ -f 7):build
java "$@"
It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.
I think it's a shame there's not some option in ant whereby you could do something like:
ant -- arg1 arg2 arg3
mpirun uses this type of syntax; ssh also can use this syntax I think.
shamangeorge wrote:
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.
This is indeed what will happen, and pausing will also trigger the pause
event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src
as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay
is enabled - setting src
to null
is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
Overall I don't see anything that would break in your code.
Two suggestions:
The way you are combining Buffer
objects is a suboptimal because it has to copy all the pre-existing data on every 'data' event. It would be better to put the chunks in an array and concat
them all at the end.
var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
var buf = Buffer.concat(bufs);
}
For performance, I would look into if the S3 library you are using supports streams. Ideally you wouldn't need to create one large buffer at all, and instead just pass the stdout
stream directly to the S3 library.
As for the second part of your question, that isn't possible. When a function is called, it is allocated its own private context, and everything defined inside of that will only be accessible from other items defined inside that function.
Dumping the file to the filesystem would probably mean less memory usage per request, but file IO can be pretty slow so it might not be worth it. I'd say that you shouldn't optimize too much until you can profile and stress-test this function. If the garbage collector is doing its job you may be overoptimizing.
With all that said, there are better ways anyway, so don't use files. Since all you want is the length, you can calculate that without needing to append all of the buffers together, so then you don't need to allocate a new Buffer at all.
var pause_stream = require('pause-stream');
// Your other code.
var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
var contentLength = bufs.reduce(function(sum, buf){
return sum + buf.length;
}, 0);
// Create a stream that will emit your chunks when resumed.
var stream = pause_stream();
stream.pause();
while (bufs.length) stream.write(bufs.shift());
stream.end();
var headers = {
'Content-Length': contentLength,
// ...
};
s3.putStream(stream, ....);
You can use this code snippet:
var New1 = EmpList.OrderBy(z => z.Age).ToList();
where New1
is a List<Employee>
.
EmpList
is variable of a List<Employee>
.
z
is a variable of Employee
type.
I was facing the same problem and i solved this issue by changing the fireabseStorage version the same as the Firebase database version
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:17.0.0'
to
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
#pragma
is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.
The one I regularly use is #pragma pack(1)
where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.
Pity we don't have a #dogma
yet. That would be fun ;)
import random
q=2
o=1
list =[r'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','0','1','2','3','4','5','6','7','8','9','0']
while(q>o):
print("")
for i in range(1,128):
x=random.choice(list)
print(x,end="")
Here length of string can be changed in for loop i.e for i in range(1,length) It is simple algorithm which is easy to understand. it uses list so you can discard characters that you do not need.
By default WampServer is installed to port 80 which is already used by IIS. To set WampServer to use an open port, left click on the WampServer icon in the system tray and go to Apache > httpd.conf
Open the httpd.conf in Notepad. press ctrl+f and search for "Listen 80", change this line to "Listen 8080" (u can change this port as what you want), and then close and save the httpd.conf file.
Open a web browser and enter "[];, this will open the WampServer configuration page where you can configure Apache, MySQL, and PHP.
and some times this problem may occur because of skype also use 80 as default port hope this will help
Only change the line str1:=''; to str1:=' ';
I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in
ngOnInt(){
userForm = new FormGroup({
name: new FormControl(),
email: new FormControl(),
adresse: new FormGroup({
rue: new FormControl(),
ville: new FormControl(),
cp: new FormControl(),
})
});
)
The simple difference between document ready and page event in jQuery-mobile is that:
The document ready event is used for the whole HTML page,
$(document).ready(function(e) {
// Your code
});
When there is a page event, use for handling particular page event:
<div data-role="page" id="second">
<div data-role="header">
<h3>
Page header
</h3>
</div>
<div data-role="content">
Page content
</div> <!--content-->
<div data-role="footer">
Page footer
</div> <!--footer-->
</div><!--page-->
You can also use document for handling the pageinit event:
$(document).on('pageinit', "#mypage", function() {
});
In your code, your first wait for task to execute but you haven't started it so it waits indefinitely. Try this:
Task<Customer> task = GetCustomers();
task.RunSynchronously();
Edit:
You say that you get an exception. Please post more details, including stack trace.
Mono contains the following test case:
[Test]
public void ExecuteSynchronouslyTest ()
{
var val = 0;
Task t = new Task (() => { Thread.Sleep (100); val = 1; });
t.RunSynchronously ();
Assert.AreEqual (1, val);
}
Check if this works for you. If it does not, though very unlikely, you might have some odd build of Async CTP. If it does work, you might want to examine what exactly the compiler generates and how Task
instantiation is different from this sample.
Edit #2:
I checked with Reflector that the exception you described occurs when m_action
is null
. This is kinda odd, but I'm no expert on Async CTP. As I said, you should decompile your code and see how exactly Task
is being instantiated any how come its m_action
is null
.
socket.disconnect()
Only reboots the connection firing disconnect event on client side. But gets connected again.
socket.close()
Disconnect the connection from client. The client will keep trying to connect.
Let's assume you have a system where char
is eight bit and all the characters you're trying to count are encoded using a non-negative number. In this case, you can write:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
if ( count[i] != 0) {
printf("The %c. character has %d occurrences.\n", i, counts[i]);
}
}
Note that this will count all the characters in the string. If you are 100% absolutely positively sure that your string will have only letters (no numbers, no whitespace, no punctuation) inside, then 1. asking for "case insensitiveness" starts to make sense, 2. you can reduce the number of entries to the number of characters in the English alphabet (namely 26) and you can write something like this:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}
Definition in http.js from the @angular/http:
delete(url, options)
The request doesn't accept a body so it seem your only option is to but your data in the URI.
I found another topic with references to correspond RFC, among other things: How to pass data in the ajax DELETE request other than headers
You can use tandem of MemoryStream
and StreamReader
classes:
void Main()
{
string myString;
using (var stream = new MemoryStream())
{
Print(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
myString = reader.ReadToEnd();
}
}
}
Have you been trying to reference your custom MapFragment
class in the layout file?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapFragment"
android:name="com.nfc.demo.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
That should work. I am not sure why it's failing. You're quoting your variables properly. What happens if you use this script with double [[
]]
?
if [[ -d $PASSED ]]; then
echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
echo "$PASSED is a file"
else
echo "$PASSED is not valid"
exit 1
fi
Double square brackets is a bash extension to [ ]
. It doesn't require variables to be quoted, not even if they contain spaces.
Also worth trying: -e
to test if a path exists without testing what type of file it is.
This is just another example of how you can use Dropzone.js in an existing form.
dropzone.js :
init: function() {
this.on("success", function(file, responseText) {
//alert("HELLO ?" + responseText);
mylittlefix(responseText);
});
return noop;
},
Then, later in the file I put
function mylittlefix(responseText) {
$('#botofform').append('<input type="hidden" name="files[]" value="'+ responseText +'">');
}
This assumes you have a div with id #botofform
that way when uploading you can use the uploaded files' names.
Note: my upload script returned theuploadedfilename.jpeg dubblenote you also would need to make a cleanup script that checks the upload directory for files not in use and deletes them ..if in a front end non authenticated form :)
In version 3, they changed "export" to "unload". It still functions more or less the same.
You can setup _JAVA_OPTIONS
instead of JAVA_OPTS
. This should work without $_JAVA_OPTIONS
.
I prefer using the following method:
system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>
I had the same issue. I had a backup of my C:\xampp\mysql\data
folder. But integrating it with the newly installed xampp
had issues. So I located the C:\xampp\mysql\bin\my.ini
file and directed innodb_data_home_dir = "C:/xampp/mysql/data"
to my backed-up data folder and it worked flawlessly.
It can also be done as follows:
csv_files = s3.list_objects_v2(s3_bucket_path)
for obj in csv_files['Contents']:
key = obj['Key']
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
No one has mentioned -m
option for remote shutdown:
shutdown -r -f -m \\machinename
Also:
-r
parameter causes a reboot (which is usually what you want on a remote machine, since physically starting it might be difficult).-f
parameter option forces the reboot.You could add to a set
until you reach n
:
setOfNumbers = set()
while len(setOfNumbers) < n:
setOfNumbers.add(random.randint(numLow, numHigh))
Be careful of having a smaller range than will fit in n
. It will loop forever, unable to find new numbers to insert up to n
RMDIR or RD if you are using the classic Command Prompt (cmd.exe):
rd /s /q "path"
RMDIR [/S] [/Q] [drive:]path
RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
If you are using PowerShell you can use Remove-Item
(which is aliased to del
, erase
, rd
, ri
, rm
and rmdir
) and takes a -Recurse
argument that can be shorted to -r
rd -r "path"
Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.
NuGet- > Install-Package Newtonsoft.Json
This is how you can do it from DB2 client.
Open the Command Editor and Run the select Query in the Commands Tab.
Open the corresponding Query Results Tab
Then from Menu --> Selected --> Export
Setting its background image to none also works:
button {
background-image: none;
}
Change the onclick from
onclick="javascript:SubmitFrm()"
to
onclick="SubmitFrm()"
You can also press F1 to open the Command Palette
and then remove the >
via Backspace. Now you can search for files, too.
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
You can use inner divs to set the margin.
<div style="display: table-cell;">
<div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
<div style="margin:5px;background-color: green;">1</div>
</div>
Andy Buchanan, as far as sticking to C++ goes, I liked yours, but I have a few mods:
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
Used like
uint32_t value = boost::lexical_cast<HexTo<uint32_t> >("0x2a");
That way you don't need one impl per int type.
Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.
Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.
$('#summernote').summernote({
height: ($(window).height() - 300),
callbacks: {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
$.ajax({
url: 'Your url to deal with your image',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img>').attr('src', 'http://' + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
I am using a Mac. I had the same problem wherein .csv file was in the same folder where the python script was placed, however, Spyder still was unable to locate the file. I changed the file name from capital letters to all small letters and it worked.
You are using the pointer newFile
without allocating space for it.
struct stasher_file *newFile = malloc(sizeof(stasher_file));
Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
import subprocess
subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])
Inspired by writing this answer, I ended up later expanding and writing a blog post going over this in careful detail. I recommend checking that out if you want to develop a deeper understanding of how to think about this problem--I try to explain it piece by piece, and also give a JSperf comparison at the end, going over speed considerations.
That said, The tl;dr is this:
To accomplish what you're asking for (filtering and mapping within one function call), you would use Array.reduce()
.
However, the more readable and (less importantly) usually significantly faster2 approach is to just use filter and map chained together:
[1,2,3].filter(num => num > 2).map(num => num * 2)
What follows is a description of how Array.reduce()
works, and how it can be used to accomplish filter and map in one iteration. Again, if this is too condensed, I highly recommend seeing the blog post linked above, which is a much more friendly intro with clear examples and progression.
You give reduce an argument that is a (usually anonymous) function.
That anonymous function takes two parameters--one (like the anonymous functions passed in to map/filter/forEach) is the iteratee to be operated on. There is another argument for the anonymous function passed to reduce, however, that those functions do not accept, and that is the value that will be passed along between function calls, often referred to as the memo.
Note that while Array.filter() takes only one argument (a function), Array.reduce() also takes an important (though optional) second argument: an initial value for 'memo' that will be passed into that anonymous function as its first argument, and subsequently can be mutated and passed along between function calls. (If it is not supplied, then 'memo' in the first anonymous function call will by default be the first iteratee, and the 'iteratee' argument will actually be the second value in the array)
In our case, we'll pass in an empty array to start, and then choose whether to inject our iteratee into our array or not based on our function--this is the filtering process.
Finally, we'll return our 'array in progress' on each anonymous function call, and reduce will take that return value and pass it as an argument (called memo) to its next function call.
This allows filter and map to happen in one iteration, cutting down our number of required iterations in half--just doing twice as much work each iteration, though, so nothing is really saved other than function calls, which are not so expensive in javascript.
For a more complete explanation, refer to MDN docs (or to my post referenced at the beginning of this answer).
Basic example of a Reduce call:
let array = [1,2,3];
const initialMemo = [];
array = array.reduce((memo, iteratee) => {
// if condition is our filter
if (iteratee > 1) {
// what happens inside the filter is the map
memo.push(iteratee * 2);
}
// this return value will be passed in as the 'memo' argument
// to the next call of this function, and this function will have
// every element passed into it at some point.
return memo;
}, initialMemo)
console.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]
more succinct version:
[1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, [])
Notice that the first iteratee was not greater than one, and so was filtered. Also note the initialMemo, named just to make its existence clear and draw attention to it. Once again, it is passed in as 'memo' to the first anonymous function call, and then the returned value of the anonymous function is passed in as the 'memo' argument to the next function.
Another example of the classic use case for memo would be returning the smallest or largest number in an array. Example:
[7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val)
// ^this would return the largest number in the list.
An example of how to write your own reduce function (this often helps understanding functions like these, I find):
test_arr = [];
// we accept an anonymous function, and an optional 'initial memo' value.
test_arr.my_reducer = function(reduceFunc, initialMemo) {
// if we did not pass in a second argument, then our first memo value
// will be whatever is in index zero. (Otherwise, it will
// be that second argument.)
const initialMemoIsIndexZero = arguments.length < 2;
// here we use that logic to set the memo value accordingly.
let memo = initialMemoIsIndexZero ? this[0] : initialMemo;
// here we use that same boolean to decide whether the first
// value we pass in as iteratee is either the first or second
// element
const initialIteratee = initialMemoIsIndexZero ? 1 : 0;
for (var i = initialIteratee; i < this.length; i++) {
// memo is either the argument passed in above, or the
// first item in the list. initialIteratee is either the
// first item in the list, or the second item in the list.
memo = reduceFunc(memo, this[i]);
// or, more technically complete, give access to base array
// and index to the reducer as well:
// memo = reduceFunc(memo, this[i], i, this);
}
// after we've compressed the array into a single value,
// we return it.
return memo;
}
The real implementation allows access to things like the index, for example, but I hope this helps you get an uncomplicated feel for the gist of it.
Here's some options that keep the file self-contained without retastering the image:
div
tags<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
The only difference : synchronized blocks allows granular locking unlike synchronized method
Basically synchronized
block or methods have been used to write thread safe code by avoiding memory inconsistency errors.
This question is very old and many things have been changed during last 7 years. New programming constructs have been introduced for thread safety.
You can achieve thread safety by using advanced concurrency API instead of synchronied
blocks. This documentation page provides good programming constructs to achieve thread safety.
Lock Objects support locking idioms that simplify many concurrent applications.
Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.
ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Better replacement for synchronized is ReentrantLock, which uses Lock
API
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
Example with locks:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.
Refer to this related question too:
Complete instruction is as follow:
openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes
openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem
yum install -y ca-certificates
,
cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
,
update-ca-trust
,
update-ca-trust force-enable
Hope to be useful
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
You can tell ESLint to ignore specific files and directories by creating an .eslintignore
file in your project’s root directory:
.eslintignore
build/*.js
config/*.js
bower_components/foo/*.js
The ignore patterns behave according to the .gitignore
specification.
(Don't forget to restart your editor.)
Can you try using document.location.replace()
it is used to clear the last entry in the history and replace it with the address of a new url. replace()
removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.
<script type="text/javascript">
function Navigate(){
window.location.replace('your link');
return false;
}
</script>
HTML:
<button onclick="Navigate()">Replace document</button>
[EDITED] It's seems you earlier have redefined "list", using it as a variable name, like this:
list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)
And you'l get
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'set' object is not callable
You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.
After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.
They're different characters. \r
is carriage return, and \n
is line feed.
On "old" printers, \r
sent the print head back to the start of the line, and \n
advanced the paper by one line. Both were therefore necessary to start printing on the next line.
Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r
to move to the start of the line and overwrite the existing text.
More importantly, Unix tends to use \n
as a line separator; Windows tends to use \r\n
as a line separator and Macs (up to OS 9) used to use \r
as the line separator. (Mac OS X is Unix-y, so uses \n
instead; there may be some compatibility situations where \r
is used instead though.)
For more information, see the Wikipedia newline article.
EDIT: This is language-sensitive. In C# and Java, for example, \n
always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
$(document).ready(function() {
$('#main_search').val('hi');
});