You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color
. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()
). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main()
method creates an instance of the class it contains (sounds strange but since main()
is created with the class instead of with the instance, it can do this) and then calls an instance method (run()
).
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass();//Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.
For example, you could just "new up" an instance of your class in the static method, then call the non-static method.
But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.
You must make Foo::comparator
static or wrap it in a std::mem_fun
class object. This is because lower_bounds()
expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind
too.
Examples:
// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });
The Main
method is static inside the Program
class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits()
method static as well.
Get URL from URI and use getFile() if you are not ready to use substring way of extracting file.
This will be helpful for the right bottom rounded button
HTML :
<a class="fixedButton" href>
<div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
</a>
CSS:
.fixedButton{
position: fixed;
bottom: 0px;
right: 0px;
padding: 20px;
}
.roundedFixedBtn{
height: 60px;
line-height: 80px;
width: 60px;
font-size: 2em;
font-weight: bold;
border-radius: 50%;
background-color: #4CAF50;
color: white;
text-align: center;
cursor: pointer;
}
Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
Old question but I had to address MrFox's comment in the accepted answer. Rotating an image when the size changes cuts off the edges of the image. One solution is to redraw the original on a larger image, centered, where the larger image's dimensions compensate for the need of not clipping the edges. For example, I wanted to be able to design a game's tiles at a normal angle but re-draw them at a 45-degree angle for an isometric view.
Here are example images (yellow borders are to make it easier to see here).
The centered tile in a larger image:
The rotated image (where you rotate the larger image, not the original):
The code (based in part on this answer in another question):
private Bitmap RotateImage(Bitmap rotateMe, float angle)
{
//First, re-center the image in a larger image that has a margin/frame
//to compensate for the rotated image's increased size
var bmp = new Bitmap(rotateMe.Width + (rotateMe.Width / 2), rotateMe.Height + (rotateMe.Height / 2));
using (Graphics g = Graphics.FromImage(bmp))
g.DrawImageUnscaled(rotateMe, (rotateMe.Width / 4), (rotateMe.Height / 4), bmp.Width, bmp.Height);
bmp.Save("moved.png");
rotateMe = bmp;
//Now, actually rotate the image
Bitmap rotatedImage = new Bitmap(rotateMe.Width, rotateMe.Height);
using (Graphics g = Graphics.FromImage(rotatedImage))
{
g.TranslateTransform(rotateMe.Width / 2, rotateMe.Height / 2); //set the rotation point as the center into the matrix
g.RotateTransform(angle); //rotate
g.TranslateTransform(-rotateMe.Width / 2, -rotateMe.Height / 2); //restore rotation point into the matrix
g.DrawImage(rotateMe, new Point(0, 0)); //draw the image on the new bitmap
}
rotatedImage.Save("rotated.png");
return rotatedImage;
}
My app manage a lot of images and it died with a OutOfMemoryError. This helped me. In the Manifest.xml Add
<application
....
android:largeHeap="true">
Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.
cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
sudo nano idlemain.py
, enter password if required.os.chdir(os.path.expanduser('~/Documents'))
this line, I added sys.path.append("/Users/admin/Downloads....")
NOTE: replace contents of the quotes with the directory where python module to be addedI just had this problem. Turns out the XML file (not the contents) was not encoded in utf-8, but in ISO-8859-1. You can check this on a Mac with file -I xml_filename
.
I used Sublime to change the file encoding to utf-8, and lxml imported it no issues.
It is possible to play a local video file.
<input type="file" accept="video/*"/>
<video controls autoplay></video>
When a file is selected via the input
element:
input.files
FileListvideo.src
propertyLean back and watch :)
http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
(function localFileVideoPlayer() {_x000D_
'use strict'_x000D_
var URL = window.URL || window.webkitURL_x000D_
var displayMessage = function(message, isError) {_x000D_
var element = document.querySelector('#message')_x000D_
element.innerHTML = message_x000D_
element.className = isError ? 'error' : 'info'_x000D_
}_x000D_
var playSelectedFile = function(event) {_x000D_
var file = this.files[0]_x000D_
var type = file.type_x000D_
var videoNode = document.querySelector('video')_x000D_
var canPlay = videoNode.canPlayType(type)_x000D_
if (canPlay === '') canPlay = 'no'_x000D_
var message = 'Can play type "' + type + '": ' + canPlay_x000D_
var isError = canPlay === 'no'_x000D_
displayMessage(message, isError)_x000D_
_x000D_
if (isError) {_x000D_
return_x000D_
}_x000D_
_x000D_
var fileURL = URL.createObjectURL(file)_x000D_
videoNode.src = fileURL_x000D_
}_x000D_
var inputNode = document.querySelector('input')_x000D_
inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
background-color: red;_x000D_
color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
The simplest thing you can do is cherry picking a range. It does the same as the rebase --onto
but is easier for the eyes :)
git cherry-pick quickfix1..quickfix2
Sometimes the files are actually located at ~/
. These are the steps I took to starting Zsh as the default terminal on Visual Studio Code/Windows 10.
cd ~/
vim .bashrc
Paste the following...
if test -t 1; then
exec zsh
fi
Save/close Vim.
Restart the terminal
Building a HashMap of these objects based on the field value as a key could be worthwhile from the performance perspective, e.g. populate Maps once and find objects very efficiently
Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
You can use the following regex to get integer and floating values from a string:
re.findall(r'[\d\.\d]+', 'hello -34 42 +34.478m 88 cricket -44.3')
['34', '42', '34.478', '88', '44.3']
Thanks Rex
For your first array example use,
a = numpy.arange(5)
To initialize big_array, use
big_array = numpy.zeros((10,4))
This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.
Edit:
If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist)
. The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.
First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:
$("form")
.find("input")
.change(function(){
if ($("#hdnFormChanged").val() == "no")
{
$("#hdnFormChanged").val("yes");
}
});
When your button is clicked, you can check the state of your hidden input:
$("#Button").click(function(){
if($("#hdnFormChanged").val() == "yes")
{
// handler code here...
}
});
a = 0.000006;
b = 6;
c = a/b;
textbox.Text = c.ToString("0.000000");
As you requested:
textbox.Text = c.ToString("0.######");
This will only display out to the 6th decimal place if there are 6 decimals to display.
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
it.remove(); // avoids a ConcurrentModificationException
}
EDIT: So inside the while try this:
map.put(pairs.getKey(), pairs.getValue().add(number))
You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList
.
EDIT 2: Then put the following inside your while loop:
if(pairs.getKey().equals("mango"))
{
map.put(pairs.getKey(), pairs.getValue().add(18));
}
else if(!map.containsKey("mango"))
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango",ints);
}
EDIT 3:
By reading your requirements, I come to think you may not need a loop. You may want to only check if the map contains the key mango
, and if it does add 18
, else create a new entry in the map with key mango
and value 18
.
So all you may need is the following, without the loop:
if(map.containsKey("mango"))
{
map.put("mango", map.get("mango).add(18));
}
else
{
List<Integer> ints = new ArrayList<Integer>();
ints.add(18);
map.put("mango", ints);
}
The "selected" answer didn't work for me. I'm using rails 3.1 with CouchRest::Model (based on Active Model). The _changed?
methods don't return true for changed attributes in the after_update
hook, only in the before_update
hook. I was able to get it to work using the (new?) around_update
hook:
class SomeModel < ActiveRecord::Base
around_update :send_notification_after_change
def send_notification_after_change
should_send_it = self.published_changed? && self.published == true
yield
Notification.send(...) if should_send_it
end
end
As everyone else has said, there's no mapping within a dictionary from value to key.
I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.
The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) ||
secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
int x;
greek.TryGetBySecond("Beta", out x);
Console.WriteLine(x);
}
}
Rising to @Ankan-Zerob's challenge, this is my estimate of the maximum length which can be stored in each text type measured in words:
Type | Bytes | English words | Multi-byte words
-----------+---------------+---------------+-----------------
TINYTEXT | 255 | ±44 | ±23
TEXT | 65,535 | ±11,000 | ±5,900
MEDIUMTEXT | 16,777,215 | ±2,800,000 | ±1,500,000
LONGTEXT | 4,294,967,295 | ±740,000,000 | ±380,000,000
In English, 4.8 letters per word is probably a good average (eg norvig.com/mayzner.html), though word lengths will vary according to domain (e.g. spoken language vs. academic papers), so there's no point being too precise. English is mostly single-byte ASCII characters, with very occasional multi-byte characters, so close to one-byte-per-letter. An extra character has to be allowed for inter-word spaces, so I've rounded down from 5.8 bytes per word. Languages with lots of accents such as say Polish would store slightly fewer words, as would e.g. German with longer words.
Languages requiring multi-byte characters such as Greek, Arabic, Hebrew, Hindi, Thai, etc, etc typically require two bytes per character in UTF-8. Guessing wildly at 5 letters per word, I've rounded down from 11 bytes per word.
CJK scripts (Hanzi, Kanji, Hiragana, Katakana, etc) I know nothing of; I believe characters mostly require 3 bytes in UTF-8, and (with massive simplification) they might be considered to use around 2 characters per word, so they would be somewhere between the other two. (CJK scripts are likely to require less storage using UTF-16, depending).
This is of course ignoring storage overheads etc.
SOLUTION for: mongoengine + marshmallow
If you use mongoengine
and marshamallow
then this solution might be applicable for you.
Basically, I imported String
field from marshmallow, and I overwritten default Schema id
to be String
encoded.
from marshmallow import Schema
from marshmallow.fields import String
class FrontendUserSchema(Schema):
id = String()
class Meta:
fields = ("id", "email")
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
Using ajaxSetup is not correct, as is noted on its doc page. It only sets up defaults, and if some requests override them there will be a mess.
I am way late to the party, but just for future reference if someone is looking for a solution to the same problem, here is my go at it, inspired by and largely identical to the previous answers, but more complete
// Automatically cancel unfinished ajax requests
// when the user navigates elsewhere.
(function($) {
var xhrPool = [];
$(document).ajaxSend(function(e, jqXHR, options){
xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(e, jqXHR, options) {
xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
});
var abort = function() {
$.each(xhrPool, function(idx, jqXHR) {
jqXHR.abort();
});
};
var oldbeforeunload = window.onbeforeunload;
window.onbeforeunload = function() {
var r = oldbeforeunload ? oldbeforeunload() : undefined;
if (r == undefined) {
// only cancel requests if there is no prompt to stay on the page
// if there is a prompt, it will likely give the requests enough time to finish
abort();
}
return r;
}
})(jQuery);
Try to avoid formatting in your query. You should return your data in a raw format and let the receiving application (e.g. a reporting service or end user app) do the formatting, i.e. rounding and so on.
Formatting the data in the server makes it harder (or even impossible) for you to further process your data. You usually want export the table or do some aggregation as well, like sum, average etc. As the numbers arrive as strings (varchar), there is usually no easy way to further process them. Some report designers will even refuse to offer the option to aggregate these 'numbers'.
Also, the end user will see the country specific formatting of the server instead of his own PC.
Also, consider rounding problems. If you round the values in the server and then still do some calculations (supposing the client is able to revert the number-strings back to a number), you will end up getting wrong results.
I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.
<div id="main" class="container" role="main">
<div class="row">
<div class="span5 offset1">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
<div class="span6">
Image Here (TODO)
</div>
</div>
Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.
I think I know what you are doing wrong. If you are applying padding to the span6
like this:
<div class="span6" style="padding-left:5px;">
<h2>Welcome</h2>
<p>Hello and welcome to my website.</p>
</div>
It is wrong. What you have to do is add padding to the elements inside:
<div class="span6">
<h2 style="padding-left:5px;">Welcome</h2>
<p style="padding-left:5px;">Hello and welcome to my website.</p>
</div>
Also i got this error if i had the comment in tn top level of template among with the actual root element.
<!-- Just a commented out stuff -->
<div>test of {{value}}</div>
you can invoke it using window.function_name() or directly function_name()
dummy.xml(remember image size should be less)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list android:opacity="transparent">
<item android:width="60dp" android:gravity="left" android:start="20dp">
<bitmap android:src="@drawable/down_button_dummy_dummy" android:gravity="left"/>
</item>
</layer-list>
</item>
</selector>
layout file snippet be like
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardElevation="5dp"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@drawable/dummy">
</Spinner>
</android.support.v7.widget.CardView>
If you are using Python 2, the following will be the solution:
import io
for line in io.open("u.item", encoding="ISO-8859-1"):
# Do something
Because the encoding
parameter doesn't work with open()
, you will be getting the following error:
TypeError: 'encoding' is an invalid keyword argument for this function
you can get distance and time using google Map API Google Map API
just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's
void parseJSONForDurationAndKMS(String json) throws JSONException {
Log.d(TAG, "called parseJSONForDurationAndKMS");
JSONObject jsonObject = new JSONObject(json);
String distance;
String duration;
distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");
Log.d(TAG, "distance : " + distance);
Log.d(TAG, "duration : " + duration);
distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);
}
The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.
The formula is:
Where:
is the physical linear resolution
and:
is the logical linear resolution
Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.
The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of viewing angle, which is approximately of an inch at arm's length. Source: CSS Absolute Lengths
This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.
If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover
or explicitly set the background-size
to percentage values.
#element { background-image: url('lores.png'); }
@media only screen and (min-device-pixel-ratio: 2) {
#element { background-image: url('hires.png'); }
}
@media only screen and (min-device-pixel-ratio: 3) {
#element { background-image: url('superhires.png'); }
}
This way, each device type only loads the correct image resource. Also keep in mind that the px
unit in CSS always operates on logical pixels.
As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).
If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.
use enumerate:
>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
... print "%d: %s" % (index, val)
...
0: a
1: b
2: c
3: d
Try using something like this:
<link rel="image_src" href="http://yoursite.com/graphics/yourimage.jpg" /link>`
Seems to work just fine on Firefox as long as you use a full path to your image.
Trouble is it get vertically offset downward for some reason. Image is 200 x 200 as recommended somewhere I read.
With unqualified imported identifiers you need external search tools like grep to find out where identifiers are declared. This makes reasoning about program correctness harder.
Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.
Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ......
Several responses here hit upon the correct solution when you're facing the mind-numbingly obscure error of referencing the service from a class file: copy service config info into your app.config web.config of your console or windows app. None of those answers seem to show you what to copy though. Let's try and correct that.
Here's what I copied out of my class library's config file, into my console app's config file, in order to get around this crazy error for a service I write called "TranslationServiceOutbound".
You basically want everything inside the system.serviceModel section:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITranslationServiceOutbound" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://MyHostName/TranslationServiceOutbound/TranslationServiceOutbound.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITranslationServiceOutbound"
contract="TranslationService.ITranslationServiceOutbound" name="BasicHttpBinding_ITranslationServiceOutbound" />
</client>
Several notes:
Make sure you first get a list of all installed versions. I actually had the version I wanted to downgrade to already installed, but ended up uninstalling that as well. To see the list of all your versions do:
sudo gem list cocoapods
Then when you want to delete a version, specify that version.
sudo gem uninstall cocoapods -v 1.6.2
You could remove the version specifier -v 1.6.2
and that would delete all versions:
You may try all this and still see that the Cocoapods you expected is still installed. If that's the case then it might be because Cocoaposa is stored in a different directory.
sudo gem uninstall -n /usr/local/bin cocoapods -v 1.6.2
Then you will have to also install it in a different directory, otherwise you may get an error saying You don't have write permissions for the /usr/bin directory
sudo gem install -n /usr/local/bin cocoapods -v 1.6.1
To check which version is your default do:
pod --version
For more on the directory problem see here
Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true);
Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true
) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring
). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.
You are correctly calling listen()
but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write()
or response.end()
. First, you need to include fs=require('fs')
to get access to the filesystem. Then, you need to actually serve the file.
XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string
will be undefined
(or perhaps null
), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.
Here is a simple implementation that incorporates all of the above:
server.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
frontend (part of index.html):
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.
UPDATE: I have changed response.sendHeader()
to the new response.writeHead()
in the code above !!!
A function pointer is a variable that contains the address of a function. Since it is a pointer variable though with some restricted properties, you can use it pretty much like you would any other pointer variable in data structures.
The only exception I can think of is treating the function pointer as pointing to something other than a single value. Doing pointer arithmetic by incrementing or decrementing a function pointer or adding/subtracting an offset to a function pointer isn't really of any utility as a function pointer only points to a single thing, the entry point of a function.
The size of a function pointer variable, the number of bytes occupied by the variable, may vary depending on the underlying architecture, e.g. x32 or x64 or whatever.
The declaration for a function pointer variable needs to specify the same kind of information as a function declaration in order for the C compiler to do the kinds of checks that it normally does. If you don't specify a parameter list in the declaration/definition of the function pointer, the C compiler will not be able to check the use of parameters. There are cases when this lack of checking can be useful however just remember that a safety net has been removed.
Some examples:
int func (int a, char *pStr); // declares a function
int (*pFunc)(int a, char *pStr); // declares or defines a function pointer
int (*pFunc2) (); // declares or defines a function pointer, no parameter list specified.
int (*pFunc3) (void); // declares or defines a function pointer, no arguments.
The first two declararations are somewhat similar in that:
func
is a function that takes an int
and a char *
and returns an int
pFunc
is a function pointer to which is assigned the address of a function that takes an int
and a char *
and returns an int
So from the above we could have a source line in which the address of the function func()
is assigned to the function pointer variable pFunc
as in pFunc = func;
.
Notice the syntax used with a function pointer declaration/definition in which parenthesis are used to overcome the natural operator precedence rules.
int *pfunc(int a, char *pStr); // declares a function that returns int pointer
int (*pFunc)(int a, char *pStr); // declares a function pointer that returns an int
Several Different Usage Examples
Some examples of usage of a function pointer:
int (*pFunc) (int a, char *pStr); // declare a simple function pointer variable
int (*pFunc[55])(int a, char *pStr); // declare an array of 55 function pointers
int (**pFunc)(int a, char *pStr); // declare a pointer to a function pointer variable
struct { // declare a struct that contains a function pointer
int x22;
int (*pFunc)(int a, char *pStr);
} thing = {0, func}; // assign values to the struct variable
char * xF (int x, int (*p)(int a, char *pStr)); // declare a function that has a function pointer as an argument
char * (*pxF) (int x, int (*p)(int a, char *pStr)); // declare a function pointer that points to a function that has a function pointer as an argument
You can use variable length parameter lists in the definition of a function pointer.
int sum (int a, int b, ...);
int (*psum)(int a, int b, ...);
Or you can not specify a parameter list at all. This can be useful but it eliminates the opportunity for the C compiler to perform checks on the argument list provided.
int sum (); // nothing specified in the argument list so could be anything or nothing
int (*psum)();
int sum2(void); // void specified in the argument list so no parameters when calling this function
int (*psum2)(void);
C style Casts
You can use C style casts with function pointers. However be aware that a C compiler may be lax about checks or provide warnings rather than errors.
int sum (int a, char *b);
int (*psplsum) (int a, int b);
psplsum = sum; // generates a compiler warning
psplsum = (int (*)(int a, int b)) sum; // no compiler warning, cast to function pointer
psplsum = (int *(int a, int b)) sum; // compiler error of bad cast generated, parenthesis are required.
Compare Function Pointer to Equality
You can check that a function pointer is equal to a particular function address using an if
statement though I am not sure how useful that would be. Other comparison operators would seem to have even less utility.
static int func1(int a, int b) {
return a + b;
}
static int func2(int a, int b, char *c) {
return c[0] + a + b;
}
static int func3(int a, int b, char *x) {
return a + b;
}
static char *func4(int a, int b, char *c, int (*p)())
{
if (p == func1) {
p(a, b);
}
else if (p == func2) {
p(a, b, c); // warning C4047: '==': 'int (__cdecl *)()' differs in levels of indirection from 'char *(__cdecl *)(int,int,char *)'
} else if (p == func3) {
p(a, b, c);
}
return c;
}
An Array of Function Pointers
And if you want to have an array of function pointers each of the elements of which the argument list has differences then you can define a function pointer with the argument list unspecified (not void
which means no arguments but just unspecified) something like the following though you may see warnings from the C compiler. This also works for a function pointer parameter to a function:
int(*p[])() = { // an array of function pointers
func1, func2, func3
};
int(**pp)(); // a pointer to a function pointer
p[0](a, b);
p[1](a, b, 0);
p[2](a, b); // oops, left off the last argument but it compiles anyway.
func4(a, b, 0, func1);
func4(a, b, 0, func2); // warning C4047: 'function': 'int (__cdecl *)()' differs in levels of indirection from 'char *(__cdecl *)(int,int,char *)'
func4(a, b, 0, func3);
// iterate over the array elements using an array index
for (i = 0; i < sizeof(p) / sizeof(p[0]); i++) {
func4(a, b, 0, p[i]);
}
// iterate over the array elements using a pointer
for (pp = p; pp < p + sizeof(p)/sizeof(p[0]); pp++) {
(*pp)(a, b, 0); // pointer to a function pointer so must dereference it.
func4(a, b, 0, *pp); // pointer to a function pointer so must dereference it.
}
C style namespace
Using Global struct
with Function Pointers
You can use the static
keyword to specify a function whose name is file scope and then assign this to a global variable as a way of providing something similar to the namespace
functionality of C++.
In a header file define a struct that will be our namespace along with a global variable that uses it.
typedef struct {
int (*func1) (int a, int b); // pointer to function that returns an int
char *(*func2) (int a, int b, char *c); // pointer to function that returns a pointer
} FuncThings;
extern const FuncThings FuncThingsGlobal;
Then in the C source file:
#include "header.h"
// the function names used with these static functions do not need to be the
// same as the struct member names. It's just helpful if they are when trying
// to search for them.
// the static keyword ensures these names are file scope only and not visible
// outside of the file.
static int func1 (int a, int b)
{
return a + b;
}
static char *func2 (int a, int b, char *c)
{
c[0] = a % 100; c[1] = b % 50;
return c;
}
const FuncThings FuncThingsGlobal = {func1, func2};
This would then be used by specifying the complete name of global struct variable and member name to access the function. The const
modifier is used on the global so that it can not be changed by accident.
int abcd = FuncThingsGlobal.func1 (a, b);
Application Areas of Function Pointers
A DLL library component could do something similar to the C style namespace
approach in which a particular library interface is requested from a factory method in a library interface which supports the creation of a struct
containing function pointers.. This library interface loads the requested DLL version, creates a struct with the necessary function pointers, and then returns the struct to the requesting caller for use.
typedef struct {
HMODULE hModule;
int (*Func1)();
int (*Func2)();
int(*Func3)(int a, int b);
} LibraryFuncStruct;
int LoadLibraryFunc LPCTSTR dllFileName, LibraryFuncStruct *pStruct)
{
int retStatus = 0; // default is an error detected
pStruct->hModule = LoadLibrary (dllFileName);
if (pStruct->hModule) {
pStruct->Func1 = (int (*)()) GetProcAddress (pStruct->hModule, "Func1");
pStruct->Func2 = (int (*)()) GetProcAddress (pStruct->hModule, "Func2");
pStruct->Func3 = (int (*)(int a, int b)) GetProcAddress(pStruct->hModule, "Func3");
retStatus = 1;
}
return retStatus;
}
void FreeLibraryFunc (LibraryFuncStruct *pStruct)
{
if (pStruct->hModule) FreeLibrary (pStruct->hModule);
pStruct->hModule = 0;
}
and this could be used as in:
LibraryFuncStruct myLib = {0};
LoadLibraryFunc (L"library.dll", &myLib);
// ....
myLib.Func1();
// ....
FreeLibraryFunc (&myLib);
The same approach can be used to define an abstract hardware layer for code that uses a particular model of the underlying hardware. Function pointers are filled in with hardware specific functions by a factory to provide the hardware specific functionality that implements functions specified in the abstract hardware model. This can be used to provide an abstract hardware layer used by software which calls a factory function in order to get the specific hardware function interface then uses the function pointers provided to perform actions for the underlying hardware without needing to know implementation details about the specific target.
Function Pointers to create Delegates, Handlers, and Callbacks
You can use function pointers as a way to delegate some task or functionality. The classic example in C is the comparison delegate function pointer used with the Standard C library functions qsort()
and bsearch()
to provide the collation order for sorting a list of items or performing a binary search over a sorted list of items. The comparison function delegate specifies the collation algorithm used in the sort or the binary search.
Another use is similar to applying an algorithm to a C++ Standard Template Library container.
void * ApplyAlgorithm (void *pArray, size_t sizeItem, size_t nItems, int (*p)(void *)) {
unsigned char *pList = pArray;
unsigned char *pListEnd = pList + nItems * sizeItem;
for ( ; pList < pListEnd; pList += sizeItem) {
p (pList);
}
return pArray;
}
int pIncrement(int *pI) {
(*pI)++;
return 1;
}
void * ApplyFold(void *pArray, size_t sizeItem, size_t nItems, void * pResult, int(*p)(void *, void *)) {
unsigned char *pList = pArray;
unsigned char *pListEnd = pList + nItems * sizeItem;
for (; pList < pListEnd; pList += sizeItem) {
p(pList, pResult);
}
return pArray;
}
int pSummation(int *pI, int *pSum) {
(*pSum) += *pI;
return 1;
}
// source code and then lets use our function.
int intList[30] = { 0 }, iSum = 0;
ApplyAlgorithm(intList, sizeof(int), sizeof(intList) / sizeof(intList[0]), pIncrement);
ApplyFold(intList, sizeof(int), sizeof(intList) / sizeof(intList[0]), &iSum, pSummation);
Another example is with GUI source code in which a handler for a particular event is registered by providing a function pointer which is actually called when the event happens. The Microsoft MFC framework with its message maps uses something similar to handle Windows messages that are delivered to a window or thread.
Asynchronous functions that require a callback are similar to an event handler. The user of the asynchronous function calls the asynchronous function to start some action and provides a function pointer which the asynchronous function will call once the action is complete. In this case the event is the asynchronous function completing its task.
My solution on Windows 10 was just to stop IIS (Internet Information Services).
You are looking for --build-arg
and the ARG
instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg
to the Dockerfile
and then build with docker build --build-arg arg=2.3 .
.
In your case (creating a list) there is no difference in practice. But generally it is better to use setUp(), because that will help Junit to report Exceptions correctly. If an exception occurs in constructor/initializer of a Test, that is a test failure. However, if an exception occurs during setup, it is natural to think of it as some issue in setting up the test, and junit reports it appropriately.
Someone might find this useful, I had a problem flattening array at some dimension, I would call it last dimension so for example, if I have array like:
array (
'germany' =>
array (
'cars' =>
array (
'bmw' =>
array (
0 => 'm4',
1 => 'x3',
2 => 'x8',
),
),
),
'france' =>
array (
'cars' =>
array (
'peugeot' =>
array (
0 => '206',
1 => '3008',
2 => '5008',
),
),
),
)
Or:
array (
'earth' =>
array (
'germany' =>
array (
'cars' =>
array (
'bmw' =>
array (
0 => 'm4',
1 => 'x3',
2 => 'x8',
),
),
),
),
'mars' =>
array (
'france' =>
array (
'cars' =>
array (
'peugeot' =>
array (
0 => '206',
1 => '3008',
2 => '5008',
),
),
),
),
)
For both of these arrays when I call method below I get result:
array (
0 =>
array (
0 => 'm4',
1 => 'x3',
2 => 'x8',
),
1 =>
array (
0 => '206',
1 => '3008',
2 => '5008',
),
)
So I am flattening to last array dimension which should stay the same, method below could be refactored to actually stop at any kind of level:
function flattenAggregatedArray($aggregatedArray) {
$final = $lvls = [];
$counter = 1;
$lvls[$counter] = $aggregatedArray;
$elem = current($aggregatedArray);
while ($elem){
while(is_array($elem)){
$counter++;
$lvls[$counter] = $elem;
$elem = current($elem);
}
$final[] = $lvls[$counter];
$elem = next($lvls[--$counter]);
while ( $elem == null){
if (isset($lvls[$counter-1])){
$elem = next($lvls[--$counter]);
}
else{
return $final;
}
}
}
}
You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :
$content = $_POST['content'];
$lines = explode(PHP_EOL, $content);
$results = '';
foreach($lines as $line)
{
$items = explode(' ', $line);
$q = str_replace("^", "^/", $items[1]);
if (substr($q, strlen($q) - 1) !== '$') $q .= '$';
$buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';
$results .= $buffer.PHP_EOL;
}
die($results);
In short:
Source: code.
You can also use 2D transform. It is illustrated in the snippet below with a list being scaled by 25%.
Nota: Bootstrap is used here for the sole purpose of layouting the demo (before/after effect).
ul#before {_x000D_
}_x000D_
_x000D_
ul#after {_x000D_
transform: scale(1.25);_x000D_
}_x000D_
_x000D_
div.container, div.row {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
border: 6px solid #000000;_x000D_
}
_x000D_
<!-- Bootstrap CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<!-- Bootstrap theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">_x000D_
_x000D_
<!-- HTML -->_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-5">_x000D_
Before_x000D_
</div>_x000D_
<div class="col-xs-5 col-xs-offset-1">_x000D_
After (scale 25%)_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-xs-5">_x000D_
<ul id="before">_x000D_
<li>Lorem ipsum dolor sit amet...</li>_x000D_
<li>In vel ante vel est accumsan...</li>_x000D_
<li>In elementum libero vel...</li>_x000D_
<li>Nam ut ante a sem mattis...</li>_x000D_
<li>Curabitur fermentum nisl...</li>_x000D_
<li>Praesent vel risus ultrices...</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="col-xs-5 col-xs-offset-1">_x000D_
<ul id="after">_x000D_
<li>Lorem ipsum dolor sit amet...</li>_x000D_
<li>In vel ante vel est accumsan...</li>_x000D_
<li>In elementum libero vel...</li>_x000D_
<li>Nam ut ante a sem mattis...</li>_x000D_
<li>Curabitur fermentum nisl...</li>_x000D_
<li>Praesent vel risus ultrices...</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- JQuery -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- Bootstrap JS -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
_x000D_
Reference:
Using simply tr :
$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5
If you really need sed :
$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5
If you want to check if a variable (say v) has been defined and is not null:
if (typeof v !== 'undefined' && v !== null) {
// Do some operation
}
If you want to check for all falsy values such as: undefined
, null
, ''
, 0
, false
:
if (v) {
// Do some operation
}
I installed it successfully by
pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl
Download java jdk<version>-linux-x64.tar.gz
file from https://www.oracle.com/technetwork/java/javase/downloads/index.html.
Extract this file where you want. like: /home/java
(Folder name created by user in home directory).
Now open terminal.
Set path JAVA_HOME=path
of your jdk folder(open jdk folder then right click on any folder, go to properties then copy the path using select all)
and paste here.
Like: JAVA_HOME=/home/xxxx/java/JDK1.8.0_201
Let Ubuntu know where our JDK/JRE is located.
sudo update-alternatives --install /usr/bin/java java /home/xxxx/java/jdk1.8.0_201/bin/java 20000
sudo update-alternatives --install /usr/bin/javac javac /home/xxxx/java/jdk1.8.0_201/bin/javac 20000
sudo update-alternatives --install /usr/bin/javaws javaws /home/xxxx/java/jdk1.8.0_201/bin/javaws 20000
Tell Ubuntu that our installation i.e., jdk1.8.0_05 must be the default Java.
sudo update-alternatives --set java /home/xxxx/sipTest/jdk1.8.0_201/bin/java
sudo update-alternatives --set javac /home/xxxx/java/sipTest/jdk1.8.0_201/bin/javac
sudo update-alternatives --set javaws /home/xxxxx/sipTest/jdk1.8.0_201/bin/javaws
Now try:
$ sudo update-alternatives --config java
There are 3 choices for the alternative java (providing /usr/bin/java
).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/lib/jvm/java-6-oracle1/bin/java 1047 auto mode
1 /usr/bin/gij-4.6 1046 manual mode
2 /usr/lib/jvm/java-6-oracle1/bin/java 1047 manual mode
3 /usr/lib/jvm/jdk1.7.0_75/bin/java 1 manual mode
Press enter to keep the current choice [*
], or type selection number: 3
update-alternatives: using /usr/lib/jvm/jdk1.7.0_75/bin/java to provide /usr/bin/java (java) in manual mode
Repeat the above for:
sudo update-alternatives --config javac
sudo update-alternatives --config javaws
<UserControl.Resources>
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</Style.Resources>
</Style>
</UserControl.Resources>
and
<ListBox ItemsSource="{Binding Path=FirstNames}"
ItemContainerStyle="{StaticResource myLBStyle}">
You just override the style of the listboxitem (see the: TargetType is ListBoxItem)
I have found this to be really useful:
df = pd.DataFrame({'A' : range(0,10) * 2, 'B' : np.random.randint(20,30,20)})
# A ascending, B descending
df.sort(**skw(columns=['A','-B']))
# A descending, B ascending
df.sort(**skw(columns=['-A','+B']))
Note that unlike the standard columns=,ascending=
arguments, here column names and their sort order are in the same place. As a result your code gets a lot easier to read and maintain.
Note the actual call to .sort
is unchanged, skw
(sortkwargs) is just a small helper function that parses the columns and returns the usual columns=
and ascending=
parameters for you. Pass it any other sort kwargs as you usually would. Copy/paste the following code into e.g. your local utils.py
then forget about it and just use it as above.
# utils.py (or anywhere else convenient to import)
def skw(columns=None, **kwargs):
""" get sort kwargs by parsing sort order given in column name """
# set default order as ascending (+)
sort_cols = ['+' + col if col[0] != '-' else col for col in columns]
# get sort kwargs
columns, ascending = zip(*[(col.replace('+', '').replace('-', ''),
False if col[0] == '-' else True)
for col in sort_cols])
kwargs.update(dict(columns=list(columns), ascending=ascending))
return kwargs
If you want the column names only, you can do:
List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
DataTable dt = reader.GetSchemaTable();
foreach (DataRow row in dt.Rows)
{
columns.Add(row.Field<String>("ColumnName"));
}
}
But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.
public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
// Add the parameters for the SelectCommand.
if (queryParams != null)
foreach (var param in queryParams)
cmd.Parameters.AddWithValue(param.Key, param.Value);
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(reader);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
}
}
}
}
conn.Close();
}
}
catch (Exception ex)
{
throw ex;
}
return CaseInsensitiveDictionary;
}
Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest:
Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.
I don't think the Chrome Developer tools pretty print XHR content. See: Viewing HTML response from Ajax call through Chrome Developer tools?
Let's make things simple, you don't need to read the document about a "custom tag" (as a 16 years web developer, I have enough this kind of tags, such as in struts, webwork, jsp, rails and now it's vuejs)
just press F12, and you will see the source code like:
<div>
<a href="#/topologies" class="luelue">page1</a>
<a href="#/" aria-current="page" class="router-link-exact-active router-link-active">page2</a>
<a href="#/databases" class="">page3</a>
</div>
so just add styles for the .router-link-active
or router-link-exact-active
if you want more details, check the router-link
api:
What about:
while range(some_number):
#do something
For SQL server 2012,
First, log in to the SQL server as an administrator and go to Security tab
Then move into Server Roles and double click on sysadmin role
Now add user which you want to give permission to create Database by clicking Add button
Click OK button and now run the query
Hope this will help for someone
When a process needs to fetch data from a disk, it effectively stops running on the CPU to let other processes run because the operation might take a long time to complete – at least 5ms seek time for a disk is common, and 5ms is 10 million CPU cycles, an eternity from the point of view of the program!
From the programmer point of view (also said "in userspace"), this is called a blocking system call. If you call write(2)
(which is a thin libc wrapper around the system call of the same name), your process does not exactly stop at that boundary; it continues, in the kernel, running the system call code. Most of the time it goes all the way up to a specific disk controller driver (filename ? filesystem/VFS ? block device ? device driver), where a command to fetch a block on disk is submitted to the proper hardware, which is a very fast operation most of the time.
THEN the process is put in sleep state (in kernel space, blocking is called sleeping – nothing is ever 'blocked' from the kernel point of view). It will be awakened once the hardware has finally fetched the proper data, then the process will be marked as runnable and will be scheduled. Eventually, the scheduler will run the process.
Finally, in userspace, the blocking system call returns with proper status and data, and the program flow goes on.
It is possible to invoke most I/O system calls in non-blocking mode (see O_NONBLOCK
in open(2)
and fcntl(2)
). In this case, the system calls return immediately and only report submitting the disk operation. The programmer will have to explicitly check at a later time whether the operation completed, successfully or not, and fetch its result (e.g., with select(2)
). This is called asynchronous or event-based programming.
Most answers here mentioning the D state (which is called TASK_UNINTERRUPTIBLE
in the Linux state names) are incorrect. The D state is a special sleep mode which is only triggered in a kernel space code path, when that code path can't be interrupted (because it would be too complex to program), with the expectation that it would block only for a very short time. I believe that most "D states" are actually invisible; they are very short lived and can't be observed by sampling tools such as 'top'.
You can encounter unkillable processes in the D state in a few situations. NFS is famous for that, and I've encountered it many times. I think there's a semantic clash between some VFS code paths, which assume to always reach local disks and fast error detection (on SATA, an error timeout would be around a few 100 ms), and NFS, which actually fetches data from the network which is more resilient and has slow recovery (a TCP timeout of 300 seconds is common). Read this article for the cool solution introduced in Linux 2.6.25 with the TASK_KILLABLE
state. Before this era there was a hack where you could actually send signals to NFS process clients by sending a SIGKILL to the kernel thread rpciod
, but forget about that ugly trick.…
First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.
Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.
There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":
REPLACE(CAST(height as varchar(31)),'.00','')
EDIT:
This script works:
DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');
It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.
However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:
http://api.jquery.com/jQuery.post/
And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!
File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload
In my case I'd simply forgotten I had a binding set up for (in my case) https://localhost:44300 in full IIS. You can't have both!
.transbg{/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";}
There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example
<code>
<?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
<?php echo $output; ?>
</div>
<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>
<script>
if(window.attachEvent) {
window.attachEvent('onload', iframeResizer);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
iframeResizer(evt);
};
window.onload = newonload;
} else {
window.onload = iframeResizer;
}
}
function iframeResizer(){
var result = document.getElementById("iframediv").offsetHeight;
document.getElementById("iframe").style.height = result;
document.getElementById("iframediv").style.display = 'none';
document.getElementById("iframe").style.display = 'inline';
}
</script>
</code>
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
//start the program
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'datapullman',
password: 'system',
server: 'localhost',
database: 'chat6'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * From emp", function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
//create a table as emp in a database (i have created as chat6)
// programs ends here
//save it as app.js and run as node app.js //open in you browser as localhost:5000
The problem is with the following CSS line on .nav_button
:
margin: 0 auto;
That would only work if you had one button, that's why they're off-centered when there are more than one nav_button
divs.
If you want all your buttons centered nest the nav_buttons
in another div:
<div class="nav">
<div class="centerButtons">
<div class="nav_button">
<div class="b_left"></div>
<div class="b_middle">Home</div>
<div class="b_right"></div>
</div>
<div class="nav_button">
<div class="b_left"></div>
<div class="b_middle">Contact Us</div>
<div class="b_right"></div>
</div>
</div>
</div>
And style it this way:
.nav{
margin-top:167px;
width:1024px;
height:34px;
}
/* Centers the div that nests the nav_buttons */
.centerButtons {
margin: 0 auto;
float: left;
}
.nav_button{
height:34px;
margin-right:10px;
float: left;
}
Maybe you can use jQuery selectbox replacement. It's a jQuery plugin.
The simplest use of bind()
is to make a function that, no matter
how it is called, is called with a particular this
value.
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
Please refer this link for more information
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
With credits to the previous answer by @Bronek and @Shimmy:
This is like I have done the same thing in ASP.NET Core:
<input asp-for="DisabledField" disabled="disabled" />
<input asp-for="DisabledField" class="hidden" />
The first input is readonly and the second one passes the value to the controller and is hidden. I hope it will be useful for someone working with ASP.NET Core.
varbinary(max)
is the way to go (introduced in SQL Server 2005)
Just search for the string in plain old indexOf
arr.forEach(function(a){
if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
console.log(a);
}
});
You need to specify an offset to addr2line, not a virtual address (VA). Presumably if you had address space randomization turned off, you could use a full VA, but in most modern OSes, address spaces are randomized for a new process.
Given the VA 0x4005BDC
by valgrind, find the base address of your process or library in memory. Do this by examining the /proc/<PID>/maps
file while your program is running. The line of interest is the text
segment of your process, which is identifiable by the permissions r-xp
and the name of your program or library.
Let's say that the base VA is 0x0x4005000
. Then you would find the difference between the valgrind supplied VA and the base VA: 0xbdc
. Then, supply that to add2line:
addr2line -e a.out -j .text 0xbdc
And see if that gets you your line number.
You're missing semi-colons after your javascript lines. Also, window.location
should have .href
or .replace
etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
You can add a function to String Object
//Add this wherever you like in your javascript code
String.prototype.isEmail = function() {
return !!this.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
}
var user_email = "[email protected]";
if(user_email.isEmail()) {
//Email is valid !
} else {
//Email is invalid !
}
Its a very old thread, but I don't see that the solution is here or the this thread is marked as solved. I have also stuck into the same problem I solved it like this
$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path))
{
File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}
The key is that you need to remove '..' from the delete method. Keep in mind that this goes true if you are using Storage as well, whether you are using Storage of File don't for get to use them like
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use File; // For File
use Storage; // For Storage
Hope that it will help someone.
In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]
List<personClass> Getperson(string id);
MEMORY USAGE key
command gives you the number of bytes that a key and its value require to be stored in RAM.
The reported usage is the total of memory allocations for data and administrative overheads that a key its value require (source redis documentation)
Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.
If so, please update bootstrap, worked for me.
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
In my case I had uncoment the ;extension=php_curl.so in php.ini, but Ubuntu was already calling this extension somewhere else.
To find this "somewhere else", on php.ini will informe. On my case: /etc/php/7.1/apache2/conf.d/20-curl.ini was the path.
So now we edit this file (terminal):
sudo nano /etc/php/7.1/apache2/conf.d/20-curl.ini
Comment the ;extension=php_curl.so
Save file and restart apache:
sudo systemctl restart apache2
First, you need to understand the rules for upgrading the versioning number. You can read more about the semantic version here.
Each version will have x.y.z version where it defines for different purpose as shown below.
To run the scripts, you can define it in your package.json.
"script": {
"buildmajor": "npm version major && ng build --prod",
"buildminor": "npm version minor && ng build --prod",
"buildpatch": "npm version patch && ng build --prod"
}
In your terminal, you just need to npm run accordingly to your needs like
npm run buildpatch
If run it in git repo, the default git-tag-version is true and if you do not wish to do so, you can add below command into your scripts:
--no-git-tag-version
for eg: "npm --no-git-tag-version version major && ng build --prod"
Well, the code that renders the button enabled/disabled:
if(name.getText().equals("")) {
loginbt.setEnabled(false);
}else {
loginbt.setEnabled(true);
}
must be written in javax.swing.event.ChangeListener
and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?
Tail the log as a background job (&) and it will interleave with rspec output.
tail -f log/test.log &
bundle exec rspec
foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
NASA has a paper on radiation-hardened software. It describes three main tasks:
Note that the memory scan rate should be frequent enough that multi-bit errors rarely occur, as most ECC memory can recover from single-bit errors, not multi-bit errors.
Robust error recovery includes control flow transfer (typically restarting a process at a point before the error), resource release, and data restoration.
Their main recommendation for data restoration is to avoid the need for it, through having intermediate data be treated as temporary, so that restarting before the error also rolls back the data to a reliable state. This sounds similar to the concept of "transactions" in databases.
They discuss techniques particularly suitable for object-oriented languages such as C++. For example
And, it just so happens, NASA has used C++ for major projects such as the Mars Rover.
C++ class abstraction and encapsulation enabled rapid development and testing among multiple projects and developers.
They avoided certain C++ features that could create problems:
new
and delete
)new
to avoid the possibility of system heap corruption).Loop through the second array each time you iterate over an element in the first array, then check for matches.
var array1 = ["cat", "sum", "fun", "run"],
array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];
function getMatch(a, b) {
var matches = [];
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
if ( a[i] === b[e] ) matches.push( a[i] );
}
}
return matches;
}
getMatch(array1, array2); // ["cat"]
This approach from Microsoft works very well and provides the option to compare one list to another and switch them to get the difference in each. If you are comparing classes simply add your objects to two separate lists and then run the comparison.
Regular expressions are quite complex to manage due to the fact that some characters are reserved: for example, "foo.bar".replaceAll(".")
produces an empty string, because the dot means "anything" If you want to replace only the point should be indicated as a parameter "\\."
.
A simpler solution is to use StringBuilder objects to search and replace text. It takes two: one that contains the text in lowercase version while the second contains the original version. The search is performed on the lowercase contents and the index detected will also replace the original text.
public class LowerCaseReplace
{
public static String replace(String source, String target, String replacement)
{
StringBuilder sbSource = new StringBuilder(source);
StringBuilder sbSourceLower = new StringBuilder(source.toLowerCase());
String searchString = target.toLowerCase();
int idx = 0;
while((idx = sbSourceLower.indexOf(searchString, idx)) != -1) {
sbSource.replace(idx, idx + searchString.length(), replacement);
sbSourceLower.replace(idx, idx + searchString.length(), replacement);
idx+= replacement.length();
}
sbSourceLower.setLength(0);
sbSourceLower.trimToSize();
sbSourceLower = null;
return sbSource.toString();
}
public static void main(String[] args)
{
System.out.println(replace("xXXxyyyXxxuuuuoooo", "xx", "**"));
System.out.println(replace("FOoBaR", "bar", "*"));
}
}
You can try this code (requires jQuery):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').keyup(function(e) {
var v = $('#foo').val();
$('#debug').val(v);
})
});
</script>
</head>
<body>
<form>
<input type="text" id="foo" value="bar"><br>
<textarea id="debug"></textarea>
</form>
</body>
</html>
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
Check this handy pipe for Angular2: Usage:
in the SafePipe
code, substitute DomSanitizationService
with DomSanitizer
provide the SafePipe
if your NgModule
<div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>
You can do this from storyboard. Select your button. Set Line Break 'Word Wrap', Set your title 'Plain' to 'Attributed'. Select 'Center alignment'. This part is important => Click ...(More) Button. And select line breaking mode to 'Character Wrap'.
To ignore all untracked files in any submodule use the following command to ignore those changes.
git config --global diff.ignoreSubmodules dirty
It will add the following configuration option to your local git config:
[diff]
ignoreSubmodules = dirty
Further information can be found here
You can change the JDK or JRE location using the following steps:
[tomcat-home]\bin
directory.
c:\tomcat8\bin
Tomcat8W //ES//Tomcat8
note:
in Apache TomEE same steps, but step (3) the command must be: TomEE //ES
I have used this simple code, and it works!
for (int i = 0; i < N * N; i++)
{
Thread.Sleep(50);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
(float)10.25, FontStyle.Bold),
Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
}
It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#
I used this code, and it does work.
$date = '2014-02-25';
date('D', strtotime($date));
I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t"
otherwise, sep = " "
.
import pandas as pd
data = pd.read_csv('data.txt', sep=" ", header=None)
One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.
int someint = (somedouble+epsilon);
Another easy way is to make your theme a child of Theme.AppCompat.Light.NoActionBar
like so:
<style name="NoActionBarTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
</style>
Whenever invalid xml character comes xml, it gives such error. When u open it in notepad++ it look like VT, SOH,FF like these are invalid xml chars. I m using xml version 1.0 and i validate text data before entering it in database by pattern
Pattern p = Pattern.compile("[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+");
retunContent = p.matcher(retunContent).replaceAll("");
It will ensure that no invalid special char will enter in xml
create table Customer(
CustId int primary key,
CustName varchar(20),
DOB date);
insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));
From other post:
find /c "string" file >NUL
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
Use the /i switch when you want case insensitive checking:
find /i /c "string" file >NUL
Or something like: if not found write to file.
find /c "%%P" file.txt || ( echo %%P >> newfile.txt )
Or something like: if found write to file.
find /c "%%P" file.txt && ( echo %%P >> newfile.txt )
Or something like:
find /c "%%P" file.txt && ( echo found ) || ( echo not found )
You can ssh to your server and run this command
ln -s /usr/share/phpmyadmin /var/www/phpmyadmin
It worked for me..
@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.
The most reliable, simplest answer is:
body {_x000D_
/* for demo */_x000D_
background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
/* anything or nothing, it doesn't matter */_x000D_
width: 60%;_x000D_
/* only need if other rulesets give this padding */_x000D_
padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
height: 0;_x000D_
/* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
padding: 0 0 56.25%;_x000D_
position: relative;_x000D_
/* only need next 2 rules if other rulesets change these */_x000D_
margin: 0;_x000D_
width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
/* for demo */_x000D_
border: 0;_x000D_
background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
<div class="fixed-aspect-padder">_x000D_
<iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
</div>_x000D_
</div>
_x000D_
/**
* Shows confirmation dialog about signing in.
*/
private void startAuthDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(800, 1400);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.auth_dialog, null);
alertDialog.getWindow().setContentView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
}
I don't think this is achievable using only CSS animations. I am assuming that CSS transitions do not fulfil your use case, because (for example) you want to chain two animations together, use multiple stops, iterations, or in some other way exploit the additional power animations grant you.
I've not found any way to trigger a CSS animation specifically on mouse-out without using JavaScript to attach "over" and "out" classes. Although you can use the base CSS declaration trigger an animation when the :hover ends, that same animation will then run on page load. Using "over" and "out" classes you can split the definition into the base (load) declaration and the two animation-trigger declarations.
The CSS for this solution would be:
.class {
/* base element declaration */
}
.class.out {
animation-name: out;
animation-duration:2s;
}
.class.over {
animation-name: in;
animation-duration:5s;
animation-iteration-count:infinite;
}
@keyframes in {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes out {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}
And using JavaScript (jQuery syntax) to bind the classes to the events:
$(".class").hover(
function () {
$(this).removeClass('out').addClass('over');
},
function () {
$(this).removeClass('over').addClass('out');
}
);
One common use is for template-typedef workaround classes like following:
template <class TObj>
class MyLibrariesSmartPointer
{
MyLibrariesSmartPointer();
public:
typedef smart_ptr<TObj> type;
};
Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType>
instead of MyLibrariesSmartPointer<SomeType>::type
, which is desireable.
You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)
Use Load function
load(filename)
You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.
Example : mongo localhost:27017/mydb myfile.js
This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.
For loading external js you can write
load("/data/db/scripts/myloadjs.js")
Suppose we have two js file myFileOne.js and myFileTwo.js
myFileOne.js
print('From file 1');
load('myFileTwo.js'); // Load other js file .
myFileTwo.js
print('From file 2');
MongoShell
>mongo myFileOne.js
Output
From file 1
From file 2
First you will need to install node definitions for Typescript. You can find the definitions file here:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts
Once you've got file, just add the reference to your .ts
file like this:
/// <reference path="path/to/node.d.ts" />
Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts
can look like this:
/// <reference path="path/to/node.d.ts" />
class MyClass {
// Here we import the File System module of node
private fs = require('fs');
constructor() { }
createFile() {
this.fs.writeFile('file.txt', 'I am cool!', function(err) {
if (err) {
return console.error(err);
}
console.log("File created!");
});
}
showFile() {
this.fs.readFile('file.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}
}
// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();
Once you transpile your .ts
file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:
> node myClass.js
You aren't supposed to change the folder attribute to not-readonly. The reason you are seeing this error message is that source control assumes that you only store your miscellaneous files somewhere other than bin folder, for it it reserved for files that are automatically created by .Net and it doesn't want to add them to source control.
I suggest instead of using Environment.CurrectDirectory
(which I assume you are using currently), you create a folder named "MyProjectName" in %appdata% address and then use:
System.IO.Path.Combine(Environment.GetEnvironmentVariable("appdata"),"YourProjectName")
.
You should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).
Here is a code sample with your three keywords working fine:
Here is the file ts.txt
:
*** test cases ***
mytest
${color} = set variable Red
Run Keyword If '${color}' == 'Red' log to console \nexecuted with single condition
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
${color} = set variable Blue
${Size} = set variable Small
${Simple} = set variable Simple
${Design} = set variable Simple
Run Keyword If '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}' log to console \nexecuted with multiple and
${Size} = set variable XL
${Design} = set variable Complicated
Run Keyword Unless '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple' log to console \nexecuted with unless and multiple or
and here is what I get when I execute it:
$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest | PASS |
------------------------------------------------------------------------------
I could get solution for such a similar problem with addition of a simple line
HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.
The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).
So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)
The difference between factory and service is just like the difference between a function and an object
Factory Provider
Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Factory are a great way for communicating between controllers like sharing data.
Can use other dependencies
Usually used when the service instance requires complex creation logic
Cannot be injected in .config()
function.
Used for non configurable services
If you're using an object, you could use the factory provider.
Syntax: module.factory('factoryName', function);
Service Provider
Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)
Singleton and will only be created once
Reusable components
Services are used for communication between controllers to share data
You can add properties and functions to a service object by using the this
keyword
Dependencies are injected as constructor arguments
Used for simple creation logic
Cannot be injected in .config()
function.
If you're using a class you could use the service provider
Syntax: module.service(‘serviceName’, function);
In below example I have define MyService
and MyFactory
. Note how in .service
I have created the service methods using this.methodname.
In .factory
I have created a factory object and assigned the methods to it.
AngularJS .service
module.service('MyService', function() {
this.method1 = function() {
//..method1 logic
}
this.method2 = function() {
//..method2 logic
}
});
AngularJS .factory
module.factory('MyFactory', function() {
var factory = {};
factory.method1 = function() {
//..method1 logic
}
factory.method2 = function() {
//..method2 logic
}
return factory;
});
Also Take a look at this beautiful stuffs
Confused about service vs factory
I prefer using the ggfortify
library. It is a ggplot2
wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.
library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2) , start = c(2010,5), frequency = 12 ),
facets = FALSE)
This works for me:
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
I have similar formula for the First and Last Day
The First Day of the month
FirstDay = DateSerial(Year(Date),Month(Date),1)
The zero Day of the next month is the Last Day of the month
LastDay = DateSerial(Year(Date),Month(Date)+ 1,0)
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
Hope this helps!
The below function is most efficient way to deep clone javascript objects.
function deepCopy(obj){
if (!obj || typeof obj !== "object") return obj;
var retObj = {};
for (var attr in obj){
var type = obj[attr];
switch(true){
case (type instanceof Date):
var _d = new Date();
_d.setDate(type.getDate())
retObj[attr]= _d;
break;
case (type instanceof Function):
retObj[attr]= obj[attr];
break;
case (type instanceof Array):
var _a =[];
for (var e of type){
//_a.push(e);
_a.push(deepCopy(e));
}
retObj[attr]= _a;
break;
case (type instanceof Object):
var _o ={};
for (var e in type){
//_o[e] = type[e];
_o[e] = deepCopy(type[e]);
}
retObj[attr]= _o;
break;
default:
retObj[attr]= obj[attr];
}
}
return retObj;
}
var obj = {
string: 'test',
array: ['1'],
date: new Date(),
object:{c: 2, d:{e: 3}},
function: function(){
return this.date;
}
};
var copyObj = deepCopy(obj);
console.log('object comparison', copyObj === obj); //false
console.log('string check', copyObj.string === obj.string); //true
console.log('array check', copyObj.array === obj.array); //false
console.log('date check', copyObj2.date === obj.date); //false
console.log('object check', copyObj.object === obj.object); //false
console.log('function check', copyObj.function() === obj.function()); //true
I found that using the following, simple code did the trick (requires custom image in bundle):
// Creates a back button instead of default behaviour (displaying title of previous screen)
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backAction)];
tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
[backButton release];
For the html code:
test.html
<button class="dismiss" onclick="alert('hello')">
<string for="exit">Dismiss</string>
</button>
the below python code worked for me. You can just try it.
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()
1 - Go to window . 2 - Go to Perspective and click . 3 - Go to Reset Perspective. 4 - Then you will find Eclipse all reset option.
A slightly simplified answer:
public class Book
{
private final String title;
public Book(String title)
{
this.title = title;
}
public Book()
{
this("Default Title");
}
...
}
A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.
A px is a pixel, which will map on to a screen pixel in most cases.
CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.
A pixel is great if you need to size something to match an image, or if you want a thin border.
Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.
Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)
… and so on.
$(document).ready(function() {
var CookieSet = $.cookie('cookietitle', 'yourvalue');
if (CookieSet == null) {
// Do Nothing
}
if (jQuery.cookie('cookietitle')) {
// Reactions
}
});
I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.
I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:
$('.start').keyup(function() {
var otherInputs = $(this).parents('td').siblings().find('input');
for(var i = 0; i < otherInputs.length; i++) {
alert($(otherInputs[i]).val());
}
return false;
});
Give unique class and different id for file input
$("#tab-content").on('change',class,function()
{
var id=$(this).attr('id');
$("#"+id).trigger(your function);
//for name of file input $("#"+id).attr("name");
});
Try this code, Hope this will help you. If this package is available then this will open the app or else open the play store for downloads
String packageN = "aman4india.com.pincodedirectory";
Intent i = getPackageManager().getLaunchIntentForPackage(packageN);
if (i != null) {
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
} else {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
}
catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
}
}
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount
function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all
is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById()
, it should probably work. Example: document.getElementById("RUnits").value
instead of document.all.Capacity.RUnits.value
You can do this by disabling the long press of the EditText
To implement it, just add the following line in the xml -
android:longClickable="false"
A clustered index actually describes the order in which records are physically stored on the disk, hence the reason you can only have one.
A Non-Clustered Index defines a logical order that does not match the physical order on disk.
Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.
For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt
Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.
Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:
SELECT 'How is my son''s school helping him learn? "Not as good as Stack Overflow would!"'
Print:
How is my son's school helping him learn? "Not as good as Stack Overflow would!"
You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();
.
I am using Spring 3.2.4 and Jackson FasterXML 2.1.1.
I have created a custom JacksonObjectMapper that works with explicit annotations for each attribute of the Objects mapped:
package com.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class MyJaxbJacksonObjectMapper extends ObjectMapper {
public MyJaxbJacksonObjectMapper() {
this.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
Then this is instantiated in the context-configuration (servlet-context.xml):
<mvc:annotation-driven>
<mvc:message-converters>
<beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper">
<beans:bean class="com.test.MyJaxbJacksonObjectMapper" />
</beans:property>
</beans:bean>
</mvc:message-converters>
</mvc:annotation-driven>
This works fine!
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
I just installed Node.js for the first time and it includes NPM, which can be ran from the Windows cmd. However, make sure that you run it as an administrator. Right click on cmd and choose "run as administrator". This allowed me to call npm commands.
One that I use often:
Integer.parseInt("1234");
Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.
Recently ran into this problem when attempting to build a solution I am working on (not just a winforms proj).
In addition to build
failure, I noticed that cleaning projects would quietly fail (checking the bin folder showed that the files had not actually been erased) and closing the Visual Studio did not end the devenv
process - rather, it caused it to crash. Windows recovery process would then restart the Visual Studio.
After some trial and error, I found the problems only happened to me when I opened the solution from the "Recent" menu on starting up VS.
Opening the solution from File >> Open >> Project/Solution
found it working as per usually.
Currently no idea why - will keep looking into this but for now, at least I can work!
The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!
<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />
Change the window width and the image scales obligingly.
Interface are nothing but a pure abstract class in C++. Ideally this interface class
should contain only pure virtual
public methods and static const
data. For example:
class InterfaceA
{
public:
static const int X = 10;
virtual void Foo() = 0;
virtual int Get() const = 0;
virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}
If you don't have to use the support library then have a look at Roman's answer.
But if you want to use the support library you have to use the old animation framework as described below.
After consulting Reto's and blindstuff's answers I have gotten the following code working.
The fragments appear sliding in from the right and sliding out to the left when back is pressed.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
CustomFragment newCustomFragment = CustomFragment.newInstance();
transaction.replace(R.id.fragment_container, newCustomFragment );
transaction.addToBackStack(null);
transaction.commit();
The order is important. This means you must call setCustomAnimations()
before replace()
or the animation will not take effect!
Next these files have to be placed inside the res/anim folder.
enter.xml:
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
exit.xml:
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="-100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_enter.xml:
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="-100%"
android:toXDelta="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
pop_exit.xml:
<?xml version="1.0" encoding="utf-8"?>
<set>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
The duration of the animations can be changed to any of the default values like @android:integer/config_shortAnimTime
or any other number.
Note that if in between fragment replacements a configuration change happens (for example rotation) the back action isn't animated. This is a documented bug that still exists in the rev 20 of the support library.
Try this function instead.
string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);
Not sure if it is a best practice, but when working with large amounts of images in a loop (i.e. creating and disposing a lot of Graphics/Image/Bitmap objects), i regularly let the GC.Collect.
I think I read somewhere that the GC only runs when the program is (mostly) idle, and not in the middle of a intensive loop, so that could look like an area where manual GC could make sense.
In case anybody wants to use the latest Version (v5.7.2)
Please find my latest version (inspired by Victors answer).
It includes all Free Icons of the "Regular"-Set: https://fontawesome.com/icons?d=gallery&s=regular&m=free
Index.html
<head>
...
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
...
</head>
CSS:
select {
font-family: 'Lato', 'Font Awesome 5 Free';
font-weight: 900;
}
HTML:
<select id="icon">
<option value="address-book"> address-book</option>
<option value="address-card"> address-card</option>
<option value="angry"> angry</option>
<option value="arrow-alt-circle-down"> arrow-alt-circle-down</option>
<option value="arrow-alt-circle-left"> arrow-alt-circle-left</option>
<option value="arrow-alt-circle-right"> arrow-alt-circle-right</option>
<option value="arrow-alt-circle-up"> arrow-alt-circle-up</option>
<option value="bell"> bell</option>
<option value="bell-slash"> bell-slash</option>
<option value="bookmark"> bookmark</option>
<option value="building"> building</option>
<option value="calendar"> calendar</option>
<option value="calendar-alt"> calendar-alt</option>
<option value="calendar-check"> calendar-check</option>
<option value="calendar-minus"> calendar-minus</option>
<option value="calendar-plus"> calendar-plus</option>
<option value="calendar-times"> calendar-times</option>
<option value="caret-square-down"> caret-square-down</option>
<option value="caret-square-left"> caret-square-left</option>
<option value="caret-square-right"> caret-square-right</option>
<option value="caret-square-up"> caret-square-up</option>
<option value="chart-bar"> chart-bar</option>
<option value="check-circle"> check-circle</option>
<option value="check-square"> check-square</option>
<option value="circle"> circle</option>
<option value="clipboard"> clipboard</option>
<option value="clock"> clock</option>
<option value="clone"> clone</option>
<option value="closed-captioning"> closed-captioning</option>
<option value="comment"> comment</option>
<option value="comment-alt"> comment-alt</option>
<option value="comment-dots"> comment-dots</option>
<option value="comments"> comments</option>
<option value="compass"> compass</option>
<option value="copy"> copy</option>
<option value="copyright"> copyright</option>
<option value="credit-card"> credit-card</option>
<option value="dizzy"> dizzy</option>
<option value="dot-circle"> dot-circle</option>
<option value="edit"> edit</option>
<option value="envelope">󴃠 envelope </option>
<option value="envelope-open"> envelope-open</option>
<option value="eye"> eye</option>
<option value="eye-slash"> eye-slash</option>
<option value="file"> file</option>
<option value="file-alt"> file-alt</option>
<option value="file-archive"> file-archive</option>
<option value="file-audio"> file-audio</option>
<option value="file-code"> file-code</option>
<option value="file-excel"> file-excel </option>
<option value="file-image"> file-image</option>
<option value="file-pdf"> file-pdf</option>
<option value="file-powerpoint"> file-powerpoint</option>
<option value="file-video"> file-video</option>
<option value="file-word"> file-word</option>
<option value="flag"> flag</option>
<option value="flushed"> flushed</option>
<option value="folder"> folder</option>
<option value="folder-open"> folder-open </option>
<option value="frown"> frown</option>
<option value="frown-open"> frown-open</option>
<option value="futbol"> futbol</option>
<option value="gem"> gem</option>
<option value="grimace"> grimace</option>
<option value="grin"> grin</option>
<option value="grin-alt"> grin-alt</option>
<option value="grin-beam"> grin-beam</option>
<option value="grin-beam-sweet"> grin-beam-sweet </option>
<option value="grin-hearts"> grin-hearts</option>
<option value="grin-squint"> grin-squint</option>
<option value="grin-squint-tears"> grin-squint-tears</option>
<option value="grin-stars"> grin-stars</option>
<option value="grin-tears"> grin-tears</option>
<option value="grin-tongue"> grin-tongue</option>
<option value="grin-tongue-squint"> grin-tongue-squint</option>
<option value="grin-tongue-wink"> grin-tongue-wink</option>
<option value="grin-wink"> grin-wink </option>
<option value="hand-lizard"> hand-lizard</option>
<option value="hand-paper"> hand-paper</option>
<option value="hand-peace"> hand-peace</option>
<option value="hand-point-down"> hand-point-down</option>
<option value="hand-point-left"> hand-point-left</option>
<option value="hand-point-right"> hand-point-right</option>
<option value="hand-point-up"> hand-point-up</option>
<option value="hand-pointer"> hand-pointer</option>
<option value="hand-rock"> hand-rock </option>
<option value="hand-scissors"> hand-scissors</option>
<option value="hand-spock"> hand-spock</option>
<option value="handshake"> handshake</option>
<option value="hdd"> hdd</option>
<option value="heart"> heart</option>
<option value="home"> home</option>
<option value="hospital"> hospital</option>
<option value="hourglass"> hourglass</option>
<option value="id-badge"> id-badge</option>
<option value="id-card"> id-card </option>
<option value="image"> image</option>
<option value="images"> images</option>
<option value="keyboard"> keyboard</option>
<option value="kiss"> kiss</option>
<option value="kiss-beam"> kiss-beam</option>
<option value="kiss-wink-heart"> kiss-wink-heart</option>
<option value="laugh"> laugh</option>
<option value="laugh-beam"> laugh-beam</option>
<option value="laugh-squint"> laugh-squint </option>
<option value="laugh-wink"> laugh-wink</option>
<option value="lemon"> lemon</option>
<option value="life-ring"> life-ring</option>
<option value="lightbulb"> lightbulb</option>
<option value="list-alt"> list-alt</option>
<option value="map"> map</option>
<option value="meh"> meh</option>
<option value="meh-blank"> meh-blank</option>
<option value="meh-rolling-eyes"> meh-rolling-eyes </option>
<option value="minus-square"> minus-square</option>
<option value="money-bill-alt"> money-bill-alt</option>
<option value="moon"> moon</option>
<option value="newspaper"> newspaper</option>
<option value="object-group"> object-group</option>
<option value="object-upgroup"> object-upgroup</option>
<option value="paper-plane"> paper-plane</option>
<option value="pause-circle"> pause-circle</option>
<option value="play-circle"> play-circle </option>
<option value="plus-square"> plus-square</option>
<option value="question-circle"> question-circle</option>
<option value="registered"> registered</option>
<option value="sad-cry"> sad-cry</option>
<option value="sad-tear"> sad-tear</option>
<option value="save"> save</option>
<option value="share-square"> share-square</option>
<option value="smile"> smile</option>
<option value="smile-beam"> smile-beam </option>
<option value="smile-wink"> smile-wink</option>
<option value="snowflake"> snowflake</option>
<option value="square"> square</option>
<option value="star"> star</option>
<option value="star-half"> star-half</option>
<option value="sticky-note"> sticky-note</option>
<option value="stop-circle"> stop-circle</option>
<option value="sun"> sun</option>
<option value="surprise"> surprise </option>
<option value="thumbs-down"> thumbs-down</option>
<option value="thumbs-up">󱅤 thumbs-up</option>
<option value="times-circle"> times-circle</option>
<option value="tired"> tired</option>
<option value="trash-alt"> trash-alt</option>
<option value="user"> user</option>
<option value="user-circle"> user-circle</option>
<option value="window-close"> window-close</option>
<option value="window-maximize"> window-maximize </option>
<option value="window-minimize"> window-minimize</option>
<option value="window-restore"> window-restore</option>
</select>
If you can use Map
or Object.assign
, it's very easy.
Create an array:
const languages = ['css', 'javascript', 'php', 'html'];
The below creates an object with index as keys:
Object.assign({}, languages)
Replicate the same as above with Maps
Converts to an index based object {0 : 'css'}
etc...
const indexMap = new Map(languages.map((name, i) => [i, name] ));
indexMap.get(1) // javascript
Convert to an value based object {css : 'css is great'}
etc...
const valueMap = new Map(languages.map(name => [name, `${name} is great!`] ));
valueMap.get('css') // css is great
As many answers here correctly and clearly point out, you should not generally attempt to loop in pandas, but rather should write vectorized code. But the question remains if you should EVER write loops in pandas, and if so the best way to loop in those situations.
I believe there is at least one general situation where loops are appropriate: when you need to calculate some function that depends on values in other rows in a somewhat complex manner. In this case, the looping code is often simpler, more readable, and less error prone than vectorized code. The looping code might even be faster, too.
I will attempt to show this with an example. Suppose you want to take a cumulative sum of a column, but reset it whenever some other column equals zero:
import pandas as pd
import numpy as np
df = pd.DataFrame( { 'x':[1,2,3,4,5,6], 'y':[1,1,1,0,1,1] } )
# x y desired_result
#0 1 1 1
#1 2 1 3
#2 3 1 6
#3 4 0 4
#4 5 1 9
#5 6 1 15
This is a good example where you could certainly write one line of pandas to achieve this, although it's not especially readable, especially if you aren't fairly experienced with pandas already:
df.groupby( (df.y==0).cumsum() )['x'].cumsum()
That's going to be fast enough for most situations, although you could also write faster code by avoiding the groupby, but it will likely be even less readable.
Alternatively, what if we write this as a loop? You could do something like the following with numpy:
import numba as nb
@nb.jit(nopython=True) # optional
def custom_sum(x,y):
x_sum = x.copy()
for i in range(1,len(df)):
if y[i] > 0: x_sum[i] = x_sum[i-1] + x[i]
return x_sum
df['desired_result'] = custom_sum( df.x.to_numpy(), df.y.to_numpy() )
Admittedly, there's a bit of overhead there required to convert DataFrame columns to numpy arrays, but the core piece of code is just one line of code that you could read even if you didn't know anything about pandas or numpy:
if y[i] > 0: x_sum[i] = x_sum[i-1] + x[i]
And this code is actually faster than the vectorized code. In some quick tests with 100,000 rows, the above is about 10x faster than the groupby approach. Note that one key to the speed there is numba, which is options. Without the "@nb.jit" line, the looping code is actually about 10x slower than the groupby approach.
Clearly this example is simple enough that you would likely prefer the one line of pandas to writing a loop with its associated overhead. However, there are more complex versions of this problem for which the readability or speed of the numpy/numba loop approach likely makes sense.
I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to
private SSLSocketFactory delegate;
This is my TLSSocketFactory class
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
and this is how i used it with okhttp and retrofit
OkHttpClient client=new OkHttpClient();
try {
client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory())
.build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
If you created any view in Mysql databases then you can simply see it as you see your all tables in your particular database.
write:
--mysql> SHOW TABLES;
you will see list of tables and views of your database.
There isn't a great way to do it out of the box. If you want to be using your cleaner syntax on a regular basis, then you can create a utility class to help out:
public class OptionalEx {
private boolean isPresent;
private OptionalEx(boolean isPresent) {
this.isPresent = isPresent;
}
public void orElse(Runnable runner) {
if (!isPresent) {
runner.run();
}
}
public static <T> OptionalEx ifPresent(Optional<T> opt, Consumer<? super T> consumer) {
if (opt.isPresent()) {
consumer.accept(opt.get());
return new OptionalEx(true);
}
return new OptionalEx(false);
}
}
Then you can use a static import elsewhere to get syntax that is close to what you're after:
import static com.example.OptionalEx.ifPresent;
ifPresent(opt, x -> System.out.println("found " + x))
.orElse(() -> System.out.println("NOT FOUND"));
Click the mse7.exe
installed along with Office typically at \Program Files\Microsoft Office\OFFICE11
.
This will open up the debugger, open the file and then run the debugger in the GUI mode.
i made a method that merge cells and put border.
protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
sheet.addMergedRegion(cellMerge);
if (border) {
setBordersToMergedCells(sheet, cellMerge);
}
}
protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}
Paste this on your command line:
export LC_CTYPE="en_US.UTF-8"
You cannot use path with directory separators directly, but you will have to make a file object for every directory.
NOTE: This code makes directories, yours may not need that...
File file= context.getFilesDir();
file.mkdir();
String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
file=new File(file,array[t]);
file.mkdir();
}
File f=new File(file,array[array.length-1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
There is a operator < between lists e.g.:
[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]
will give
False
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
The correct way for checking the visibility of an element with Protractor is to call the isDisplayed
method. You should be careful though since isDisplayed
does not return a boolean, but rather a promise
providing the evaluated visibility. I've seen lots of code examples that use this method wrongly and therefore don't evaluate its actual visibility.
Example for getting the visibility of an element:
element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
if (isVisible) {
// element is visible
} else {
// element is not visible
}
});
However, you don't need this if you are just checking the visibility of the element (as opposed to getting it) because protractor patches Jasmine expect() so it always waits for promises to be resolved. See github.com/angular/jasminewd
So you can just do:
expect(element(by.className('your-class-name')).isDisplayed()).toBeTruthy();
Since you're using AngularJS
to control the visibility of that element, you could also check its class attribute for ng-hide
like this:
var spinner = element.by.css('i.icon-spin');
expect(spinner.getAttribute('class')).not.toMatch('ng-hide'); // expect element to be visible
According to matplotlib documentation, The signature of the Axes
class grid()
method is as follows:
Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.
which
can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.
axis
can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.
So in order to show grid lines for both the x axis and y axis, we can use the the following code:
ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')
This method gives us finer control over what to show for grid lines.
The serial communication manager library has many API and features targeted for the task you want. If the device is a USB-UART its VID/PID can be used. If the device is BT-SPP than platform specific APIs can be used. Take a look at this project for serial port programming: https://github.com/RishiGupta12/serial-communication-manager
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
Select the text you want to automatically indent.
Click Format Selection in Edit, Advanced, or press CTRL+K, CTRL+F. Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.
Step (1) :- CTRL+A
Step (2) :- CTRL+K
Step (3) :- CTRL+F
You can use ngModel
like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue
in your code and when the checkbox is changed by the user addProp()
is called.
Just to add another option to Dónal's answer, you can also still use the good old java.lang.Object.getClass()
method.
Using Windows command prompt: adb logcat -d | findstr <package>
.
*This was first mentioned by jj_, but it took me ages to find it in the comments...
U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
This is the best code I found to get the current IP, avoiding get VMWare host or other invalid IP address.
public string GetLocalIpAddress()
{
UnicastIPAddressInformation mostSuitableIp = null;
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var network in networkInterfaces)
{
if (network.OperationalStatus != OperationalStatus.Up)
continue;
var properties = network.GetIPProperties();
if (properties.GatewayAddresses.Count == 0)
continue;
foreach (var address in properties.UnicastAddresses)
{
if (address.Address.AddressFamily != AddressFamily.InterNetwork)
continue;
if (IPAddress.IsLoopback(address.Address))
continue;
if (!address.IsDnsEligible)
{
if (mostSuitableIp == null)
mostSuitableIp = address;
continue;
}
// The best IP is the IP got from DHCP server
if (address.PrefixOrigin != PrefixOrigin.Dhcp)
{
if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
mostSuitableIp = address;
continue;
}
return address.Address.ToString();
}
}
return mostSuitableIp != null
? mostSuitableIp.Address.ToString()
: "";
}
To read only the first row of the csv file use next()
on the reader object.
with open('some.csv', newline='') as f:
reader = csv.reader(f)
row1 = next(reader) # gets the first line
# now do something here
# if first row is the header, then you can do one more next() to get the next row:
# row2 = next(f)
or :
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
# do something here with `row`
break
One solution is to put them inside <center>
, like this:
<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>
I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/
If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors();
in the configure
method. The method looks like that:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
Given:
public enum PersonType {
COOL_GUY(1),
JERK(2);
private final int typeId;
private PersonType(int typeId) {
this.typeId = typeId;
}
public final int getTypeId() {
return typeId;
}
public static PersonType findByTypeId(int typeId) {
for (PersonType type : values()) {
if (type.typeId == typeId) {
return type;
}
}
return null;
}
}
For me, this typically aligns with a look-up table in a database (for rarely-updated tables only).
However, when I try to use findByTypeId
in a switch statement (from, most likely, user input)...
int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
// Do things only a cool guy would do.
break;
case JERK:
// Push back. Don't enable him.
break;
default:
// I don't know or care what to do with this mess.
}
...as others have stated, this results in an NPE @ switch(personType) {
. One work-around (i.e., "solution") I started implementing was to add an UNKNOWN(-1)
type.
public enum PersonType {
UNKNOWN(-1),
COOL_GUY(1),
JERK(2);
...
public static PersonType findByTypeId(int id) {
...
return UNKNOWN;
}
}
Now, you don't have to do null-checking where it counts and you can choose to, or not to, handle UNKNOWN
types. (NOTE: -1
is an unlikely identifier in a business scenario, but obviously choose something that makes sense for your use-case).
make a parent div, in css make it float:right then make the child div's position fixed this will make the div stay in its position at all times and on the right
Mount remount the /
Eg.
mount -o remount,rw /dev/xyz /
sed -i 's/1 1/0 0/' /etc/fstab
sed -i 's/1 2/0 0/' /etc/fstab
As mentioned by the other answers you can use:
Process.Start("notepad somefile.txt");
However, there is another way.
You can instance a Process object and call the Start instance method:
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.StartInfo.WorkingDirectory = "c:\temp";
process.StartInfo.Arguments = "somefile.txt";
process.Start();
Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.
Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.
I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.
/**
* ResizeHeaderOnScroll
*
* @constructor
*/
var ResizeHeaderOnScroll = function()
{
this.protocol = window.location.protocol;
this.domain = window.location.host;
};
ResizeHeaderOnScroll.prototype.init = function()
{
if($(document).scrollTop() > 0)
{
$('header').data('size','big');
} else {
$('header').data('size','small');
}
ResizeHeaderOnScroll.prototype.checkScrolling();
$(window).scroll(function(){
ResizeHeaderOnScroll.prototype.checkScrolling();
});
};
ResizeHeaderOnScroll.prototype.checkScrolling = function()
{
if($(document).scrollTop() > 0)
{
if($('header').data('size') == 'big')
{
$('header').data('size','small');
$('header').stop().animate({
paddingTop:'1em',
paddingBottom:'1em'
},200);
}
}
else
{
if($('header').data('size') == 'small')
{
$('header').data('size','big');
$('header').stop().animate({
paddingTop:'3em'
},200);
}
}
}
$(document).ready(function(){
var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
resizeHeaderOnScroll.init()
})
Actually you just need to tell doctrine who's your repository class, if you don't, doctrine uses default repo instead of yours.
@ORM\Entity(repositoryClass="Company\NameOfBundle\Repository\NameOfRepository")
A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code.
the ideal way is to
{{ something|safe }}
than completely turning off auto escaping.
In Eclipse;
It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version
object. Try setting the versionID
to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];
If you want to set by the id property then you need to add the select as
syntax:
ng-options="version.id as version.name for version in versions"
Table names and column names can be specified as part of the mapping of DbContext
. Then there is no need to do it in migrations.
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Restaurant>()
.HasMany(p => p.Cuisines)
.WithMany(r => r.Restaurants)
.Map(mc =>
{
mc.MapLeftKey("RestaurantId");
mc.MapRightKey("CuisineId");
mc.ToTable("RestaurantCuisines");
});
}
}
If you can edit all documents in aggregate :
"TimeStamp": {$toDecimal: {$toDate: "$Your Date"}}
And for the client, you set the query :
Date.parse("Your date".toISOString())
That's what makes you whole work with ISODate.
$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';
$array = array_values($array);
through this function you can reset your array
$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';
If you are using eclipse and if you want force eclipse to re load dependencies you could try below command
gradlew clean cleaneclipse build eclipse --refresh-dependencies
1. Try this: .attr()
$('.field').hover(function () {
var value=$(this).attr('data-fullText');
$(this).html(value);
});
DEMO 1: http://jsfiddle.net/hsakapandit/Jn4V3/
2. Try this: .data()
$('.field').hover(function () {
var value=$(this).data('fulltext');
$(this).html(value);
});
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
Like this:
#include <string>
#include <vector>
struct user
{
std::string username;
std::vector<unsigned char> userpassword;
};
int main()
{
user r; // r.username is "" and r.userpassword is empty
// ...
}
li:nth-child(1n) { color:green; }_x000D_
li:nth-child(2n) { color:red; }
_x000D_
<ul>_x000D_
<li>list element 1</li>_x000D_
<li>list element 2</li>_x000D_
<li>list element 3</li>_x000D_
<li>list element 4</li>_x000D_
</ul>
_x000D_
See browser support here : CSS3 :nth-child() Selector
You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.
Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.
rp
I use both PuTTY and Bitvise SSH Client. PuTTY handles screen sessions better, but Bitvise automatically opens up a SFTP window so you can transfer files just like you would with an FTP client.
Click 'Run'->choose your JUnit->in 'Test Runner' select the JUnit version you want to run with.