Try this :
ImageView imageview = (ImageView)findViewById(R.id.your_imageview_id);
Bitmap bmp = BitmapFactory.decodeFile(new java.net.URL(your_url).openStream());
imageview.setImageBitmap(bmp);
You can also try this : Android-Universal-Image-Loader for efficiently loading your image from URL
First we need to check if we have enabled mod_headers.c and mod_expires.c.
sudo apache2 -l
If we don't have it, we need to enable them
sudo a2enmod headers
Then we need to restart apache
sudo apache2 restart
At last, add the rules on .htaccess (seen on other answers), for example
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>
figure (1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig, 'Position', [0 0 xwidth ywidth])
plot(x,y)
print -depsc2 correlation.eps; % for saving in eps, look up options for saving as png or other formats you may need
This saves the figure in the dimensions specified
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
I have used this library with sucess
http://plugins.krajee.com/checkbox-x
It requires jQuery and bootstrap 3.x
Download the zip here: https://github.com/kartik-v/bootstrap-checkbox-x/zipball/master
Put the contents of the zip in a folder within your project
Pop the needed libs in your header
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="path/to/css/checkbox-x.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="path/to/js/checkbox-x.min.js" type="text/javascript"></script>
Add the data controls to the element using the data-size="xl" to change the size as shown here http://plugins.krajee.com/cbx-sizes-demo
<label for="element_id">CheckME</label>
<input type="checkbox" name="my_element" id="element_id" value="1" data-toggle="checkbox-x" data-three-state="false" data-size="xl"/>
There are numerous other features as well if you browse the plugin site.
Only two Semicolons are allowed to be used in for
loop.
If you have do initialization of multiple variables or manipulation of multiple variables, you can achieve it by separating them with comma(,).
for(int i=0, j=5; i < 5; i++, j--)
NOTE: Multiple conditions separated by comma are NOT allowed.
for(int i=0, j=5; i < 5, j > 5; i++, j--) // This is NOT allowed.
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
Best solution to solve this. I was searching the same problem. I spent 1 day and then I got solution. Now, It is well.
Check your R version in bash terminal if you are on Ubuntu or Linux.
R --version
then use these commands
sudo apt-get update
sudo apt-get upgrade
Now check the new version of R. Use this command
sudo apt-cache showpkg r-base
Now update the R only.
sudo apt-get install r-base
Now R will be updated and the error will be removed. Make sure to cd
the library path where you want to install the new package. This way in bash terminal. Try to create the R directory at home folder or it will be at the default. Locate this location for package ~/R/lib/ .
R
.libPaths("~/R/lib")
install.packages("devtools")
OR
install.packages("devtools", lib="~/R/lib")
The good folks at HubSpot have a resource where you can find pure Javascript methodologies for achieving a lot of jQuery goodness - including ready
http://youmightnotneedjquery.com/#ready
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
example inline usage:
ready(function() { alert('hello'); });
You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable
.
Main you have to consider three thing while binding the datasource of a dropdown.
you can use following code to bind a dropdownlist to a datasource as a datatable
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true"
you can use SelectedIndexChanged
event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
While using formControl
, you have to import ReactiveFormsModule
to your imports
array.
Example:
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
MaterialModule,
],
...
})
export class AppModule {}
$("input").change(function () {
alert("Changed!");
});
With Swift 5, Array
has two methods called sorted()
and sorted(by:)
. The first method, sorted()
, has the following declaration:
Returns the elements of the collection, sorted.
func sorted() -> [Element]
The second method, sorted(by:)
, has the following declaration:
Returns the elements of the collection, sorted using the given predicate as the comparison between elements.
func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]
If the element type inside your collection conforms to Comparable
protocol, you will be able to use sorted()
in order to sort your elements with ascending order. The following Playground code shows how to use sorted()
:
class ImageFile: CustomStringConvertible, Comparable {
let fileName: String
let fileID: Int
var description: String { return "ImageFile with ID: \(fileID)" }
init(fileName: String, fileID: Int) {
self.fileName = fileName
self.fileID = fileID
}
static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
return lhs.fileID == rhs.fileID
}
static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
return lhs.fileID < rhs.fileID
}
}
let images = [
ImageFile(fileName: "Car", fileID: 300),
ImageFile(fileName: "Boat", fileID: 100),
ImageFile(fileName: "Plane", fileID: 200)
]
let sortedImages = images.sorted()
print(sortedImages)
/*
prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
*/
If the element type inside your collection conforms to Comparable
protocol, you will have to use sorted(by:)
in order to sort your elements with a descending order.
class ImageFile: CustomStringConvertible, Comparable {
let fileName: String
let fileID: Int
var description: String { return "ImageFile with ID: \(fileID)" }
init(fileName: String, fileID: Int) {
self.fileName = fileName
self.fileID = fileID
}
static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
return lhs.fileID == rhs.fileID
}
static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
return lhs.fileID < rhs.fileID
}
}
let images = [
ImageFile(fileName: "Car", fileID: 300),
ImageFile(fileName: "Boat", fileID: 100),
ImageFile(fileName: "Plane", fileID: 200)
]
let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)
/*
prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
*/
If the element type inside your collection DOES NOT conform to Comparable
protocol, you will have to use sorted(by:)
in order to sort your elements with ascending or descending order.
class ImageFile: CustomStringConvertible {
let fileName: String
let fileID: Int
var description: String { return "ImageFile with ID: \(fileID)" }
init(fileName: String, fileID: Int) {
self.fileName = fileName
self.fileID = fileID
}
}
let images = [
ImageFile(fileName: "Car", fileID: 300),
ImageFile(fileName: "Boat", fileID: 100),
ImageFile(fileName: "Plane", fileID: 200)
]
let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)
/*
prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
*/
Note that Swift also provides two methods called sort()
and sort(by:)
as counterparts of sorted()
and sorted(by:)
if you need to sort your collection in-place.
To just print 1 or 0 based on the boolean value I just used:
printf("%d\n", !!(42));
Especially useful with Flags:
#define MY_FLAG (1 << 4)
int flags = MY_FLAG;
printf("%d\n", !!(flags & MY_FLAG));
For benchmarking, like in your example, I use the pear Benchmark package. You set markers for measuring. The class also provides a few presentation helpers, or you can process the data as you see fit.
I actually have it wrapped in another class with a __destruct method. When a script exits, the output is logged via log4php to syslog, so I have a lot of performance data to work from.
Add System.Web.Extensions as a reference to your project
For Ref.
On my installation of Fedora 25 (workstation) all of the distribution ID info was found in this file:
/usr/lib/os.release.d/os-release-workstation
This included,
Check your php.ini, I'm using Apache2.2 + php 5.3. and I had the same problem and after modify the php.ini in order to set the libraries directory of PHP, it worked correctly. The problem is the default extension_dir
configuration value.
The default (and WRONG) value for my work enviroment is
; extension_dir="ext"
without any full path and commented with a semicolon.
There are two solution that worked fine for me.
1.- Including this line at php.ini file
extension_dir="X:/[PathToYourPHPDirectory]/ext
Where X: is your drive letter instalation (normally C: or D: )
2.- You can try to simply uncomment, deleting semicolon. Include the next line at php.ini file
extension_dir="ext"
Both ways worked fine for me but choose yours. Don't forget restart Apache before try again.
I hope this help you.
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
if non of the steps work from the above. my device still offline after connected through wifi. i did the following:
go to your device...
go to settings.
go to developer options.
Allow adb debugging in charge mode only.
repeat the steps as you always do . which is:
a. connet your usb on chargemode only. b. open command write: - adb tcpip 4455 - adb connect 192.168.1.11:4455 b. disconnect usb.
now everythings work for me .
<html>
<head>
<title> Download-Button </title>
</head>
<body>
<p> Click the image ! You can download! </p>
<?php
$image = basename("http://localhost/sc/img/logo.png"); // you can here put the image path dynamically
//echo $image;
?>
<a download="<?php echo $image; ?>" href="http://localhost/sc/img/logo.png" title="Logo title">
<img alt="logo" src="http://localhost/sc/img/logo.png">
</a>
</body>
This is not a correct method of updating record in SQL:
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
You should write it like this:
command.CommandText = "UPDATE Student
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";
Then you add the parameters same as you added them for the insert operation.
It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:
For example, you might use the following code to increment a counter in XML in C#.
Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);
By using the DLR, you could use the following code instead for the same operation.
scriptobj.Count += 1;
MSDN lists these advantages:
- Simplifies Porting Dynamic Languages to the .NET Framework
- Enables Dynamic Features in Statically Typed Languages
- Provides Future Benefits of the DLR and .NET Framework
- Enables Sharing of Libraries and Objects
- Provides Fast Dynamic Dispatch and Invocation
See MSDN for more details.
If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.
target_compile_options
solution above is wrong, it won't link the library.
Use:
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")
OR
target_link_libraries(XXX PUBLIC pthread)
OR
set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)
GET Scroll Position:
var scrolled_val = window.scrollY;
DETECT Scroll Position:
$(window).scroll
(
function (event)
{
var scrolled_val = window.scrollY;
alert(scrolled_val);
}
);
pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
To add up on the answer, I used this at the beginning of the needed script. So it runs smoothly on different environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
Because I didn't want it to be alsways using the 'Agg'
backend, only when it would go through Travis CI for example.
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
IMHO, the best explanation about its meaning gave us Stroustrup + take into account examples of Dániel Sándor and Mohan:
Stroustrup:
Now I was seriously worried. Clearly we were headed for an impasse or a mess or both. I spent the lunchtime doing an analysis to see which of the properties (of values) were independent. There were only two independent properties:
has identity
– i.e. and address, a pointer, the user can determine whether two copies are identical, etc.can be moved from
– i.e. we are allowed to leave to source of a "copy" in some indeterminate, but valid stateThis led me to the conclusion that there are exactly three kinds of values (using the regex notational trick of using a capital letter to indicate a negative – I was in a hurry):
iM
: has identity and cannot be moved fromim
: has identity and can be moved from (e.g. the result of casting an lvalue to a rvalue reference)
Im
: does not have identity and can be moved from.The fourth possibility,
IM
, (doesn’t have identity and cannot be moved) is not useful inC++
(or, I think) in any other language.In addition to these three fundamental classifications of values, we have two obvious generalizations that correspond to the two independent properties:
i
: has identitym
: can be moved fromThis led me to put this diagram on the board:
Naming
I observed that we had only limited freedom to name: The two points to the left (labeled
iM
andi
) are what people with more or less formality have calledlvalues
and the two points on the right (labeledm
andIm
) are what people with more or less formality have calledrvalues
. This must be reflected in our naming. That is, the left "leg" of theW
should have names related tolvalue
and the right "leg" of theW
should have names related torvalue.
I note that this whole discussion/problem arise from the introduction of rvalue references and move semantics. These notions simply don’t exist in Strachey’s world consisting of justrvalues
andlvalues
. Someone observed that the ideas that
- Every
value
is either anlvalue
or anrvalue
- An
lvalue
is not anrvalue
and anrvalue
is not anlvalue
are deeply embedded in our consciousness, very useful properties, and traces of this dichotomy can be found all over the draft standard. We all agreed that we ought to preserve those properties (and make them precise). This further constrained our naming choices. I observed that the standard library wording uses
rvalue
to meanm
(the generalization), so that to preserve the expectation and text of the standard library the right-hand bottom point of theW
should be namedrvalue.
This led to a focused discussion of naming. First, we needed to decide on
lvalue.
Shouldlvalue
meaniM
or the generalizationi
? Led by Doug Gregor, we listed the places in the core language wording where the wordlvalue
was qualified to mean the one or the other. A list was made and in most cases and in the most tricky/brittle textlvalue
currently meansiM
. This is the classical meaning of lvalue because "in the old days" nothing was moved;move
is a novel notion inC++0x
. Also, naming the topleft point of theW
lvalue
gives us the property that every value is anlvalue
or anrvalue
, but not both.So, the top left point of the
W
islvalue
and the bottom right point isrvalue.
What does that make the bottom left and top right points? The bottom left point is a generalization of the classical lvalue, allowing for move. So it is ageneralized lvalue.
We named itglvalue.
You can quibble about the abbreviation, but (I think) not with the logic. We assumed that in serious usegeneralized lvalue
would somehow be abbreviated anyway, so we had better do it immediately (or risk confusion). The top right point of the W is less general than the bottom right (now, as ever, calledrvalue
). That point represent the original pure notion of an object you can move from because it cannot be referred to again (except by a destructor). I liked the phrasespecialized rvalue
in contrast togeneralized lvalue
butpure rvalue
abbreviated toprvalue
won out (and probably rightly so). So, the left leg of the W islvalue
andglvalue
and the right leg isprvalue
andrvalue.
Incidentally, every value is either a glvalue or a prvalue, but not both.This leaves the top middle of the
W
:im
; that is, values that have identity and can be moved. We really don’t have anything that guides us to a good name for those esoteric beasts. They are important to people working with the (draft) standard text, but are unlikely to become a household name. We didn’t find any real constraints on the naming to guide us, so we picked ‘x’ for the center, the unknown, the strange, the xpert only, or even x-rated.
You seem to be unnecessarily setting properties on your ComboBox
. You can remove the DisplayMemberPath
and SelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedSalesPeriod}"
IsSynchronizedWithCurrentItem="True"/>
Furthermore, it is pointless using your displayPeriod
property, as the WPF Framework would call the ToString
method automatically for objects that it needs to display that don't have a DataTemplate
set up for them explicitly.
UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod
property and also your SalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:
public class SalesPeriodV
{
private int month, year;
public int Year
{
get { return year; }
set
{
if (year != value)
{
year = value;
NotifyPropertyChanged("Year");
}
}
}
public int Month
{
get { return month; }
set
{
if (month != value)
{
month = value;
NotifyPropertyChanged("Month");
}
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
}
Then I added two properties into the view model:
private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
get { return salesPeriods; }
set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
Then initialised the collection with your values:
SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );
And then data bound only these two properties to a ComboBox
:
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString
method without your displayPeriod
property. Hopefully, you can work out your mistakes from this code example.
All the solutions above mentioned will work only when you have a local webserver running on your local host. If you want to achieve this with out a web server, you might need to put in some manual effort by uploading the JSON file using file upload control. The browser will not offer this functionality with out a local server because of security risks.
You can parse the uploaded file with out a local webserver as well. Here is the sample code I have achieved a solution similar problem.
<div id="content">
<input type="file" name="inputfile" id="inputfile">
<br>
<h2>
<pre id="output"></pre>
</h2>
</div>
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function () {
let fileReader = new FileReader();
fileReader.onload = function () {
let parsedJSON = JSON.parse(fileReader.result);
console.log(parsedJSON);
// your code to consume the json
}
fileReader.readAsText(this.files[0]);
})
</script>
In my case I want to read a local JSON file and show it in a html file on my desktop, that's all I have to do.
Note: Don't try to automate the file uploading using JavaScript, even that's also not allowed due the same security restrictions imposed by browsers.
Your function prototype states your function will return a char. Thus, you can't return a string in your function.
Do not use list as variable name. You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
Got it to work go to the local.properties file under your build.gradle files to find out the PATH to your SDK, from the SDK location go into the platform-tools folder and look and see if you have adb.exe. If not go to http://adbshell.com/downloads and download ADB KITS. Copy the zip folder's contents into the platform-tools folder and re-make your project.
I didn't need to update the PATH in the Extended Controls Settings section on the emulator, I left Use detected ADB location settings on. Hope this makes this faster for you !
((Number) intOrLongOrSomewhat).longValue()
You can even add the size of the terms (indexed terms). Have a look at Elastic Search: how to see the indexed data
Extra answer: if you are doing this from chroot.
You need source of random numbers to be able to establish secure connection to pypi.
On linux, you can bind-mount host dev to chroot dev:
mount --bind /dev /path-to-chroot/dev
This answer may be late reply but it will be useful for seeing this topic in future.
The features of .NET framework 4.5 can be seen in the following link.
To summarize:
Installation
.NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.
- Support for Arrays Larger than 2 GB on 64-bit Platforms
- Enhanced Background Server Garbage Collection
- Support for Timeouts in Regular Expression Evaluations
- Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
- Simple Default Culture Definition for an Application Domain
- Internationalized Domain Names in Windows 8 Apps
You can use gdb for this like objdump.
This excerpt is taken from http://sources.redhat.com/gdb/current/onlinedocs/gdb_9.html#SEC64
Here is an example showing mixed source+assembly for Intel x86:
(gdb) disas /m main Dump of assembler code for function main: 5 { 0x08048330 : push %ebp 0x08048331 : mov %esp,%ebp 0x08048333 : sub $0x8,%esp 0x08048336 : and $0xfffffff0,%esp 0x08048339 : sub $0x10,%esp 6 printf ("Hello.\n"); 0x0804833c : movl $0x8048440,(%esp) 0x08048343 : call 0x8048284 7 return 0; 8 } 0x08048348 : mov $0x0,%eax 0x0804834d : leave 0x0804834e : ret End of assembler dump.
The reason might be because the IPython module is not in your PYTHONPATH.
If you donwload IPython and then do python setup.py install
The setup doesn't add the module IPython to your python path. You might want to add it to your PYTHONPATH manually. It should work after you do :
export PYTHONPATH=/pathtoIPython:$PYTHONPATH
Add this line in your .bashrc or .profile to make it permanent.
If we think about today, accepted answer is too old. As we know that we have many new libraries which can help you to make this types of application.
You should learn following topics that will helps you surely:
SyncAdapter: The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.
Realm: Realm is a mobile database: a replacement for SQLite & Core Data.
Retrofit Type-safe HTTP client for Android and Java by Square, Inc. Must Learn a-smart-way-to-use-retrofit
And your sync logic for database like: How to sync SQLite database on Android phone with MySQL database on server?
Best Luck to all new learner. :)
First of all, you need to make sure you're producing the correct number of *
symbols. We need to produce 1, 3, 5 et cetera instead of 1, 2, 3. This can be fixed by modifying the counter variables:
for (int i=1; i<10; i += 2)
{
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
As you can see, this causes i
to start at 1
and increase by 2
at each step as long is it is smaller than 10
(i.e., 1
, 3
, 5
, 7
, 9
). This gives us the correct number of *
symbols. We then need to fix the indentation level per line. This can be done as follows:
for (int i=1; i<10; i += 2)
{
for (int k=0; k < (4 - i / 2); k++)
{
System.out.print(" ");
}
for (int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println("");
}
Before printing the *
symbols we print some spaces and the number of spaces varies depending on the line that we are on. That is what the for loop with the k
variable is for. We can see that k
iterates over the values 4
, 3
, 2
, 1
and 0
when ì
is 1
,3
, 5
, 7
and 9
. This is what we want because the higher in the triangle we are, the more spaces we need to place. The further we get down the triangle, we less spaces we need and the last line of the triangle does not even need spaces at all.
Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.
This is very simple beacuse i have created a couple lines of code that will do this for you
So set a variable as msg and then use this code. it popup in a VBS message box.
CODE:
@echo off
echo %msg% >vbs.txt
copy vbs.txt vbs.vbs
del vbs.txt
start vbs.vbs
timeout /t 1
del vbs.vbs
cls
This is just something i came up with it should work for most of your message needs and it also works with Spaces unlike some batch scripts
The Question should be: Print Odd-Even Numbers simultaneously Using Threads
public class EvenOdd1 {
static boolean flag = true;
public static void main(String[] args) {
Runnable odd = () -> {
for (int i = 1; i <= 10;) {
if (EvenOddPrinter.flag) {
System.out.println(Thread.currentThread().getName() + " " + i);
i += 2;
EvenOddPrinter.flag = !EvenOddPrinter.flag;
}//if
}//for
};
Runnable even = () -> {
for (int i = 2; i <= 10;) {
if (!EvenOddPrinter.flag) {
System.out.println(Thread.currentThread().getName() + " " + i);
i += 2;
EvenOddPrinter.flag = !EvenOddPrinter.flag;
}
}
};
Thread t1 = new Thread(odd, "Odd");
Thread t2 = new Thread(even, "Even");
t1.start();
t2.start();
}
}
/*The output =>
Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Odd 9
Even 10
*/
Probably not what you want, but since you mentioned Node.js: I could not find a good tool to preview GitHub Flavored Markdown documentation on my local drive before committing them to GitHub, so today I created one, based on Node.js: https://github.com/ypocat/gfms
So perhaps you can reuse the showdown.js from it for your Wiki, if your question is still actual. If not, maybe other people facing the same problem as I did will find (just as I did) this question and this answer to it.
Use the following command:
in.nextLine();
right after
System.out.println("Invalid input. Please Try Again.");
System.out.println();
or after the following curly bracket (where your comment regarding it, is).
This command advances the scanner to the next line (when reading from a file or string, this simply reads the next line), thus essentially flushing it, in this case. It clears the buffer and readies the scanner for a new input. It can, preferably, be used for clearing the current buffer when a user has entered an invalid input (such as a letter when asked for a number).
Documentation of the method can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
Hope this helps!
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
This worked for me on after updating python3.7 on ubuntu18.04
cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so
If you want to validate your date(YYYY-MM-DD)
along with the comparison it will be use full for you...
function validateDate()
{
var newDate = new Date();
var presentDate = newDate.getDate();
var presentMonth = newDate.getMonth();
var presentYear = newDate.getFullYear();
var dateOfBirthVal = document.forms[0].dateOfBirth.value;
if (dateOfBirthVal == null)
return false;
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
dateValues = dateOfBirthVal.match(validatePattern);
if (dateValues == null)
{
alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
return false;
}
var birthYear = dateValues[1];
birthMonth = dateValues[3];
birthDate= dateValues[5];
if ((birthMonth < 1) || (birthMonth > 12))
{
alert("Invalid date")
return false;
}
else if ((birthDate < 1) || (birthDate> 31))
{
alert("Invalid date")
return false;
}
else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31)
{
alert("Invalid date")
return false;
}
else if (birthMonth == 2){
var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
if (birthDate> 29 || (birthDate ==29 && !isleap))
{
alert("Invalid date")
return false;
}
}
else if((birthYear>presentYear)||(birthYear+70<presentYear))
{
alert("Invalid date")
return false;
}
else if(birthYear==presentYear)
{
if(birthMonth>presentMonth+1)
{
alert("Invalid date")
return false;
}
else if(birthMonth==presentMonth+1)
{
if(birthDate>presentDate)
{
alert("Invalid date")
return false;
}
}
}
return true;
}
Try removing the .
before the .bmp
(it isn't matching BMP
as expected). As you can see from the error, the save_handler
is upper-casing the format
you provided and then looking for a match in SAVE
. However the corresponding key in that object is BMP
(instead of .BMP
).
I don't know a great deal about PIL
, but from some quick searching around it seems that it is a problem with the mode
of the image. Changing the definition of j
to:
j = Image.fromarray(b, mode='RGB')
Seemed to work for me (however note that I have very little knowledge of PIL
, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode
, I used this page - hopefully one of the choices there will work for you.
Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered
class name to elements I want to center:
.contentCentered {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.contentCentered::before {_x000D_
content: '';_x000D_
display: inline-block;_x000D_
height: 100%; _x000D_
vertical-align: middle;_x000D_
margin-right: -.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
.contentCentered > * {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div class="contentCentered">_x000D_
<div>_x000D_
<h1>Some text</h1>_x000D_
<p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
shoulder, said—"Did ye see anything looking like men going_x000D_
towards that ship a while ago?"</p>_x000D_
</div>_x000D_
</div>
_x000D_
Forked CodePen: http://codepen.io/dougli/pen/Eeysg
If you use unicorn.
Look at top
on your server. Unicorn likely is using 100% of CPU right now.
There are several reasons of this problem.
You should check your HTTP requests, some of their can be very hard.
Check unicorn's version. May be you've updated it recently, and something was broken.
Netbeans has great C and C++ support. Some people complain that it's bloated and slow, but I've been using it almost exclusively for personal projects and love it. The code assistance feature is one of the best I've seen.
You might want to try using something like this
curl = require('node-curl');
curl('www.google.com', function(err) {
console.info(this.status);
console.info('-----');
console.info(this.body);
console.info('-----');
console.info(this.info('SIZE_DOWNLOAD'));
});
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.
According to the page:
This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.
Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.
lsof -P | grep ':3000' | awk '{print $2}'
This will give you just the pid, tested on MacOS.
I tried to test this and it did not seem to work but I'm curious why Apple is using it. I was just on https://linkmaker.itunes.apple.com/us/ and noticed in the generated code it provides if you select the 'Large Button' radio button, they are using an inline media query.
<a href="#"
target="itunes_store"
style="
display:inline-block;
overflow:hidden;
background:url(#.png) no-repeat;
width:135px;
height:40px;
@media only screen{
background-image:url(#);
}
"></a>
note: added line-breaks for readability, original generated code is minified
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {_x000D_
totalCost.value = checkbox.checked ? 10 : calculate();_x000D_
}_x000D_
_x000D_
function calculate() {_x000D_
return other.value*2;_x000D_
}
_x000D_
input { display: block}
_x000D_
Checkbox: <input type="checkbox" onclick="change(this)"/>_x000D_
Total cost: <input id="totalCost" type="number" value=5 />_x000D_
Other: <input id="other" type="number" value=7 />
_x000D_
Just extract the ISO file to hard drive and it will work.
Here is a manual way to invalidate the cache for all files on CloudFront via AWS
Wildcards can only be used in the ServerAlias
rather than the ServerName
. Something which had me stumped.
For your use case, the following should suffice
<VirtualHost *:80>
ServerAlias *.example.com
VirtualDocumentRoot /var/www/%1/
</VirtualHost>
A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code
Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.
The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.
The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.
One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.
You don't need anything fancy: the following contains a new line (two, actually):
<summary>Tootsie roll tiramisu macaroon wafer carrot cake.
Danish topping sugar plum tart bonbon caramels cake.
</summary>
The question is, why isn't this newline having the desired effect: and that's a question about what the recipient of the XML is actually doing with it. For example, if the recipient is translating it to HTML and the HTML is being displayed in the browser, then the newline will be converted to a space by the browser. You need to tell us something about the processing pipeline.
In add_argument()
, type
is just a callable object that receives string and returns option value.
import ast
def arg_as_list(s):
v = ast.literal_eval(s)
if type(v) is not list:
raise argparse.ArgumentTypeError("Argument \"%s\" is not a list" % (s))
return v
def foo():
parser.add_argument("--list", type=arg_as_list, default=[],
help="List of values")
This will allow to:
$ ./tool --list "[1,2,3,4]"
Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.
So if you use sed to return some HTML templates (on a server), use double backslash instead of single:
var htmlTemplate = "<div style=\\"color:green;\\"></div>";
The difference is that ActionEvent
is fired when the action is performed on the JCheckBox
that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox
is selected or deselected.
For instance, if JCheckBox c1
(say) is added to a ButtonGroup
. Changing the state of other JCheckBoxes
in the ButtonGroup
will not fire an ActionEvent
on other JCheckBox
, instead an ItemEvent
is fired.
Final words: An ItemEvent
is fired even when the user deselects a check box by selecting another JCheckBox
(when in a ButtonGroup
), however ActionEvent
is not generated like that instead ActionEvent
only listens whether an action is performed on the JCheckBox
(to which the ActionListener
is registered only) or not. It does not know about ButtonGroup
and all other selection/deselection stuff.
For anyone who must work with an older version of MySQL (pre-5.0 ish) you are unable to do sub-queries for this type of query. Here is the solution I was able to do and it seemed to work great.
SELECT MAX(d.id), d2.*, CONCAT(title,' ',forename,' ',surname) AS name
FROM customer AS c
LEFT JOIN customer_data as d ON c.customer_id=d.customer_id
LEFT JOIN customer_data as d2 ON d.id=d2.id
WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
GROUP BY c.customer_id LIMIT 10, 20;
Essentially this is finding the max id of your data table joining it to the customer then joining the data table to the max id found. The reason for this is because selecting the max of a group doesn't guarantee that the rest of the data matches with the id unless you join it back onto itself.
I haven't tested this on newer versions of MySQL but it works on 4.0.30.
One follow up to this. I had installed SQL Server 2014 with only Windows Authentication. After enabling Mixed Mode, I couldn't log in with a SQL user and got the same error message as the original poster. I verified that named pipes were enabled but still couldn't log in after several restarts. Using 127.0.0.1 instead of the hostname allowed me to log in, but interestingly, required a password reset prompt on first login:
Once I reset the password the account worked. What's odd, is I specifically disabled password policy and expiration.
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
If you have date as a datetime.datetime
(or a datetime.date
) instance and want to combine it via a time from a datetime.time
instance, then you can use the classmethod datetime.datetime.combine
:
import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
use dnsmasq
pretending you're using a debian-based dist(ubuntu,mint..), check if it's installed with
(sudo) systemctl status dnsmasq
If it is just disabled start it with
(sudo) systemctl start dnsmasq
If you have to install it, write
(sudo) apt-get install dnsmasq
To define domains to resolve edit /etc/dnsmasq.conf
like this
address=/example.com/127.0.0.1
to resolve *.example.com
! You need to reload dnsmasq to take effect for the changes !
systemctl reload dnsmasq
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
# cases
$x = null
$x = ''
$x = ' '
# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
After some messing around this is how I got the desired look (at least in the emulator) and it keeps the ripple effect.
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/tab_selector"
app:tabIconTint="@drawable/tab_selector"
app:tabIconTintMode="src_atop"
app:tabTextColor="@drawable/tab_selector" />
And the @drawable/tab_selector
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/colorPrimary" android:drawable="@color/colorPrimaryDark" android:state_selected="true" />
<item android:color="@color/colorPrimaryDark" android:drawable="@color/colorPrimary" />
</selector>
FYI: This is what the emulator showed before I added the color
argument to @drawable/tab_selector
:
Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:
row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)
df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.
See this Link
HTML
<div id="products"></div>
JS
var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
};
var name = $("<div/>",{"text":someone.name,"class":"name"
});
var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);
Not sure but I think this was a question not about the height of a 'multiple' type of select element but a drop-down type of select element. I have come across times when the drop-down looks squashed and does not show clearly the selected value. Undoubtedly it has to do with CSS style info in use on the page. The only way to stop it is either change the CSS (which would likely affect the whole page or parts of it in ways you don't want affected) or use style info in the select element itself to override the CSS that's clobbering it. Example:
<select name="myselect" id="myselect" style="font-size:15px; height:30px">
<option value="someval">somedescr</option>
...
</select>
Hope this helps.
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu[5]
You can also pad a string to the required length using Guava's Strings.padEnd(String input, int minLength, char padding)
If your image view is dynamic, the answer containing getLayout will fail with null-exception.
In that case the correct way is:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);
Use JQuery or so, as CSS is a general misconception (the countless questions and discussions here about simple design goals show that).
It is not possible with CSS to do what you seem to wish: image shall have width of 100%, but if this width results in a height that is too large, a max-height shall apply - and of course the correct proportions shall be preserved.
If you don't have to come back on the page with keeping form's value, you can do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:field="${client.name}"/>
It's some kind of magic :
If you matter keeping you form's input values, like a back on the page with an user input mistake, then you will have to do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:name="name"
th:value="${form.name != null} ? ${form.name} : ${client.name}"/>
That means :
Without having to map your client bean to your form bean. And it works because once you submitted the form, the value arn't null but "" (empty)
If you want list of database
SELECT datname FROM pg_database WHERE datistemplate = false;
If you want list of tables from current pg installation of all databases
SELECT table_schema,table_name FROM information_schema.tables
ORDER BY table_schema,table_name;
return
in function return execution back to caller and exit
from function terminates the program.
in main
function return 0
or exit(0)
are same but if you write exit(0)
in different function then you program will exit from that position.
returning different values like return 1
or return -1
means that program is returning error .
When exit(0)
is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.
Unless you have a specific reason not to, just use a normal object. Object properties in JavaScript can be referenced using hashtable-style syntax:
var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";
Both foo
and bar
elements can now then be referenced as:
hashtable['foo'];
hashtable['bar'];
// Or
hashtable.foo;
hashtable.bar;
Of course this does mean your keys have to be strings. If they're not strings they are converted internally to strings, so it may still work. Your mileage may vary.
I started using the new ASP.NET Chart control a few days ago, and it's absolutely amazing in its capabilities.
EDIT: This is obviously only if you are using ASP.NET. Not sure about WinForms.
If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.
private void textBox_Enter(object sender, EventArgs e)
{
ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
}
private void textBox_Leave(object sender, EventArgs e)
{
ActiveForm.AcceptButton = null; // remove "return" button behavior
}
In the spirit of being complete, the answers that instruct you to use Guid.NewGuid()
are correct.
In addressing your subsequent edit, you'll need to post the code for your RequestObject
class. I'm suspecting that your guid property is not marked as a DataMember
, and thus is not being serialized over the wire. Since default(Guid)
is the same as new Guid()
(i.e. all 0
's), this would explain the behavior you're seeing.
you can easily
There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.
Here's an example that uses the protocol of the current request in an action method:
var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);
HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:
<span>
Copy
<a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a>
and post it anywhere on the internet!
</span>
In Go 1.10+ there is strings.Builder
, here.
A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use.
It's almost the same with bytes.Buffer
.
package main
import (
"strings"
"fmt"
)
func main() {
// ZERO-VALUE:
//
// It's ready to use from the get-go.
// You don't need to initialize it.
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteString("a")
}
fmt.Println(sb.String())
}
Click to see this on the playground.
StringBuilder's methods are being implemented with the existing interfaces in mind. So that you can switch to the new Builder type easily in your code.
It can only grow or reset.
It has a copyCheck mechanism built-in that prevents accidentially copying it:
func (b *Builder) copyCheck() { ... }
In bytes.Buffer
, one can access the underlying bytes like this: (*Buffer).Bytes()
.
strings.Builder
prevents this problem.io.Reader
etc.bytes.Buffer.Reset()
rewinds and reuses the underlying buffer whereas the strings.Builder.Reset()
does not, it detaches the buffer.
Check out its source code for more details, here.
The accepted answer calls the draw
function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:
datatable.clear().rows.add(newData).draw();
In Bootstrap 4 it was renamed to .rounded-circle
Usage :
<div class="col-xs-7">
<img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>
See migration docs from bootstrap.
Some of the Answers seems a little bit off IMO Here is my take circa 2016
<add key="ClientsFilePath" value="filepath"/>
Make sure System.Configuration
is referenced.
Question is asking for value of an appsettings key
Which most certainly SHOULD be
string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]
//yourKeyValue should hold on the HEAP "filepath"
Here is a twist in which you can group together values ( not for this question)
var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];
emails
will be value of Environment Key + "_Emails"
example : [email protected];[email protected];
Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9
This can be done using the unique function in ufp.path module.
import ufp.path
ufp.path.unique('./test.ext')
if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.
Strings are immutable, so using
public string GenerateString()
{
return
"abc" +
"def";
}
will slow you performance - each of those values is a string literal which must be concatenated at runtime - bad news if you reuse the method/property/whatever alot...
Store your string literals in resources is a good idea...
public string GenerateString()
{
return Resources.MyString;
}
That way it is localisable and the code is tidy (although performance is pretty terrible).
pushd
is a bash
enhancement to the POSIX-specified Bourne Shell. pushd
cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd
command might do the chdir(2)
call and then start a new shell, but ... it wouldn't be very usable.) pushd
is a shell builtin, just like cd
.
So, either change your script to start with #!/bin/bash
or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash
.
Copying an audio file to the sd card of the emulator and selecting it via media player as the default ringtone does indeed solve the problem.
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/>
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
var myDelegate = function(message) {
alert(message);
}
myButton.onclick = function() {
myDelegate(myMessage);
};
</script>
Try this - I slightly changed the above answers:
var getAttributes = function(attribute) {
var allElements = document.getElementsByTagName('*'),
allElementsLen = allElements.length,
curElement,
i,
results = [];
for(i = 0; i < allElementsLen; i += 1) {
curElement = allElements[i];
if(curElement.getAttribute(attribute)) {
results.push(curElement);
}
}
return results;
};
Then,
getAttributes('data-foo');
You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?
After I read that this particular issue was fixed in the roslyn compiler (see this issue at GitHub), I updated Visual Studio from version 15.0.x to 15.3.1. It works like a charm now.
delete all frameworks from Embedded Binaries and re-add it
In my view, the best way to do this is via an API so that you do not add a large and complex dependency into your app that runs unmanaged code, that needs to be frequently updated.
Here is a simple way to do this, which is free for 800 requests/month:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();
var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
input.Html = "<b>Hello, world!</b>";
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertWebHtmlToPdf(input, callback);
With the above approach you can also install the API on-premises or on your own infrastructure if you prefer.
I was able to make this work by creating a named range in the current sheet that referred to the table I wanted to reference in the other sheet.
Technically, and from Comintern's accepted workaround,
I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents.
I.e. Sheets("Zeroes").Cells.Delete
Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:
Sub DeleteCells ()
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
End Sub
Or if you prefer to respect the Calculation State Excel is currently in:
Sub DeleteCells ()
Dim SaveCalcState
SaveCalcState = Application.Calculation
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = SaveCalcState
End Sub
Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but
Conditional formatting IS deleted, as is Entire Row formatting.
(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)
Since this is a popular question, I would like to add that in Elasticsearch version 2 things changed a bit.
Instead of filtered
query, one should use bool
query in the top level.
If you don't care about the score of must
parts, then put those parts into filter
key. No scoring means faster search. Also, Elasticsearch will automatically figure out, whether to cache them, etc. must_not
is equally valid for caching.
Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html
Also, mind that "gte": "now"
cannot be cached, because of millisecond granularity. Use two ranges in a must
clause: one with now/1h
and another with now
so that the first can be cached for a while and the second for precise filtering accelerated on a smaller result set.
It looks like Google actively frowns on using IP-to-location mapping:
https://developers.google.com/maps/articles/geolocation?hl=en
That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:
Use defaultdict
from collections import defaultdict
a = {}
a = defaultdict(lambda:0,a)
a["anything"] # => 0
This is very useful for case like this,where default values for every key is set as 0:
results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
for k,v in results.iteritems():
a['count'] += v['count']
a['pass_count'] += v['pass_count']
Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:
http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial
You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.
Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.
This is the code:
f = open(filename, 'w')
f.write("hello\talex")
The \t
inside the string is the escape sequence for the horizontal tabulation.
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
Here my regexp for validate string:
^\"([^\"\\]*|\\(["\\\/bfnrt]{1}|u[a-f0-9]{4}))*\"$
Was written usign original syntax diagramm.
JavaScript can modify array items inside a function (it is passed as a reference to the object/array).
function makeAllPretty(items) {
for (var x = 0; x < myArray.length; x++){
// Do stuff to the array
items[x] = makePretty(items[x]);
}
}
myArray = new Array(var1, var2, var3);
makeAllPretty(myArray);
Here's another example:
function inc(items) {
for (let i=0; i < items.length; i++) {
items[i]++;
}
}
let values = [1,2,3];
inc(values);
console.log(values);
// Prints [2,3,4]
I got same error while running JAVA command. To resolve this, I moved the java path as the first entry in the path, and it resolved the issue. Please have look at this screenshot for reference:
This works for me:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
<item
android:state_selected="true"
android:drawable="@drawable/info_icon_solid_with_shadow" />
<item
android:drawable="@drawable/info_icon_outline_with_shadow" />
</selector>
And then in java:
//assign the image in code (or you can do this in your layout xml with the src attribute)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));
//set the click listener
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View button) {
//Set the button's appearance
button.setSelected(!button.isSelected());
if (button.isSelected()) {
//Handle selected state change
} else {
//Handle de-select state change
}
}
});
For smooth transition you can also mention animation time:
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">
This will give you a list.
List<Card> cardsList = Arrays.asList(hand);
If you want an arraylist, you can do
ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
let co = require('co');
const sleep = ms => new Promise(res => setTimeout(res, ms));
co(function*() {
console.log('Welcome to My Console,');
yield sleep(3000);
console.log('Blah blah blah blah extra-blah');
});
This code above is the side effect of the solving Javascript's asynchronous callback hell problem. This is also the reason I think that makes Javascript a useful language in the backend. Actually this is the most exciting improvement introduced to modern Javascript in my opinion. To fully understand how it works, how generator works needs to be fully understood. The function
keyword followed by a *
is called a generator function in modern Javascript. The npm package co
provided a runner function to run a generator.
Essentially generator function provided a way to pause the execution of a function with yield
keyword, at the same time, yield
in a generator function made it possible to exchange information between inside the generator and the caller. This provided a mechanism for the caller to extract data from a promise
from an asynchronous call and to pass the resolved data back to the generator. Effectively, it makes an asynchronous call synchronous.
RMI is based on Proxy.
Should be possible to cite one for most of the 23 patterns in GoF:
I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.
To follow up on Rachel's answer.
Here's two ways in which you can get Mouse Screen Coordinates in WPF.
1.Using Windows Forms. Add a reference to System.Windows.Forms
public static Point GetMousePositionWindowsForms()
{
var point = Control.MousePosition;
return new Point(point.X, point.Y);
}
2.Using Win32
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
var w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
subprocess.Popen
creates a process and opens pipes and stuff. What you are doing is:
sudo -S
mypass
mount -t vboxsf myfolder /home/myuser/myfolder
which is obviously not going to work. You need to pass the arguments to Popen. If you look at its documentation, you will notice that the first argument is actually a list of the arguments.
I have tried accepted answer but it isn't seems working on my end and I don't know how the accepted answer suppose to work.
$('#modalId').on('hidden.bs.modal', function () {
$(this).remove();
})
This is working perfectly fine on my side. BS Version > 3
You can use re.escape():
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_
).
Question is good, but the answer is : it depends on that.
If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.
But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.
Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:
$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
mb_substr( $str, -7, null, 'UTF-8') ;
good question, i try so many way, but it is curry and boring, until i find shortcut.
only two shortcut, but i think safari is more convenient for that.
You can:
click file-> new ->create project from existing project
select your original file, eg. solution 1 and input the new file name solution 2
change the project name in the new solution 2
This Worked for me:
Go to Developer Options on your device and disable the "USB Debugging" and after sometime enable it again.
With Java 8, Steve's answer can become
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(
invocation -> {
Object[] args = invocation.getArguments();
return args[0];
});
assertEquals("someString", mock.myFunction("someString"));
assertEquals("anotherString", mock.myFunction("anotherString"));
}
EDIT: Even shorter:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(
invocation -> invocation.getArgument(0));
assertEquals("someString", mock.myFunction("someString"));
assertEquals("anotherString", mock.myFunction("anotherString"));
}
This fixed the same issue for me:
My eclipse is installed in /usr/local/bin/eclipse
1) Changed permission for eclipse from root to owner: sudo chown -R $USER eclipse
2) Right click on project/Maven
right click on Update Maven
select Force update maven project
Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.
@GitaarLAB and @Jukka elaborate that <xmp>
tag is obsolete, but still the best. When I use it like this
<xmp>
<div>Lorem ipsum</div>
<p>Hello</p>
</xmp>
then the first EOL is inserted in the code, and it looks awful.
It can be solved by removing that EOL
<xmp><div>Lorem ipsum</div>
<p>Hello</p>
</xmp>
but then it looks bad in the source. I used to solve it with wrapping <div>
, but recently I figured out a nice CSS3 rule, I hope it also helps somebody:
xmp { margin: 5px 0; padding: 0 5px 5px 5px; background: #CCC; }
xmp:before { content: ""; display: block; height: 1em; margin: 0 -5px -2em -5px; }
This looks better.
nc -l 8000
Where 8000 is the port number. If the port is free, it will start a server that you can close easily. If it isn't it will throw an error:
nc: Address already in use
I found it too easy for multiple requests.
step1: define a variable at top of page:
xhrPool = []; // no need to use **var**
step2: set beforeSend in all ajax requests:
$.ajax({
...
beforeSend: function (jqXHR, settings) {
xhrPool.push(jqXHR);
},
...
step3: use it whereever you required:
$.each(xhrPool, function(idx, jqXHR) {
jqXHR.abort();
});
The "==" operator returns true only if the two references pointing to the same object in memory. The equals() method on the other hand returns true based on the contents of the object.
Example:
String personalLoan = new String("cheap personal loans");
String homeLoan = new String("cheap personal loans");
//since two strings are different object result should be false
boolean result = personalLoan == homeLoan;
System.out.println("Comparing two strings with == operator: " + result);
//since strings contains same content , equals() should return true
result = personalLoan.equals(homeLoan);
System.out.println("Comparing two Strings with same content using equals method: " + result);
homeLoan = personalLoan;
//since both homeLoan and personalLoan reference variable are pointing to same object
//"==" should return true
result = (personalLoan == homeLoan);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);
Output: Comparing two strings with == operator: false Comparing two Strings with same content using equals method: true Comparing two references pointing to same String with == operator: true
You can also get more details from the link: http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html?m=1
advanced way using regex
import re
text = "hello ,world!"
replaces = {"hello": "hi", "world":" 2020", "!":"."}
regex = re.sub("|".join(replaces.keys()), lambda match: replaces[match.string[match.start():match.end()]], text)
print(regex)
I developed my own function that convert human readable memory size to different sizes.
function convertMemorySize($strval, string $to_unit = 'b')
{
$strval = strtolower(str_replace(' ', '', $strval));
$val = floatval($strval);
$to_unit = strtolower(trim($to_unit))[0];
$from_unit = str_replace($val, '', $strval);
$from_unit = empty($from_unit) ? 'b' : trim($from_unit)[0];
$units = 'kmgtph'; // (k)ilobyte, (m)egabyte, (g)igabyte and so on...
// Convert to bytes
if ($from_unit !== 'b')
$val *= 1024 ** (strpos($units, $from_unit) + 1);
// Convert to unit
if ($to_unit !== 'b')
$val /= 1024 ** (strpos($units, $to_unit) + 1);
return $val;
}
convertMemorySize('1024Kb', 'Mb'); // 1
convertMemorySize('1024', 'k') // 1
convertMemorySize('5.2Mb', 'b') // 5452595.2
convertMemorySize('10 kilobytes', 'bytes') // 10240
convertMemorySize(2048, 'k') // By default convert from bytes, result is 2
This function accepts any memory size abbreviation like "Megabyte, MB, Mb, mb, m, kilobyte, K, KB, b, Terabyte, T...." so it is typo safe.
If you were resizing before uploading I just found out this http://www.plupload.com/
It does all the magic for you in any imaginable method.
Unfortunately HTML5 resize only is supported with Mozilla browser, but you can redirect other browsers to Flash and Silverlight.
I just tried it and it worked with my android!
I was using http://swfupload.org/ in flash, it does the job very well, but the resize size is very small. (cannot remember the limit) and does not go back to html4 when flash is not available.
Android studio also create the apk file on every time compile the program, just go to your workspace folder and find app->build->outputs-> then you can see the apk file.
In mysqli_query(first parameter should be connection,your sql statement) so
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');
but best practice is
$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);
Recursively add subfolders,
for i in `find . -name "*.java" -type f`; do
echo "$i"
done
I had a file named mysql.py in the folder. That's why it gave an error because it tried to call it in the import process.
import mysql.connector
I solved the problem by changing the file name.
Since MongoDB version 3.2 you can use updateMany():
> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
Because it's more common to call range(0, 10)
which returns [0,1,2,3,4,5,6,7,8,9]
which contains 10 elements which equals len(range(0, 10))
. Remember that programmers prefer 0-based indexing.
Also, consider the following common code snippet:
for i in range(len(li)):
pass
Could you see that if range()
went up to exactly len(li)
that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++)
over for(int i = 0; i <= 9; i++)
.
If you are calling range with a start of 1 frequently, you might want to define your own function:
>>> def range1(start, end):
... return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Additional Version of PHP can be installed directly from the APP (using MAMP PRO v5 at least).
Here's how (All Steps):
MAMP PRO --> Preferences --> click [Check Now] to check for updates (even if you have automatic updates enabled!) --> click [Show PHP Versions] --> Install as needed!
Step-by-step screenshots:
fscanf
- "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned."
So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF
.
You should check for EOF when you call fscanf
, not check the array slot for EOF.
Easiest way of doing is: (In Linux/Ububuntu e.t.c)
Go to tomcat bin directory:
cd /opt/tomcat8.5/bin
create new file under bin directory "setenv.sh" and save below mention entries in it.
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx2048m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"
and issue command:
./catalina.sh run
In your catalina log file you can see entry like this:
INFO [main] VersionLoggerListener.log Command line argument: -Xms512m
INFO [main] VersionLoggerListener.log Command line argument: -Xmx2048m
INFO [main] VersionLoggerListener.log Command line argument: -XX:MaxPermSize=256m
Which confirms that above changes took place.
Also, the value of "Xms512m" and "-Xmx2048m" can be modified accordingly in the setenv.sh file.
Startup of tomcat could be done in two steps as well. cd /opt/tomcat8.5/bin
Step #1
run ./setenv.sh
Step #2
./startup.sh
If you're using systemd edit:
/usr/lib/systemd/system/tomcat8.service
and set
Environment=CATALINA_OPTS="-Xms512M -Xmx2048M -XX:MaxPermSize=256m"
There are 3 options, you probably want #3
1. This will keep the local file for you, but will delete it for anyone else when they pull.
git rm --cached <file-name>
or git rm -r --cached <folder-name>
2. This is for optimization, like a folder with a large number of files, e.g. SDKs that probably won't ever change. It tells git to stop checking that huge folder every time for changes, locally, since it won't have any. The assume-unchanged
index will be reset and file(s) overwritten if there are upstream changes to the file/folder (when you pull).
git update-index --assume-unchanged <path-name>
3. This is to tell git you want your own independent version of the file or folder. For instance, you don't want to overwrite (or delete) production/staging config files.
git update-index --skip-worktree <path-name>
It's important to know that git update-index
will not propagate with git, and each user will have to run it independently.
Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
Perhaps the easiest is to use position: absolute
to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.
css:
<style>
body {
margin: 0 0 20px;
}
.footer {
position: absolute;
bottom: 0;
height: 20px;
background: #f0f0f0;
width: 100%;
}
</style>
Here is the html main content.
<div class="footer"> Here is the footer. </div>
Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.
Assuming the original branch is named master
, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master
updates into your local master
:
git fetch origin
git checkout master
git merge origin/master
To switch to your branch, just do
git checkout branch1
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);
If someone is still facing the issue on their local machine(Ubuntu) then try below command:
sudo chmod 666 /var/run/docker.sock
Here is the complete solution for directly integrating a report-viewer control (as well as any asp.net server side control) in an MVC .aspx view, which will also work on a report with multiple pages (unlike Adrian Toman's answer) and with AsyncRendering set to true, (based on "Pro ASP.NET MVC Framework" by Steve Sanderson).
What one needs to do is basically:
Add a form with runat = "server"
Add the control, (for report-viewer controls it can also sometimes work even with AsyncRendering="True" but not always, so check in your specific case)
Add server side scripting by using script tags with runat = "server"
Override the Page_Init event with the code shown below, to enable the use of PostBack and Viewstate
Here is a demonstration:
<form ID="form1" runat="server">
<rsweb:ReportViewer ID="ReportViewer1" runat="server" />
</form>
<script runat="server">
protected void Page_Init(object sender, EventArgs e)
{
Context.Handler = Page;
}
//Other code needed for the report viewer here
</script>
It is of course recommended to fully utilize the MVC approach, by preparing all needed data in the controller, and then passing it to the view via the ViewModel.
This will allow reuse of the View!
However this is only said for data this is needed for every post back, or even if they are required only for initialization if it is not data intensive, and the data also has not to be dependent on the PostBack and ViewState values.
However even data intensive can sometimes be encapsulated into a lambda expression and then passed to the view to be called there.
A couple of notes though:
Do a row div.
Like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
</div>_x000D_
</div>
_x000D_
Just upload your image to the repository root, and link to the filename without any path, like so:
![Screenshot](screenshot.png)
E = exponent expression, simply means power(10, n) or 10 ^ n
F = fraction expression, default 6 digits precision
G = gerneral expression, somehow smart to show the number in a concise way (but really?)
See the below example,
The code
void main(int argc, char* argv[])
{
double a = 4.5;
printf("=>>>> below is the example for printf 4.5\n");
printf("%%e %e\n",a);
printf("%%f %f\n",a);
printf("%%g %g\n",a);
printf("%%E %E\n",a);
printf("%%F %F\n",a);
printf("%%G %G\n",a);
double b = 1.79e308;
printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
printf("%%e %e\n",b);
printf("%%f %f\n",b);
printf("%%g %g\n",b);
printf("%%E %E\n",b);
printf("%%F %F\n",b);
printf("%%G %G\n",b);
double d = 2.25074e-308;
printf("=>>>> below is the example for printf 2.25074*10^-308\n");
printf("%%e %e\n",d);
printf("%%f %f\n",d);
printf("%%g %g\n",d);
printf("%%E %E\n",d);
printf("%%F %F\n",d);
printf("%%G %G\n",d);
}
The output
=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
It ought to be implemented in msysgit, but there are two downsides:
I did a quick search and there is work being actively done on this, see issue 224.
Adding processData: false
to the $.ajax
options will fix this issue.
Maybe you could use:
select last_name+', '+first_name
from user_mstr
where ',' + @user_id_list + ',' like '%,' + convert(nvarchar, user_id) + ',%'
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
You're almost there. As you can see, the onItemSelected
will give you a position
parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position)
.
Example:
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
This will put a message on screen, with the selected item printed by its toString() method.
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
use market://
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + my_packagename));
You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?
this.Controls.Add(dataGridView1);
By the way the code is a bit confused
String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql = "SELECT Clients FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
conn.Open();
DataSet ds = new DataSet();
DataGridView dataGridView1 = new DataGridView();
using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
// Of course, before addint the datagrid to the hosting form you need to
// set position, location and other useful properties.
// Why don't you create the DataGrid with the designer and use that instance instead?
this.Controls.Add(dataGridView1);
}
}
EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as
SELECT field_names_list FROM _tablename_
so the correct syntax to use for retrieving all the clients data is
string sql = "SELECT * FROM Clients";
where the *
means -> all the fields present in the table
As described in the above solution you should enable the user interaction first and add the tap gesture
this code has been tested using
yourlabel.isUserInteractionEnabled = true
yourlabel.addGestureRecognizer(UITapGestureRecognizer(){
//TODO
})
Range("A1").value = Environ("Username")
This is better than Application.Username
, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.
Application Username
is the name of the User set in Excel > Tools > Options Environ("Username")
is the name you registered for Windows; see Control Panel >SystemYou can combine data from the two tables, order by goals highest first and then choose the top two like this:
MySQL
select *
from (
select * from tblMadrid
union all
select * from tblBarcelona
) alldata
order by goals desc
limit 0,2;
SQL Server
select top 2 *
from (
select * from tblMadrid
union all
select * from tblBarcelona
) alldata
order by goals desc;
If you only want Messi and Ronaldo
select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'
To ensure that messi is at the top of the result, you can do something like this:
select * from (
select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'
) stars
order by name;
I had the same problem and I fixed it by using the
(int)Math.Round(myNumber, 0)
Use component scanning as given below, if com.project.action.PasswordHintAction
is annotated with stereotype annotations
<context:component-scan base-package="com.project.action"/>
EDIT
I see your problem, in PasswordHintActionTest
you are autowiring PasswordHintAction
. But you did not create bean configuration for PasswordHintAction
to autowire. Add one of stereotype annotation(@Component, @Service, @Controller
) to PasswordHintAction
like
@Component
public class PasswordHintAction extends BaseAction {
private static final long serialVersionUID = -4037514607101222025L;
private String username;
or create xml configuration in applicationcontext.xml
like
<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />
SWIFT 3
To add a gradient layer on your view
Bind your view outlet
@IBOutlet var YOURVIEW : UIView!
Define the CAGradientLayer()
var gradient = CAGradientLayer()
Here is the code you have to write in your viewDidLoad
YOURVIEW.layoutIfNeeded()
gradient.startPoint = CGPoint(x: CGFloat(0), y: CGFloat(1))
gradient.endPoint = CGPoint(x: CGFloat(1), y: CGFloat(0))
gradient.frame = YOURVIEW.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.green.cgColor]
gradient.colors = [ UIColor(red: 255.0/255.0, green: 56.0/255.0, blue: 224.0/255.0, alpha: 1.0).cgColor,UIColor(red: 86.0/255.0, green: 13.0/255.0, blue: 232.0/255.0, alpha: 1.0).cgColor,UIColor(red: 16.0/255.0, green: 173.0/255.0, blue: 245.0/255.0, alpha: 1.0).cgColor]
gradient.locations = [0.0 ,0.6 ,1.0]
YOURVIEW.layer.insertSublayer(gradient, at: 0)
There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);
BOOST_FOREACH(std::string const& token, tokens)
{
std::cout << "<" << *tok_iter << "> " << "\n";
}
Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:
function datetime()
{
return date( 'Y-m-d H:i:s', time());
}
echo datetime(); // display example: 2011-12-31 07:55:13
Or a bit more advance to match the question.
function datetime($date_string = false)
{
if (!$date_string)
{
$date_string = time();
}
return date("Y-m-d H:i:s", strtotime($date_string));
}
Here is an example that sets the image path dynamically (image located somewhere on disc rather than build as resource):
if (File.Exists(imagePath))
{
// Create image element to set as icon on the menu element
Image icon = new Image();
BitmapImage bmImage = new BitmapImage();
bmImage.BeginInit();
bmImage.UriSource = new Uri(imagePath, UriKind.Absolute);
bmImage.EndInit();
icon.Source = bmImage;
icon.MaxWidth = 25;
item.Icon = icon;
}
First thought, you would think that the Icon property can only contain an image. But it can actually contain anything! I discovered this by accident when I programmatically tried to set the Image
property directly to a string with the path to an image. The result was that it did not show the image, but the actual text of the path!
This leads to an alternative to not have to make an image for the icon, but use text with a symbol font instead to display a simple "icon". The following example uses the Wingdings font which contains a "floppydisk" symbol. This symbol is really the character <
, which has special meaning in XAML, so we have to use the encoded version <
instead. This works like a dream! The following shows a floppydisk symbol as an icon on the menu item:
<MenuItem Name="mnuFileSave" Header="Save" Command="ApplicationCommands.Save">
<MenuItem.Icon>
<Label VerticalAlignment="Center" HorizontalAlignment="Center" FontFamily="Wingdings"><</Label>
</MenuItem.Icon>
</MenuItem>
In my opinion, it is not possible for the like button (and I hope it is not possible).
But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.
Build.SERIAL
is the simplest way to go, although not entirely reliable as it can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.
There are several ways to get that number depending on the device's manufacturer and Android version, so I decided to compile every possible solution I could found in a single gist. Here's a simplified version of it :
public static String getSerialNumber() {
String serialNumber;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serialNumber = (String) get.invoke(c, "gsm.sn1");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ril.serialnumber");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "ro.serialno");
if (serialNumber.equals(""))
serialNumber = (String) get.invoke(c, "sys.serialnumber");
if (serialNumber.equals(""))
serialNumber = Build.SERIAL;
// If none of the methods above worked
if (serialNumber.equals(""))
serialNumber = null;
} catch (Exception e) {
e.printStackTrace();
serialNumber = null;
}
return serialNumber;
}
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
The other answers didn't work for me, I guess something wrong happens between ButterKnife and 3.0.0 alpha5.
However, I found that when I annotated any one sentence, either BUtterKnife or 3.0.0 alpha5, it works normally.
So, you should just avoid the duplication or conflict.
Because you initialize myList with 'new', the list itself will never be null.
But it can be filled with 'null' values.
In that case .Count > 0
and .Any()
will be true. You can check this with the .All(s => s == null)
var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))
You should always include the table name in the SQL query when dealing with associations.
Indeed if another table has the user_id
column and you join both tables, you will have an ambiguous column name in the SQL query (i.e. troubles).
So, in your example:
GroupUser.where("groups_users.user_id != ?", me)
Or a bit more verbose:
GroupUser.where("#{table_name}.user_id IS NOT ?", me)
Note that if you are using a hash, you don't need to worry about that because Rails takes care of it for you:
GroupUser.where(user: me)
In Rails 4, as said by @dr4k3, the query method not
has been added:
GroupUser.where.not(user: me)
Am I doing that right, as far as iterating through the Arraylist goes?
No: by calling iterator
twice in each iteration, you're getting new iterators all the time.
The easiest way to write this loop is using the for-each construct:
for (String s : arrayList)
if (s.equals(value))
// ...
As for
java.lang.ArrayIndexOutOfBoundsException: -1
You just tried to get element number -1
from an array. Counting starts at zero.
As you want to exclude both words, you need a conjuction:
^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$
Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.
Try this:
HTML:
<div id="container">
<div id="content">
// Content here
</div>
</div>
CSS:
#container{
height: 100%;
width: 100%;
overflow: hidden;
}
#content{
width: 100%;
height: 99%;
overflow: auto;
padding-right: 15px;
}
html, body{
height: 99%;
overflow:hidden;
}
Tested on FF and Safari.
instanceof
test should pass in order for the assignment to go through.
In your example it results
Object[] a = new Object[1];
boolean isIntegerArr = a instanceof Integer[]
sysout
of the above line, it would return false;
(Arrays.asList(a)).toArray(c);
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
// Request parameters.
const params = {
'visualFeatures': 'Categories,Description,Adult,Faces',
'maxCandidates': '2',
'details': 'Celebrities,Landmarks',
'language': 'en'
};
const options = {
uri: uriBase,
qs: params,
body: fs.readFileSync(./my_local_image_path.jpg),
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, ' ');
body = JSON.parse(body);
if (body.code) // err
{
console.log("AZURE: " + body.message)
}
console.log('Response\n' + jsonString);
Promise - Provide a single future value. Not lazy . Not cancel-able. It will either reject or resolve.
Observable - Provide multiple future value. Lazy . Cancel-able . It provide other methods live map,filter,reduce.
Construct some data
df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )
Extract exact matches:
subset(df, date==3)
name date
1 John 3
Extract matches in range:
subset(df, date>4 & date<6)
name date
2 Adam 5
The following syntax produces identical results:
df[df$date>4 & df$date<6, ]
name date
2 Adam 5
Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:
So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.
With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.
Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).
When asked, I tend to say:
Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).
If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.
Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.
Well, if you can use Tcl/Tk in your environment, you probably should write a TCL script and use that. You might also look at wish.
This is quite simple:
my_data
is a before defined structure type.
So you want to declare an my_data
-array of some elements, as you would do with
char a[] = { 'a', 'b', 'c', 'd' };
So the array would have 4 elements and you initialise them as
a[0] = 'a', a[1] = 'b', a[1] = 'c', a[1] ='d';
This is called a designated initializer (as i remember right).
and it just indicates that data has to be of type my_dat
and has to be an array that needs to store so many my_data structures that there is a structure with each type member name Peter, James, John and Mike.
You can try settings of code::block
, there is a complier..., then you select in C mode.
s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]
dic={}
for i in range(0,len(s),10):
dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)
for keys,values in dic.items():
print(keys)
print(values)
Output:
(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]
Clearly you need a factory pattern!
KeyFactory keyFactory = new KeyFactory();
KeyObj keyObj = keyFactory.getKeyObj(wParam);
keyObj.doStuff();
class VK_F11 extends KeyObj {
boolean val;
public void doStuff() {
val = !val;
}
}
class VK_F12 extends KeyObj {
boolean val;
public void doStuff() {
val = !val;
}
}
class KeyFactory {
public KeyObj getKeyObj(int param) {
switch(param) {
case VK_F11:
return new VK_F11();
case VK_F12:
return new VK_F12();
}
throw new KeyNotFoundException("Key " + param + " was not found!");
}
}
:D
</sarcasm>
A non-open source approach is: PDF Creator Pilot which provides more language options including C++, C#, Delphi, ASP, ASP.NET, VB, VB.NET, VBScript, PHP and Python