text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringclasses 91
values | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
|---|---|---|---|---|---|
What’s New in Astropy 3.2?¶
Overview¶
Astropy 3.2 is a major release that adds significant new functionality since the 3.1.x series of releases.
In particular, this release includes:
New Sub-package for Time Series
New SI/CODATA 2018 Constants
Additions and changes to Ecliptic Transformations
Table performance improvements and change in meta handling
Table I/O integration of pandas I/O functions for ASCII tables
Improved help on Table read() and write() methods
In addition to these major changes, Astropy v3.2 includes a large number of smaller improvements and bug fixes, which are described in the Full Changelog. By the numbers:
551 issues have been closed since v3.1
256 pull requests have been merged since v3.1
67 distinct people have contributed to this release, 24 of which are first time contributors to Astropy
New Sub-package for Time Series¶
Astropy 3.2 includes a new experimental sub-package: Time series (astropy.timeseries). Currently this sub-package provides classes to represent sampled and binned time series as well as some basic analysis tasks.
The following example shows a simple example of reading in a Kepler light curve, finding the period of the transits, and folding the light curve.
import numpy as np import matplotlib.pyplot as plt from astropy.timeseries import TimeSeries from astropy.utils.data import get_pkg_data_filename from astropy import units as u filename = get_pkg_data_filename('timeseries/kplr010666592-2009131110544_slc.fits') ts = TimeSeries.read(filename, format='kepler.fits') plt.figure(figsize=(10,5)) # Show the original light curve plt.subplot(1, 2, 1) plt.plot(ts.time.mjd, ts['sap_flux'], 'k.', markersize=1) plt.xlabel('Barycentric Modified Julian Date') plt.ylabel('SAP Flux (e-/s)') # Find the transit period and fold the light curve from astropy.timeseries import BoxLeastSquares periodogram = BoxLeastSquares.from_timeseries(ts, 'sap_flux') results = periodogram.autopower(0.2 * u.day) best = np.argmax(results.power) ts_folded = ts.fold(period=results.period[best], midpoint_epoch=results.transit_time[best]) # Show the folded light curve plt.subplot(1, 2, 2) plt.plot(ts_folded.time.jd, ts_folded['sap_flux'], 'k.', markersize=1) plt.xlabel('Time relative to epoch (days)') plt.gca().get_yaxis().set_visible(False)
This sub-package should be considered experimental and subject to API changes in the future if user feedback calls for it.
Note that the
LombScargle and
BoxLeastSquares periodogram classes have now moved
from the
astropy.stats to the
astropy.timeseries module. These
classes have been improved and can now take absolute times as an alternative
to relative times.
Finally, the
LombScargle class now includes a
model_parameters() method to make it easier to
compute the best-fit parameters for a given frequency, as well as
design_matrix() and
offset() to inspect the model further.
New SI/CODATA 2018 Constants¶
The new redefinition of the SI system and its base units came into force on 2019-05-20. Accompanying that redefinition was a new set of physical constants (CODATA2018). Astropy v3.2 contains these new CODATA2018 phsical constants, which contain in particular quite different uncertainties due to the redefinition. E.g.,:
>>> from astropy import constants >>> from astropy.constants import codata2018 >>> constants.m_e <<class 'astropy.constants.codata2014.CODATA2014'> >>> constants.m_e.uncertainty, codata2018.m_e.uncertainty (1.1e-38, 2.8e-40) >>> constants.mu0.uncertainty, codata2018.mu0.uncertainty (0.0, 1.9e-16)
While CODATA2018 will not be the default in astropy v3.2, a future version will transition to the new values (with units similarly matched where relevant).
For more background on the values and measurements of these constants see the CODATA web site, or see the wikipedia article on the new SI system for a more accessible description of the revised system.
Additions and changes to Ecliptic Transformations¶
The Ecliptic frames and associated transformations in
astropy.coordinates
have been updated to correctly reflect the “True” and “Mean” terminology. In
this release there are now
*MeanEcliptic frames now which include precession but
not nutation, and
*TrueEcliptic frames which also include nutation.
Additionally, new frames (
HeliocentricEclipticIAU76 and
CustomBarycentricEcliptic) have been added with specific
conventions used in particular fields. For more details on the motivation behind
these changes, see PR #8394
and the associated discussion.
As an example, this shows the evolution of the ecliptic origin for the true and mean barycentric ecliptic frames over the course of a year:
import numpy as np import matplotlib.pyplot as plt from astropy.visualization import quantity_support quantity_support() from astropy import units as u from astropy.time import Time from astropy.coordinates import BarycentricMeanEcliptic, BarycentricTrueEcliptic, ICRS t = Time('J2018') + np.linspace(-1, 0, 1000)*u.year bme_origin = BarycentricMeanEcliptic([0]*len(t)*u.deg, [0]*len(t)*u.deg, equinox=t) bte_origin = BarycentricTrueEcliptic([0]*len(t)*u.deg, [0]*len(t)*u.deg, equinox=t) im = bme_origin.transform_to(ICRS()) it = bte_origin.transform_to(ICRS()) plt.plot(t.jyear, im.ra.wrap_at(180*u.deg), label='BarycentricMeanEcliptic') plt.plot(t.jyear, it.ra.wrap_at(180*u.deg), label='BarycentricTrueEcliptic') plt.xlabel('Julian year') plt.ylabel('ICRS R.A. of ecliptic origin [{}]'.format(im.ra.unit)) plt.legend(loc=0)
Note that this change may break some usage of the previous
*TrueEcliptic
frames, as in the last few versions these had a behavior more akin to “mean”
ecliptic frames. In many cases it will be sufficient to simply replace this
usage with the appropriate
*MeanEcliptic frames.
Default time scale for “J2000”-style strings changed to TT¶
In past versions of astropy, times specified as “equinox-style strings” - e.g.,
Time('J2000') - defaulted to the UTC scale. This includes default equinoxes
for FK4/FK5 coordinates. To be more consistent with commonly-accepted usage of
terms like “J2000”, this strings now default to the TT time scale. This
difference is on the order of 60 seconds, which for e.g. equinox precession is
typically an extremely small differences (picoarcseconds). However, if the
previous behavior is needed, the easiest work-around is to change any use of
e.g.,
'J2000' to
Time('J2000', scale='utc').
Table performance improvements and change in meta handling¶
A number of changes were made to the
Table implementation to
improve performance:
Table row access speed is improved by a factor of 2 to 3.
Table slicing speed is improved by a factor of 2.
Getting the table length is now faster by a factor of 3 to 10.
Writing a table with masked columns to ECSV is now faster (depending on how many masked columns there are).
Manipulating tables and columns that have substantial meta-data stored in the
metaattributes (e.g. some FITS tables) is now faster. This was done by removing unnecessary deep copies of the meta-data and in some cases converting to a shallow copy. See the change log for #8404 for details about the related API changes in table initialization and slicing.
Table I/O integration of pandas I/O functions for ASCII tables¶
Astropy
Table now supports the ability to read or write tables
using some of the
I/O methods
available within pandas. This interface provides
convenient wrappers for the pandas read/write
functions for the following formats: CSV, JSON, HTML, and fixed width.
For very large tables these may provide better performance than the built-in
astropy table ASCII read and write functions. For details see Pandas.
Support for ASDF readers/writers for Table class¶
If the asdf package is installed,
Table can be read from and written to
ASDF files, using e.g.:
from astropy.table import Table tab = Table.read('data.asdf')
and:
tab.write('table.asdf')
Improved help on Table read() and write() methods¶
Starting from astropy version 3.2 is now possible to get detailed help for
read and
write which is
specific to a particular data format. This includes information about
the format and method keywords that apply only for that format. The
following examples illustrate the new syntax for getting help:
>>> Table.read.help('ascii.latex') >>> Table.read.help('ascii') >>> Table.read.help('fits') >>> Table.write.help('hdf5') >>> Table.write.help('csv') >>> Table.read.help() # Generic read help
Deprecated/Renamed/Removed functionality¶
The bundled version of the six package in
the
astropy.extern.six sub-package is now deprecated. You should instead
make use of the six package directly.
Composition of model classes (as opposed to instances) is now deprecated and will be removed in the v4.0 release.
The
LombScargle and
BoxLeastSquares periodogram classes have now moved
from the
astropy.stats to the
astropy.timeseries module.
The previously deprecated
astropy.tests.pytest_plugins module has been
removed. The variables
PYTEST_HEADER_MODULES and
TESTED_VERSIONS should
instead be imported from
astropy.tests.plugins.display, and the function
enable_deprecations_as_exceptions should be imported from
astropy.tests.helper.
Full change log¶
To see a detailed list of all changes in version v3.2, including changes in API, please see the Full Changelog.
|
http://docs.astropy.org/en/stable/whatsnew/3.2.html
|
CC-MAIN-2019-26
|
refinedweb
| 1,453
| 51.14
|
Axios is an external library used in making promised based HTTP requests. One of the coolest things that comes with it people hardly talk about is the axios timeout functionality.
This article simply explains how to use the axios timeout functionality to optimize/minimize the time it takes to make HTTP requests.
So when you make HTTP requests to a web server there would be sometimes when a response would be delayed for no reason. You may want to avoid this unnecessary delay with axios timeout object. What the axios timeout does is that it would abort a request when it takes longer time. Since the time is measured in milliseconds, whatever seconds set to it is how long the request takes and once it exceeds that times, the request is aborted. The default time is set to 0 which indicates no timeout. This gives you some form of control over making requests.
Here is how you can globally set timeout with axios.
import axios from axios;
axios.defaults.timeout === 3000;
One important thing to note is that axios timeout is response/request bound and not connection bound. What this means is that if there is no network on the clients side or for some reason the IP address is not found or may be the domain name is not found, axios timeout isn't going to work. But if for instance the server your making a request to is taking too long to load, then axios time out will work.
You can also set axios timeout this way
import axios from axios ; axios .post(‘url’, {timeout: 3000}) .then((res) => console.log(res)) .catch((err) => console.log(err))
In this case if your response takes more than 3 seconds, it goes into the catch block.
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/kelahkelah/axios-defaults-timeout-3c7
|
CC-MAIN-2022-27
|
refinedweb
| 297
| 71.34
|
Layout callback in custom view classes
@omz, I know you are busy, but I have sort of mentioned this before, but not as a topic on its own. But the layout callback method when you create a custom class that inherits from ui.View, gets 2 callbacks when a view loads. I normally have to make another class member and store the last screen size to avoid a single redundant call to layout. Maybe there is a good reason it's called twice and a better way to avoid executing the layout code twice.
It's not a big deal, but worth mentioning for 1.6 if it is indeed a redundant call.
Or the old MadonnaView workaround...
import ui class MadonnaView(ui.View): def __init__(self): self.first_time = True def layout(self): if self.first_time: self.first_time = False return
Thanks @ccc. Was really about pointing that it happens so it could be addressed in 1.6 if it has not been already.
I still use the screen size to check, just in case double calls made in different circumstances.
- MartinPacker
phuket, do you have a simple example that calls layout twice? i tried with the most basic example, and thst doesn't happen...
perhaps you are setting the frame after you instantiate (rather than within the constructor)?
- MartinPacker
@JonB, you are right. I wasn't setting the h,w in the init method, but inside the layout method. And maybe this was my misunderstanding about presenting a sheet. I thought I had to do that before to be device independent. If I presented a view using sheet, I had no idea what the resulting size would be on different screen sizes. ( I remember a long time ago, I asked about this here).
I can see with 1.6, you can look at the screen size and determine what you want your view size to be before you call your class to present. Of course, this is only an issue with presenting with a sheet. As you can control the exact size of your sheet view with 1.6, no reason why the size of the view can't be set in the init method.
I hope what I said is correct. My mind is spinning. I did so many tests. But if the view is sized in the init method, no double layout calls. Makes sense.
|
https://forum.omz-software.com/topic/2094/layout-callback-in-custom-view-classes/?
|
CC-MAIN-2021-49
|
refinedweb
| 397
| 85.18
|
Yesterday, I wrote the first of a series of posts on skills related to effective Silverlight programming; specifically an introduction to LINQ. Today, with that material fresh, I’d like to take a giant leap forward and consider a number of advanced techniques that are common with Linq programmers.
To do this, I’ve extended and modified the Presidents class we were using, and created a second related class PresidentDetail. For convenience, I’ve placed both in the file President.cs,
using System; using System.Collections.Generic; namespace LinqDemo2 { public class President { public string FirstName { get; set; } public string LastName { get; set; } public static List<President> GetPresidents() { List<President> presidents = new List<President> { new President() { FirstName = "George", LastName = "Washington" }, new President() { FirstName = "John", LastName = "Adams" }, new President() { FirstName = "Thomas", LastName = "Jefferson" }, new President() { FirstName = "James", LastName = "Madison" }, new President() { FirstName = "James", LastName = "Monroe" } }; return presidents; } } public class PresidentDetail { public string Name { get; set; } public string Portrait { get; set; } public string Birth { get; set; } public string Death { get; set; } public string PortraitPrefix =
""; public static List<PresidentDetail> GetPresidentialDetail() { List<PresidentDetail> details = new List<PresidentDetail> { new PresidentDetail() { Name = "George Washington", Birth = "Feb 22, 1732", Death = "Dec 14, 1799", Portrait = "georgewashington.jpg"}, new PresidentDetail() { Name = "John Adams", Birth = "Oct. 30, 1735", Death = "July 4, 1826", Portrait = "johnadams.jpg"}, new PresidentDetail() { Name = "Thomas Jefferson", Birth = "April 13 1743", Death = "July 4, 1826", Portrait = "thomasjefferson.jpg"}, new PresidentDetail() { Name = "James Madison", Birth = "March 15, 1761", Death = "June 28, 1836", Portrait = "jamesmadison.jpg"}, new PresidentDetail() { Name = "James Monroe", Birth = "April 28, 1758", Death = "July 4, 1831", Portrait = "jamesmonroe.jpg"} }; return details; } } }
As you can see, each class comes with a static method that returns a typed List populated with instances of the class.
Page.xaml once again contains a TextBlock to display the LinqStatement and a DataGrid to display the data from the selection. Our selection, however, will consist of data from the two tables, based on a join. We’ll join the two tables based on the combined FirstName and LastName in the President table matching the Name in the PresidentDetail table. This done, it is time to return the results, but that raises a problem, only one object can be returned.
You could write
select President
or you could write
select detail
but you are not allowed to write
Select President, Detail
One solution is to create a temporary new class that combines the two,
public class PresidentAndDetails
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get; set; }
public string Birth { get; set; }
public string Death { get; set; }
public string Portrait { get; set; }
}
You can then write your LinqStatement as follows:
PresidentAndDetails result =
from president in presidents
join detail in details on
string.Format("{0} {1}", president.FirstName,
president.LastName)
equals detail.Name
orderby president.LastName, detail.Birth
select new PresidentAndDetails { President = president, Detail = detail };
The syntax is somewhat similar to yesterday’s example except that we’ve added a join (based on the concatenation of first and last name from one object with the Name from the second) and, in the projection we’re actually instantiating a new object (of type PresidentAndDetails, and initializing the members.
Anonymous Types
It gives me the heebie jeebies to create a class, PresidentAndDetails just to have a return type for a single query and fortunately, C# 3 offers the alternative of anonymous types, which allow you to eschew creating the class before you need it, and allow you to avoid naming the class, but instead to create an implicit class whose type will be inferred by its use. Thus, the Linq statement above can be rewritten as follows (and the class PresidentAndDetails can be tossed):
var result =
from president in presidents
join detail in details on
string.Format("{0} {1}", president.FirstName,
president.LastName)
equals detail.Name
orderby president.LastName, detail.Birth
select new { President = president, Detail = detail }
The significant change is that we’ve gotten rid of the definition of the class, and the select statement does not name the class; it is inferred by the naming of the members. Notice also that the return value is now assigned to a variable whose type is identified as var; the actual type is assigned when the result is generated, but it is still strongly typed.
Lambda Expressions
All of this is good, but not terribly radical, but when we add lambda expressions, C# as we know it suddenly takes a dramatic change. There is much to say about lambda expressions but the essential thing to know is this: delegates are a way to indirectly refer to methods. Lambda expressions are a way to write short in-line substitutions for the methods that delegates refer to.
Lambda expressions consist of three parts:
- The Parameters
- The Operator ( => )
- The Result
Putting this together you might have a delegate that looks like this,
int someDelegate(int, int);
and you might use that delegate to refer to, for example, this method:
int myMethod(int a, int b)
{
return a * b;
}
You could also use that delegate to refer to this lambda expression:
(a,b) => a*b
You read this aloud “a and b goto a times b” or, to be more explicit, “given the parameters a and b, you will get back the product of a and b”
If you have more than one parameter, you must enclose them in parentheses and separate them by commas, and the types of the parameters and the return type must match the delegate that supports the lambda expression.
Lambda expressions are incredibly powerful and useful in many situations, not the least of which is LINQ. They can greatly simplify our Linq statement. For example, our most recent query now becomes,
var result = presidents.Join( details,
president => string.Format( "{0} {1}",
president.FirstName, president.LastName ),
detail => detail.Name,
( president, detail ) => new {
President = president, Detail = detail } )
.OrderBy( ca => ca.Detail.Name )
.ThenBy( ca => ca.Detail.Birth );
At first glance, this hardly looks like C# at all, but if we take it apart, it becomes much more reasonable.
var result indicates that the type of result will be decided at run time based on the strongly typed value inferred by running the query.
presidents.Join(details, the beginning of a join between the presidents object and the details object
president => string.Format( “{0} {1}, president.FirstName, president.LastName },
a lambda expression indicating that given a president object, you’ll get back the string consisting of the first name and the last name
detail => detail.Name similarly, a lambda expression indicating that given the detail object, you’ll get back the Name property of that object
put that together and your join says to join the president object and the detail object on the concatenated string and the Name property. If that matches, you now have the president object and the detail object and it is time to create your new anonymous type, which is what the next lambda expression does,
(president, detail) => new { President = president, Detail = detail }
read this as “given a president and a detail instance get back a new anonymous object initialized with two members. The president member is initialized to the value of the president object you have, the Detail member is initialized to the value of the detail object you have.
.OrderBy ( ca => ca.Detail.Name ) This order by phrase lends the anonymous object the temporary name ca (you can use any name). Within that temp object are two member objects, President and Detail and here you set Detail.Name as the property to order by.
Intellisense recognizes the anonymous type and its internal members,
of course, there’s nothing magical about the name “ca”….
Setting the Item Source
I’ll have to follow up, but for now it seems the ItemSource for the DataGrid is much happier with a non-anonymous type, thus I’ve modified the search and created a temporary class to hold the fields that I want to display,
public class PresResult
{
public string Name { get; set; }
public string Birth { get; set; }
public string Death { get; set; }
}
The search and assignment to ItemsSource looks like this,
var result = presidents.Join( details, president => string.Format( "{0} {1}", president.FirstName, president.LastName ), detail => detail.Name, ( president, detail ) => new PresResult() { Name = detail.Name, Birth = detail.Birth, Death = detail.Death } ) .OrderBy( ca => ca.Name ) .ThenBy( ca => ca.Birth ); Results.ItemsSource = result;
and the DataGrid in Page.xaml looks like this,
<Data:DataGrid x: <Data:DataGrid.Columns> <Data:DataGridTextColumn <Data:DataGridTextColumn <Data:DataGridTextColumn </Data:DataGrid.Columns> </Data:DataGrid>
When run, the application looks like this (red circle added)
It is pretty amazing that 3 of the first five presidents died on July 4, two within hours of one another.
For more on Linq I highly recommend Professional Linq by Joseph Rattz and of course the Linq Project.
|
http://jesseliberty.com/2008/11/18/silverlight-related-skills-%E2%80%93-post-2/
|
CC-MAIN-2021-31
|
refinedweb
| 1,466
| 50.87
|
#include <hallo.h> Chris Tillman wrote on Mon Apr 15, 2002 um 09:10:49PM: > +of the other CDs in the drive. CD's 2 through 5 have no selection > +menu but will boot different ``flavors'' depending on which CD-ROM is There is no menu. s/selection menu but will boot different ``flavors''/different kernel flavors that you can choice but will boot only one of the different ``flavors'' (using the old compatible boot method)/ Gruss/Regards, Eduard. -- Wenn ich's nicht compilieren kann, ist es nicht frei -- Joey in #debian.de -- To UNSUBSCRIBE, email to debian-cd-request@lists.debian.org with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
|
http://lists.debian.org/debian-cd/2002/04/msg00288.html
|
CC-MAIN-2013-48
|
refinedweb
| 114
| 63.7
|
IBM Cognos 10 Report Studio Cookbook, Second Edition — Save 50%
Over 100 recipes that will show you how to use IBM Cognos 10 Report Studio to build creative, stunning, and sophisticated reports with this book and ebook
(For more resources related to this topic, see here.)
In this article, we will cover some fundamental techniques that will be used in your day-to-day life as a Report Studio author. In each recipe, we will take a real-life example and see how it can be accomplished. At the end of the article, you will learn several concepts and ideas which you can mix-and-match to build complex reports. Though this article is called Report Authoring Basic Concepts, it is not a beginner's guide or a manual. It expects the following:
- You are familiar with the Report Studio environment, components, and terminologies
- You know how to add items on the report page and open various explorers and panes
- You can locate the properties window and know how to test run the report
Based on my personal experience, I will recommend this article to new developers with two days to two months of experience.
In the most raw terminology, a report is a bunch of rows and columns. The aim is to extract the right rows and columns from the database and present them to the users. The selection of columns drive what information is shown in the report, and the selection of rows narrow the report to a specific purpose and makes it meaningful. The selection of rows is controlled by filters. Report Studio provides three types of filtering: detail , summary , and slicer. Slicers are used with dimensional models.). In the first recipe of this article, we will cover when and why to use the detail and summary filters.
Once we get the correct set of rows by applying the filters, the next step is to present the rows in the most business-friendly manner. Grouping and ordering plays an important role in this. The second recipe will introduce you to the sorting technique for grouped reports.
With grouped reports, we often need to produce subtotals and totals. There are various types of aggregation possible. For example, average, total, count, and so on. Sometimes, the nature of business demands complex aggregation as well. In the third recipe, you will learn how to introduce aggregation without increasing the length of the query. You will also learn how to achieve different aggregation for subtotals and totals.
The fourth recipe will build upon the filtering concept you have learnt earlier. It will talk about implementing the if-then-elselogic in filters. Then we will see some techniques on data formatting, creating sections in a report, and hiding a column in a crosstab.
Finally, the eighth and last recipe of this article will show you how to use prompt's Use Value and Display Value properties to achieve better performing queries.
The examples used in all the recipes are based on the GO Data Warehouse (query) package that is supplied with IBM Cognos 10.1.1 installation. These recipe samples can be downloaded from the Packt Publishing website. They use the relational schema from the Sales and Marketing (query) / Sales (query) namespace.
The screenshots used throughout this article are taken from Cognos Version 10.1.1 and 10.2.
Summary filters and detail filters
Business owners need to see the sales quantity of their product lines to plan their strategy. They want to concentrate only on the highest selling product for each product line. They would also like the facility to select only those orders that are shipped in a particular month for this analysis.
In this recipe, we will create a list report with product line, product name, and quantity as columns. We will also create an optional filter on the Shipment Month Key. Also, we will apply correct filtering to bring up only the top selling product per product line.
Getting ready
Create a new list report based on the GO Data Warehouse (query) package. From the Sales (query) namespace, bring up Products / Product line , Products / Product , and Sales fact / Quantity as columns, the way it is shown in the following screenshot:
How to do it...
Here we want to create a list report that shows product line, product name, and quantity, and we want to create an optional filter on Shipment Month. The report should also bring up only the top selling product per product line. In order to achieve this, perform the following steps:
- We will start by adding the optional filter on Shipment Month. To do that, click anywhere on the list report on the Report page. Then, click on Filters from the toolbar.
- In the Filters dialog box, add a new detail filter. In the Create Filter screen, select Advanced and then click on OK as shown in the following screenshot:
- By selecting Advanced , we will be able to filter the data based on the fields that are not part of our list table like the Month Key in our example as you will see in the next step.
- Define the filter as follows:
[Sales (query)].[Time (ship date)].[Month key (ship date)] = ?ShipMonth?
- Validate the filter and then click on OK.
- Set the usage to Optional as shown in the following screenshot:
- Now we will add a filter to bring only the highest sold product per product line. To achieve this, select Product line and Product (press Ctrl and select the columns) and click on the group button from the toolbar. This will create a grouping as shown in the following screenshot:
- Now select the list and click on the filter button again and select Edit Filters . This time go to the Summary Filters tab and add a new filter. In the Create Filter screen, select Advanced and then click on OK.
- Define the filter as follows:
[Quantity] = maximum([Quantity] for [Product line]).
- Set usage to Required and set the scope to Product as shown in the following screenshot:
- Now run the report to test the functionality. You can enter 200401as the Month Key as that has data in the Cognos supplied sample.
How it works...
Report Studio allows you to define two types of filters. Both work at different levels of granularity and hence have different applications.
The detail filter
The detail filter works at the lowest level of granularity in a selected cluster of objects. In our example, this grain is the Sales entries stored in Sales fact . By putting a detail filter on Shipment Month, we are making sure that only those sales entries which fall within the selected month are pulled out.
The summary filter
In order to achieve the highest sold product per product line, we need to consider the aggregated sales quantity for the products.
If we put a detail filter on quantity, it will work at sales entry level. You can try putting a detail filter of [Quantity] = maximum([Quantity]for[Productline])and you will see that it gives incorrect results.
So, we need to put a summary filter here. In order to let the query engine know that we are interested in filtering sales aggregated at product level, we need to set the SCOPE to Product . This makes the query engine calculate [Quantity]at product level and then allows only those products where the value matches maximum([Quantity]for [Product line]).
There's more...
When you define multiple levels of grouping, you can easily change the scope of summary filters to decide the grain of filtering.
For example, if you need to show only those products whose sales are more than 1000 and only those product lines whose sales are more than 25000, you can quickly put two summary filters for code with the correct Scope setting.
Before/after aggregation
The detail filter can also be set to apply after aggregation (by changing the application property). However, I think this kills the logic of the detail filter. Also, there is no control on the grain at which the filter will apply. Hence, Cognos sets it to before aggregation by default, which is the most natural usage of the detail filter.
See also
- The Implementing if-then-else in filtering recipe
Sorting grouped values
The output of the previous recipe brings the right information back on the screen. It filters the rows correctly and shows the highest selling product per product line for the selected shipment month.
For better representation and to highlight the best-selling product lines, we need to sort the product lines in descending order of quantity.
Getting ready
Open the report created in the previous recipe in Cognos Report Studio for further amendments.
How to do it...
In the report created in the previous recipe, we managed to show data filtered by the shipment month. To improve the reports look and feel, we will sort the output to highlight the best-selling products. To start this, perform the following steps:
- Open the report in Cognos Report Studio.
- Select the Quantity column.
- Click on the Sort button from the toolbar and choose Sort Descending .
- Run the report to check if sorting is working. You will notice that sorting is not working.
- Now go back to Report Studio, select Quantity , and click on the Sort button again. This time choose Edit Layout Sorting under the Other Sort Options header.
- Expand the tree for Product line . Drag Quantity from Detail Sort List to Sort List under Product line as shown in the following screenshot:
- Click on the OK button and test the report. This time the rows are sorted in descending order of Quantity as required.
How it works...
The sort option by default works at the detailed level. This means the non-grouped items are sorted by the specified criteria within their own groups.
Here we want to sort the product lines that are grouped (not the detailed items). In order to sort the groups, we need to define a more advanced sorting using the Edit Layout Sorting options shown in this recipe.
There's more...
You can also define sorting for the whole list report from the Edit Layout Sorting dialog box. You can use different items and ordering for different groups and details.
You can also choose to sort certain groups by the data items that are not shown in the report. You need to bring only those items from source (model) to the query, and you will be able to pick it in the sorting dialog.
Aggregation and rollup aggregation
Business owners want to see the unit cost of every product. They also want the entries to be grouped by product line and see the highest unit cost for each product line. At the end of the report, they want to see the average unit cost for the whole range.
Getting ready
Create a simple list report with Products / Product line , Products / Product , and Sales fact / Unit cost as columns.
How to do it...
In this recipe, we want to examine how to aggregate the data and what is meant by rollup aggregation. Using the new report that you have created, this is how we are going to start this recipe:
- We will start by examining the Unit cost column. Click on this column and check the Aggregate Function property.
- Set this property to Average .
- Add grouping for Product line and Product by selecting those columns and then clicking on the GROUP button from the toolbar.
- Click on the Unit cost column and then click on the Summarize button from the toolbar. Select the Total option from the list.
- Now, again click on the Summarize button and choose the Average option as shown in the following screenshot:
- The previous step will create footers as shown in the following screenshot:
- Now delete the line with the <Average (Unit cost)> measure from Product line . Similarly, delete the line with the <Unit cost> measure from Summary . The report should look like the following screenshot:
- Click on the Unit cost column and change its Rollup Aggregate Function property to Maximum .
- Run the report to test it.
How it works...
In this recipe, we have seen two properties of the data items related to aggregation of the values.
The aggregation property
We first examined the aggregation property of unit cost and ensured that it was set to average. Remember that the unit cost here comes from the sales table. The grain of this table is sales entries or orders. This means there will be many entries for each product and their unit cost will repeat.
We want to show only one entry for each product and the unit cost needs to be rolled up correctly. The aggregation property determines what value is shown for unit cost when calculated at product level. If it is set to Total , it will wrongly add up the unit costs for each sales entry. Hence, we are setting it to Average . It can be set to Minimum or Maximum depending on business requirements.
The rollup aggregation property
In order to show the maximum unit cost for product type, we create an aggregate type of footer in step 4 and set the Rollup Aggregation to Maximum in step 8.
Here we could have directly selected Maximum from the Summarize drop-down toolbox. But that creates a new data item called Maximum (Unit Cost) . Instead, we ask Cognos to aggregate the number in the footer and drive the type by rollup aggregation property. This will reduce one data item in query subject and native SQL.
Multiple aggregation
We also need to show the overall average at the bottom. For this we have to create a new data item. Hence, we select unit cost and create an Average type of aggregation in step 5. This calculates the Average (Unit Cost) and places it on the product line and in the overall footer.
We then deleted the aggregations that are not required in step 7.
There's more...
The rollup aggregation of any item is important only when you create the aggregation of Aggregate type. When it is set to automatic, Cognos will decide the function based on the data type, which is not preferred.
It is good practice to always set the aggregation and rollup aggregation to a meaningful function rather than leaving them as automatic.
Implementing if-then-else in filters
Business owners want to see the sales quantity by order methods. However, for the Sales Visit type of order method, they want a facility to select the retailer.
Therefore, the report should show quantity by order methods. For the order methods other than Sales Visit , the report should consider all the retailers. For Sales Visit orders, it should filter on the selected retailer.
Getting ready
Create a simple list report with Order method / Order method type and Sales fact / Quantity as columns. Group by Order method to get one row per method and set the Aggregation for quantity to Total.
How to do it...
In this recipe, we need to create a filter that will be used to select the retailer if the Order method is Sales Visit . We will check what will happen if we use the if then elseconstruction inside the filter and how to overcome any problems with the following steps:
- Here we need to apply the retailer filter only if Order method is Sales Visit . So, we start by adding a new detail filter.
- Define the filter as follows:
if ([Order method type]='Sales visit') then
([Sales (query)].[Retailers].[Retailer name] = ?SalesVisitRetailer?).
- Validate the report. You will find multiple error messages.
- Now change the filter definition to:
(([Order method type]='Sales visit') and
([Sales (query)].[Retailers].[Retailer name] = ?SalesVisitRetailer?))
or ([Order method type]<>'Sales visit').
- Validate the report and it should be successful.
- Run the report and test the data.
How it works...
The if elseconstruct works fine when it is used in data expression. However, when we use it in a filter, Cognos often doesn't like it. It is strange because the filter is parsed and validated fine in the expression window and if elseis a valid construct.
The workaround for this problem is to use and...orclauses as shown in this recipe. The ifcondition and corresponding action item are joined with the andclause. The elsepart is taken care of by the oroperations with the reverse condition (in our example, Order Method <> 'Sales Visit').
There's more...
You need not use both andand orclauses all the time. The filtering in this example can also be achieved by this expression:
-([Sales (query)].[Retailers].[Retailer name] = ?SalesVisitRetailer?)
or ([Order method]<>'Sales visit')
Depending on the requirement, you need to use only or, only and, or the combination of and...or.
Make sure that you cover all the possibilities.
Formatting data – dates, numbers, and percentages
Virtually all reports involve displaying numerical information. It is very important to correctly format the numbers. In this recipe, we will create a report which formats dates, numbers, and percentages.
Date transformation and formatting are important in business reports. We will see two ways of displaying MONTH-YEAR from the Shipment Date Key. We will apply some formatting to a numeric column and will also configure a ratio to be displayed as a percentage.
Getting ready
Create a simple list report with Products / Product line , Products / Product type , and Time (ship date) / Date (ship date) as columns from the Sales (query) namespace.
Also, add Quantity , Unit price , and Unit cost from the Sales fact Query Subject .
Create a grouping on Product line and Product type .
How to do it...
In this recipe, we will check how to apply different formats on the data items.
- We will start by formatting the date column we have (check in Cognos 8).
- Select the Time (ship date) / Date (ship date) column and open Data Format from the Properties pane. Open the Data Format dialog box by clicking on the Browse button next to the Data Format property.
- Choose the format type Date , set Date Style to Medium , and set Display Days to No , as shown in the following screenshot:
- Now select the Quantity column in the report. Choose Data Format from property and open the dialog box again.
- This time select Number as the type and set the different properties as required. In our example recipe, we will set the Number of Decimal Points to 2 and use brackets () as a Negative Sign Symbol .
- Finally, we will add the ratio calculation to the report. For that, add a new query calculation and define it as follows:
[Unit price]/[Unit cost]
- Select this column and from the Data Format property dialog box, set it as Percent . Choose % as the Percentage Symbol and set the Number of Decimal Places to 2 . Also, set the Divide by Zero Characters to N/A .
- Run the report to test it.
How it works...
In this recipe, we are trying multiple techniques. We are checking how dates can be formatted to hide certain details (for example, days) and how to change the separator. Also, we have tested formatting options for numbers and the percentage.
Date format
Here, we started by setting the data format for the Month Year column as date for display purposes. We have set the display days to No as we only want to display MONTH-YEAR .
Numerical format
This is straightforward. The quantity column is displayed with two decimal points and negative numbers are displayed in brackets as this is what we have set the data formatting to.
The % margin
The ratio of unit price to unit cost is calculated by this item. Without formatting, the value is simply the result of a division operation. By setting the data format to Percent , Cognos automatically multiplies the ratio by 100 and displays it as a percentage.
There's more...
Please note that ideally the warehouse stores a calendar table with a Date type of field; this is made available through the Framework model. Also, we are assuming here that you need to see the shipment month. So, you want to see the MONTH-YEAR format only and we are hiding the days.
Using the data format options, you can do a lot of things. Assume that you don't have a date field in your data source but instead you have just a date key and you want to display the year and month as we did in our recipe. For that, create a new query calculation and use the following expression:
[Sales (query)].[Time (ship date)].[Day key (ship date)]/10000
Now set the Data Format to Number with the following options:
- Set the No of decimal places field to 2
- Set the Decimal separator to -
- Set Use thousand separator to No
Run the report to examine the output. You will see that we have gotten rid of the last two digits from the day key and the year part is separated from the month part by a hyphen. This is not truly converted to MONTH-YEAR , but conveys the information as shown in the following screenshot:
The advantage here is that the numerical operation is faster than converting the numerical key to DATE. We can use similar techniques to cosmetically achieve the required result.
Creating sections
Users want to see the details of orders. They would like to see the order number and then a small table showing the details (product name, promotion, quantity, and unit sell price) within each order.
Getting ready
Create a simple list report with Sales order / Order number , Products / Product , Sales fact / Quantity , and Sales fact / Unit sale price as columns.
How to do it...
Creating sections in a report is helpful to show a data item as the heading of a section. When you run the report, separate sections appear for each value. There is a way to reconstruct the report, and this is how to do it:
- Click on the Order number column. Hit the Section button on the toolbar as shown in the following screenshot:
- You will see that Report Studio automatically creates a header for Order number and moves it out of the list.
- Notice that the Order number field is now grouped as shown in the following screenshot:
- Run the report to test it.
How it works...
The information we are trying to show in this report can also be achieved by normal grouping on order number. That will bring all the related records together. We can also set an appropriate group/level span and sorting for better appearance.
However, in this recipe, I want to introduce another feature of Report Studio called section .
When you create a section on a column, Report Studio automatically does the following:
- It creates a new list object and moves the current report object (in our case, the existing list) inside that. This is report nesting. Both the inner and outer objects use the same query.
- It creates grouping on the column selected for section, which is Order number in this case. It also creates a group header for that item and removes it from the inner list.
- It formats the outer list appropriately. For example, hiding the column title.
There's more...
Some of the advantages of creating sections are as follows:
- As mentioned earlier, Report Studio does a lot of the work for you and gives you a report that looks more presentable. It makes the information more readable by clearly differentiating different entities; in our case, different orders. You will see mini-lists or tables, one for each Order number , as shown in the following screenshot:
- As the outer and inner queries are the same, there is no maintenance overhead.
Hiding columns in crosstabs
Users want to see sales figures by periods and order method. We need to show monthly sales and the yearly total sales. The year should be shown in the Year total row and not as a separate column.
Getting ready.
How to do it...
In this recipe, we want to hide the year from the crosstab and show it only in the report as a year total. To do this, perform the following steps:
- First, let's identify the issue. If you run the report as it is, you will notice that the year is shown to the left of the months. This consumes one extra column. Also, the yearly total doesn't have a user friendly title as shown in the following screenshot:
- We will start by updating the title for the yearly total row. Select the <Total(Month)> crosstab node. Change its Source Type to Data Item Value instead of Data Item Label and choose Year as the Data Item Value .
- Run the report and check that the yearly total is shown with the appropriate year as shown in the following screenshot:
- Now we need to get rid of the year column on the left edge. For that, click on the Unlock button in the Report Studio toolbar. The icon should change to an open lock (unlocked).
- Now select the <#Year#> text item (not the whole cell) and delete it.
- Select the empty crosstab node left after deleting the text. Change its Padding to 0 pixels in all directions.
- Run the report and you will see the following screenshot:
As you can see the year column on the left is now successfully hidden.
How it works...
When we want to hide an object in Report Studio, we often set its Box Type property to None . However, in this case, that was not possible.
Try setting the Box Type of the year column to None and run the report. It will look like the following screenshot:
As you can see, the cells have shifted to the left leaving the titles out of sync. This is most often the problem when Report Studio creates some merged cells (in our case, for the aggregations).
The solution to this is to format the column in such a way that it is hidden in the report as we have seen in this recipe.
There's more...
This solution works best in HTML output. The Excel output still has a column on the left with no data in it.
You might need to define the background color and bordering as well so as to blend the empty column with either the page background on the left or the month column on the right.
Prompts – display value versus use value
In order to achieve the best performance with our queries, we need to perform filtering on the numerical key columns. However, the display values in the prompts need to be textual and user friendly.
In this recipe, we will create a filter that displays the product line list (textual values) but actually filters on the numerical codes (Product_Line_Code).
Getting ready
Create a simple list report with Products / Product and Sales fact / Quantity as columns.
How to do it...
In this recipe, we will create a prompt and examine the differences between using the display value and the use value.
- Open Page Explorer and click on the Prompt Pages folder. Drag a new page from Toolbox under Prompt Pages .
- Double-click on the newly created prompt page to open it for editing.
- From the toolbox, drag Value Prompt to the prompt page. This will open a wizard.
- Set the prompt name to ProductLineand then click on Next as shown in the following screenshot:
- Keep the Create a parameterized filter option checked. For Package item , choose Sales (query) / Products / Product line code . Click on Next as shown in the following screenshot:
- Keep the Create new query option checked. Give the query name as promptProductLine.
- Under Value to display , select Sales (query) / Products / Product line .
- Click on the Finish button. Run the report to test it.
How it works...
When you drag a prompt object from Toolbox , Report Studio launches the prompt wizard.
In the first step, you choose the parameter to be connected to the prompt. It might be an existing parameter (defined in the query filter or framework model) or a new one. In this recipe, we chose to create a new one.
Then, you are asked whether you want to create a filter. If there is already a filter defined, you can uncheck this option. In our example, we are choosing this option and creating a filter on Product line code . Please note that we have chosen the numerical key column here. Filtering on a numerical key column is a standard practice in data warehousing as it improves the performance of the query and uses the index.
In the next step, Report Studio asks where you want to create a new query for the prompt. This is the query that will be fired on the database to retrieve prompt values. Here we have the option to choose a different column for the display value.
In our recipe, we chose Product line as the display value. Product line is the textual or descriptive column that is user friendly. It has one-to-one mapping with the Product line code . For example, Camping Equipment has a product line code of 991.
Hence, when we run the report, we see that the prompt is populated by Product line names, which makes sense to the users. Whereas if you examine the actual query fired on the database, you will see that filtering happens on the key column; that is, Product line code.
There's more...
You can also check the generated SQL from Report Studio.
In order to do that, navigate to the Tools | Show Generated SQL / MDX option from the menu as shown in the following screenshot:
It will prompt you to enter a value for the product line code (which is proof that it will be filtering on the code).
Enter any dummy number and examine the query generated for the report. You will see that the Product line code (key column) is being filtered for the value you entered.
So, now you know how the prompt display values and use values work.
If you ever need to capture the prompt value selected by the user in expressions (which you will often need for conditional styling or drill-throughs), you can use the following two functions:
- ParamDisplayValue (parameter name) : This function returns the textual value which represents the display value of the prompt. In our example, it will be the product line that was selected by the user.
- ParamValue (parameter name) : This function returns the numeric value which represents the use value of the prompt. In our example, it will be the Product line code for the product line selected by the user.
Summary
This article provided details on the concepts required to start with authoring reports in IBM Cognos Report Studio. It also covered filters, sorting, aggregations, formatting and conditional formatting, and so on.
Resources for Article :
Further resources on this subject:
- IBM Cognos Insight [Article]
- How to Set Up IBM Lotus Domino Server [Article]
- Integrating IBM Cognos TM1 with IBM Cognos 8 BI [Article]
About the Author :
Abhishek Sanghani
Abhishek Sanghani was born in India and attended Mumbai University, where he majored in Computer Engineering. He..
Ahmed Lashin.
Post new comment
|
https://www.packtpub.com/article/report-authoring
|
CC-MAIN-2014-15
|
refinedweb
| 5,198
| 63.59
|
First solution in Clear category for Radiation Search by hanpari
"""
If you feel like this
you can check this solution:
to compare two different approach.
Both solutions are similar with one
exception: one is using matrix transform from
list to dictionary based on Guidos comment:
You can judge by yourself
if readability was approved or not.
"""
def checkio(data):
width = len(data[0])
height = len(data)
result = [0,0]
def check(x,y,value):
"""
using recursion the function
is counting all valid fields
(equals to value)until
they are present. Valid field
is disabled as 0 and function returns
count of all found valid field.
"""
data[y][x] = 0
count = 1
for pos in ((-1,0),(0,-1),
(0,1), (1,0)):
x1 = x + pos[0]
y1 = y + pos[1]
if (x1 < 0 or
x1 >= width or
y1 < 0 or
y1 >= height):
continue
if data[y1][x1] == value:
count += check(x1,y1,value)
return count
for y in range(height):
for x in range(width):
val = data[y][x]
if val != 0:
temp = [check(x,y,val), val]
result = (temp if
temp[0] > result[0]
else result)
return result
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio([
[2, 1, 2, 2, 2, 4],
[2, 5, 2, 2, 2, 2],
[2, 5, 4, 2, 2, 2],
[2, 5, 2, 2, 4, 2],
[2, 4, 2, 2, 2, 2],
[2, 2, 4, 4, 2, 2]
]) == [19, 2], '19 of 2'
May 7, 2014
Forum
Price
Global Activity
ClassRoom Manager
Leaderboard
Coding games
Python programming for beginners
|
https://py.checkio.org/mission/radiation-search/publications/hanpari/python-3/first/share/80b5e3eb1cb52a6c78a3fddbe93646e7/
|
CC-MAIN-2021-31
|
refinedweb
| 261
| 50.03
|
Interopability Between Ext 3.0 platform and Ext 4.0
Hi all,
I was at this all last night and even had a few brain farts on the way but i want to utilize the charting capabilities in Ext 4.0 on my Ext 3.0 application.
Currently, im using the Ext 3.0 base files for my application. I created a test page using the Ext 4.0 base files and created a chart in ext 4.0 (awesome btw...)...
The only way i figured out how to integrate the 4.0 chart into my 3.0 app was to create an Ext iframe window which points to a url "/testing_4.0.php". This iframe target is setup to use the 4.0 base files and it correctly displays the 4.0 chart in my 3.0 app using an iframe window...
The problem i have is that i lose all layout functionality as the chart must be statically configured using width and height parameters and doesnt fill the window.
What i would ultimetly want is the chart to be displayed in a standard Ext window (not an iframe) so that i can get the chart to resize dynamically as the window is resized...
Is it possible to use the base 4.0 and specify some kind of backward compatability so the 3.0 built apps will function with 4.0 base files?
Any other ideas are welcomed and appreciated!!
It has been stated that when 4.0 is actually released, it will ship with a compatibility layer file to allow 3.x functionality to work with making immediate changes.Tim Ryan
Read BEFORE posting a question / BEFORE posting a Bug
Use Google to Search - API / Forum
API Doc (4.x | 3.x | 2.x | 1.x) / FAQ / 1.x->2.x Migration Guide / 2.x->3.x Migration Guide
Wonderful news! I will in the mean time keep my iframe setup and i will just hard code a width and height for the chart until 4.0 has the compatability layer working...
Thanks for the response!
Put it into a viewport and it will resize within the iframe window:
PHP Code:
Ext.onReady(function () {
Ext.create('Ext.Viewport', {
layout: {
type: 'border',
padding: 5
},
defaults: {
split: true
},
items: [
{
xtype: 'toolbar',
region: 'north',
items : [{
text : 'Reload Data',
handler : function() {
store1.loadData(generateData(10));
}
}]
},{
id: 'chartCmp',
region: 'center',
layout: 'fit',
xtype: 'chart',
animate: true,
shadow: true,
store: store1,
axes: [{
type: 'Numeric',
position: 'left',
fields: ['data1'],
label: {
renderer: Ext.util.Format.numberRenderer('0,0')
},
title: 'Number of Hits',
grid: true
}, {
type: 'Category',
position: 'bottom',
fields: ['name'],
title: 'Month of the Year'
}],
series: [{
type: 'column',
axis: 'bottom',
highlight: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' $');
}
},
label: {
display: 'insideEnd',
'text-anchor': 'middle',
field: 'data1',
renderer: Ext.util.Format.numberRenderer('0'),
orientation: 'vertical',
color: '#333'
},
xField: 'name',
yField: 'data1'
}]
}]
});
});
You should look at the ext sandbox example. Using the sandbox files allows you to use the Ext 4 stuff alongside Ext 3 by changing the namespace for Ext4 from Ext to Ext4.
Thanks for the responses. I will try out the sandbox approach and if that fails i will try the viewport approcach....Ext4 charts are just too good to pass on...
So i tried the sandbox approach which worked but the css (ext4.css) was messing up my desktop css.
I ended up using the viewport which worked wonderfully...It now resizes with the iframe window
Thanks for all the help!!
I've been playing around with the sandbox demo, the Ext 4 charts do work in a 3 environment, but not very well in the 'desktop' environment. Since the ext4 chart and window in the sandbox example are created mostly outside the Ext 3.3 desktop framework they don't really play nice with the desktop. Things like minimizing/maximizing the Ext 4 window, having it constrain to the desktop rather than the whole page etc don't work. The Ext4 window is also always in front of all other windows. I guess it was just a cobbled together demo to show that it is sorta possible. Until the compatibility file is released i don't think it's worth spending too much time on.
Similar Threads
Adobe AIR...just another widget platform?By Hermman in forum Ext.air for Adobe AIRReplies: 2Last Post: 1 Oct 2011, 3:33 AM
Ext.platform methodsBy jordandobson in forum Sencha Touch 1.x: DiscussionReplies: 9Last Post: 13 Sep 2010, 10:30 AM
0.82 documentation Ext.platformBy mrsunshine in forum Sencha Touch 1.x: BugsReplies: 0Last Post: 17 Jun 2010, 1:19 AM
Development platform pickle.By SeaSharp in forum Community DiscussionReplies: 9Last Post: 15 Oct 2007, 2:41 AM
|
https://www.sencha.com/forum/showthread.php?125002-Interopability-Between-Ext-3.0-platform-and-Ext-4.0
|
CC-MAIN-2016-30
|
refinedweb
| 797
| 68.57
|
In this example, you’ll learn to print the number entered by a user using C++ cout statement.
Here in the below program, we’ll Print Number on the output console.
Program to Print Number Entered by User
#include <iostream> using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; cout << "You entered " << number; return 0; }
Output
Enter an integer: 23 You entered 23
This program asks the user to enter a number.
When the user enters an integer, it is stored in variable number using
cin.
Then it is displayed on the screen using
cout.
Related Programs
- C++ “Hello, World!” Program
- Addition of Two Numbers by commenting. Documentation.
Please write to us at [email protected] to report any issue with the above content or for feedback.
|
https://coderforevers.com/cpp/cpp-program/read-print-integer/
|
CC-MAIN-2019-39
|
refinedweb
| 130
| 63.7
|
Hello,
I've just started learning to program and have begun with Java. I'm working my way through an online tutorial and after the beginner section (before the intermediate section) there are some games to create as practice; this is the third one.
I've followed all the steps and created the game successfully and now I'm adding to it in order to practice my skills.
I decided to amend the following:
(1) Amend the output so that if there is only 1 stick, the output is "There is 1 stick" instead of "There are 1 sticks"
(2) Close all open scanners
(3) Amend the output so that if the computer takes 1 stick, the output is "Computer takes 1 stick" instead of "Computer takes 1 sticks"
(4) Amend the opening sequence to include the title of the game (i.e. figure out how to put string into "") and ask the user if they want to play. If yes then play the game and if not then say goodbye and don't play.
I have done everything up until ending the game if the user doesn't want to play.
I have tried:
Adding break but I keep being told this cannot exist outside of a loop etc.
The opening of the code is:
The game works fine i.e. the message "let's play" is printed if I say Y or y and is not printed if I choose anything else but I don't want the game to play if I choose anything other than Y or y.The game works fine i.e. the message "let's play" is printed if I say Y or y and is not printed if I choose anything else but I don't want the game to play if I choose anything other than Y or y.Code:package games.javatutorials; import java.util.Scanner; public class TwentyOneSticks { public static void main(String[] args) { int numSticks = 21; int numToTake = 0; Scanner reply = new Scanner (System.in); Scanner input = new Scanner (System.in); Scanner take = new Scanner (System.in); System.out.println("The game is \"21 Sticks\", are you ready to play? (Y/n)"); String ready = reply.nextLine(); if (ready.equals("y") || ready.equals("Y")) { System.out.println("Let's play!");} //I tried adding: else { // System.out.println("Ok, goodbye!"); // break; // } // This obviously did not work. I also tried adding the break // at the end of my while loop (as though part of the above if // statement which did not work. System.out.println("Would you like to go first? (Y/n)"); String goFirst = input.nextLine()
I'm probably jumping ahead i.e. I'm sure the tutorial will teach me this soon but I'd like to know if there's a simple way of doing this. Please keep in mind that I have only learned up to the beginner stuff in:
Java made easy dot com
So please keep the solution as simple and basic as possible.
Thank you very much,
3773
|
http://forums.devshed.com/java-help/940890-21-sticks-help-code-last-post.html
|
CC-MAIN-2017-17
|
refinedweb
| 504
| 71.85
|
1.1.1 Pascal Casing
This convention capitalizes the first character of each word (eg: MyCounter).
1.1.2 Camel Casing
This convention capitalizes the first character of each word except the first one. E.g. myCounter.
1.1.3 Upper case
Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long, identifiers of three or more characters should use Pascal Casing instead. For Example:
public class Math
{
public const PI = ...
public const E = ...
public const myVarCount = ...
}
public class Math
{
public const PI = ...
public const E = ...
public const myVarCount = ...
}
1.2 Naming Guidelines
Generally the use of underscore characters inside names and naming according to the guidelines for Hungarian notation are considered bad practice. Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the variable. This style of naming was widely used in early Windows programming, but now is obsolete or at least should be considered deprecated.
And remember: a good variable name describes the semantic not the type. An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button should be postfixed with their type name without abbreviations. For example:
System.Windows.Forms.Button cancelButton;
System.Windows.Forms.TextBox nameTextBox;
System.Windows.Forms.Button cancelButton;
System.Windows.Forms.TextBox nameTextBox;
1.2.1 Class Naming Guidelines
1.2.2 Interface Naming Guidelines
1.2.3 Enum Naming Guidelines
1.2.4 ReadOnly and Const Field Names
1.2.5 Parameter/non const field Names
1.2.6 Variable Names
1.2.7 Method Names
1.2.8 Property Names
1.2.9 Event Names
Cheers,
God Bless
|
http://it.toolbox.com/blogs/coding-dotnet/naming-conventions-21622
|
crawl-002
|
refinedweb
| 287
| 54.29
|
#include "ntw.h"
Go to the source code of this file.
The cached_image is an abstract widget which is used to create other widgets. For a cached_image, the image data is cached on disk on the client AND server side, so creating many of the same image from a buffer is much faster than sending the data over the network each time. It's also the most memory-efficient way on the server side to build images.
Note that the client handles cached images exactly like an image_buffer. The only difference is that the server does not store the image in memory.
The cached_image and image_buffer are the only way to include an image in a list or tree model.
If you're not interested in persistence, use cached_image rather than image_buffer for images.
|
http://ntw.sourceforge.net/Docs/CServer/cached__image_8h.html
|
CC-MAIN-2018-05
|
refinedweb
| 134
| 71.85
|
There are a number of cases where I think type checking should produce
errors, for instance:
def str = "s"
if (str == 12) {...
In IDEA this is described as "Reports calls to *.equals()* and *==*
operator usages where the target and argument are of incompatible types.
While such a call might theoretically be useful, most likely it represents
a bug."
As that text says, I guess it's not always a coding error. But I'm
interested in how hard it would be to add it.
org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport#checkCompatibleAssignmentTypes
seems to have the code for this, and StaticTypeCheckingVisitor seems to do
many checks of this kind, but not this one.
cheers, jamie
|
http://mail-archives.eu.apache.org/mod_mbox/groovy-users/201509.mbox/%3CCAHz4dqFEX4t==3qSKp=Bj+dVdbFn1a2FWQK7JXNj=jHgqfbQXg@mail.gmail.com%3E
|
CC-MAIN-2021-04
|
refinedweb
| 114
| 56.15
|
SAP HANA Geospatial processing feature was launched with SAP HANA SP6. As a developer I had no idea even what spatial processing meant but with the help of the content available over SCN and doing some hand-on as a part of SAP Blue Project(You can see the full blog at “HANA Cookbook for MySQL Developers”) I have come up with a small demo of an application which highlights some of the geospatial features.
The demo will look as shown below:-
The blog will be divided into 2 parts where-in I will try to highlight how the application was created from an end to end perspective.
In Part 1(current document) I will explain some of the geospatial features available in SAP HANA and how we can write logic to store and access such data. I will also show what data was used in my application.
In PART 2 of this blog Experiences with SAP HANA Geo-Spatial Features – Part 2 I will show you details on how geospatial information can be access via XSJS as GeoJson and how can we integrate Leaflet MAP client to display the data.
So to start SAP HANA has brought in some new spatial data types like POINT (ST_POINT) and Geometry (ST_GEOMETRY) to store spatial information. A point is like a fixed single location in space and will be represented by X and Y co-ordinates (*can also have a Z co-ordinate in case of 3D space).
A Geometry is like a super class container and can store the below type within it.. More information about GeoJson can be found below here: –.
SAP HANA also provides a list of other means to extract data from geometrical data structures apart from GeoJson like Well Known Text (WKT), Well Known Binary (EKB) etc. More information is available in the HANA SPATIAL reference found in the link below:-
Now coming to the application where-in I am showing all the parliamentary constituencies of India (*Note: The data regarding the parties ruling the constituencies might not be accurate as the data was collected was from 2009 and it might have changed over time)
So first I had to collect the shape files for all the constituencies of INDIA. Finally after some amount of research here and there I finally got the data of the Indian parliamentary constituency. You can find the same in this link.
The data was in ESRI shape file format () and luckily SAP HANA supported the shape file import into it.
So in order to load shape file into HANA you need to perform the 4 simple steps stated below:-
- Download Putty() and PSCP()
- Copy the shape file(zip it first) from your local machine into HANA using PSCP
C:\<path to PSCP directory>>pscp.exe <source file> <OS_Username>@<HANA _server name>:<destination folder>
- You can login to you server using putty and unzip the files.
- You can import the shape files in HANA by running the below command
IMPORT “Schema_Name”.”Table_Name” AS SHAPEFILE FROM ‘path to shape file’
Note: Don’t give the extension of the shape file in the path. Just mention its name.
So once I imported my shape files into HANA, the data looked like below:-
So as you can see I had the list of all the constituencies along with the following information:-
- The state to which it belong, the ruling party, area and the color code(some of the fields were added later)
- the next part of this blog, I will explain how we can expose the data out of HANA as a XSJS service and how we can visualize the data using LEAFLET.
Please find the 2nd Part of the Blog in the following link Experiences with SAP HANA Geo-Spatial Features – Part 2
Nice blog! Looking forward to the next part!
Please find the second part in the below link
Experiences with SAP HANA Geo-Spatial Features – Part 2
Really Nice one crystal clear .
Thanks!!!!! 🙂
Hi Trinoy,
Thanks for the excellent blog. I was trying to implement this. and I am facing an issue. It will be great if you can kindly help. While importing the shape files I am able to import only one file. If i run the same import command for other file it’s not letting me do that and complains that the table already exists.
Could not execute ‘IMPORT “ID280253″.”IN_PC” AS SHAPEFILE FROM ‘/usr/sap/HET/HDB00/work/DATA/S01_PC” in 49 ms 466 µs .
SAP DBTech JDBC: [2] (at 18): general error: Can’t import due to table already exists: line 1 col 19 (at pos 18)
Also some I am getting sql exception for some of the files:
Could not execute ‘IMPORT “ID280253″.”IN_PC” AS SHAPEFILE FROM ‘/usr/sap/HET/HDB00/work/DATA/S01_PC” in 428 ms 519 µs .
SAP DBTech JDBC: [2]: general error: Shapefile Import failed. SQLException.
~Prashant
I got the first one resolved by using following sql statment:
IMPORT “<SCHEMA>”.”<TableName>” AS SHAPEFILE FROM ‘<file Location>’ WITH REPLACE;
I was able to import files for :
S04-Bihar
S05-Goa
S07-Haryana
S11-Kerala
S19-Punjab
S21-Sikkim
S22- Tamilnadu
S23-tripurA
S24-UP
S25-West Bengal
S27-Jharkhand
For rest I am facing issue. Any clue..?
Hi Prashant
I had faced some issue while importing shapes in rev70 but when i upgrade to rev71, i was able to resolve it.
Which version are you using ?
Trinoy
Thanks Trinoy. We are at Rev 70 only, I have requested for upgrade. Will keep you posted.
~Prashant
Hi Trinoy,
This is kind of weird but after updating to revision 72 I am able to import shape file 01 which was earlier giving error, but now I am unable to import multiple files. I have started to face my first problem and the REPLACE addition also is not working. Will it be possible for you to share the SQL command which you used to import multiple files.
~Prashant
can you try this
create a TMP table
DROP TABLE INDIA_PC_TMP
import content into the temp table
IMPORT INDIA_PC_TMP AS SHAPEFILE FROM <loc>
then fill the main table from the temp table.
INSERT INTO INDIA_PC SELECT * FROM INDIA_PC_TMP;
I agree it is not a good way but let me know if this works…..
Thank You for sharing this , even though we need to create 28 tables, finally it worked .
Thanks….Glad you like the blog….
This is part of SAP HANA Cookbook for MySQL Developers | SAP HANA. Please feel free to check out entire Cookbook.
Regards,
Swapan
Hi Trinoy,
You rock!
Regards,
Balaji
That’s great work. I’ve been trying to do this for a while, but ran into issues changing spatial references to the other default formats. Everything just default to 0, which was annoying as this would impact the results of spatial queries. Just noticed HANA 7.0 Dev Edition is available, so hopefully that issue goes away, but would be good to confirm the exact edition spatial is available from.
Also Is there any documentation that explains how to add new spatial references to the table? If you go to
and check out an example like
You can certain formats you can import, including SQL for PostGIS. Would be nice if there was a HANA entry here or Hana supported import of these existing formats.
Interesting to see how ESRI will be using this and the impact on products (or services??) like Geo.E.
P.s. I love Leaflet too. It’s so flexible
Cheers,
Katan
Hi Katan,
Would you please elaborate on the different formats and the way in which you tried that. I can try to replicate the same in my system and figure out if the issue still exists.
And i agree with you Leaflet is really amazing!!!!!
I have not done much research on ESRI so can`t comment on that but will try to get some facts around that topic and will let you know.
Cheers
Trinoy Hazarika
Hi Trinoy,
I was following the examples from the HANA Spatial Reference Guide to test stuff out.
So there is a view for spatial reference systems information ST_SPATIAL_REFERENCE_SYSTEMS system view.
I was trying to setup data to use WGS 84 (planar) – SRID 1000004326, which is there by default.
I used this statement to add a column and it failed here if I included an SRID.
ALTER TABLE SpatialShapes ADD (location ST_POINT(1000004326));
If I did not include it, I could see the column was created successfully using SRID 0. There was another view which I could use to see all spatial columns in all tables and metadata about them including SRID, but I’ve forgotten it’s name…
Unfortunately I have trashed the instance. So need to create a new one and test again. It was all pretty new back then.
Cheers,
Katan
Hi,
I’m running the SAP HANA Developer version 70 on Amazon’s AWS and I get the same SQL error when I try to import the ESRI shape files. (SAP DBTech JDBC: [2]: general error: Shapefile Import failed. SQLException.)
Do you know how and if there is a possibility to update HANA to version 72 on AWS?
Thank you very much for your help in advance,
Juergen
HI
what are the 28 tables you mentioned that we need to create before import. can you send me the format of the tables because my import is failing due to the tables are not available. in your example you mentioned only 2 tables but the import required INDIA_PC table columns ? where is this info.
BR,
Rushi.
hi
Further more, i have created a table based on the screenshot you have added with the following columns. Please confirm is this is right to use.
“ST_CODE”,
“ST_NAME”,
“PC_NAME”,
“PC_CODE”,
“AREA”,
“PC_NO”,
“FLAG”,
“PARTY”,
“SHAPE”,
“COLOR”
let me know.
BR,
Rushi.
I get Failed to load resource: the server responded with a status of 403 (Forbidden)
then going there:
get: Wrong apikey
Thanks for this post,
looking forward to try it. 🙂 🙂
also, It was a nice demo at SAP TechEd 2015 _Bangalore. 🙂
Thanks,
–Pavan G
Nice introduction to the topic. Thanks 🙂
In addition to the topic: Has somebody experience with a transport scenario for HANA content that is based on spatial data and computations?
So, usually – from my experience – you try to not create the physical tables, views and procedures directly from SQL. Because this will lead to serious trouble if you want to move your content/implementation between systems (typically DEV env -> PROD env). Instead you use design time objects. For example Core Data Services – CDS (.hdbdd) for your schema. But I didn’t find any documentation that CDS is supporting spacial data types..
So what are the options to work with spatial data on a design time level?
Thanks,
Mathias
Geospatial types were supported in CDS (hdbdd) as of SPS 09. Support for the Geospatial functions was added in SPS 10.
Ok I didn’t check the latest docs.. sry.
But thanks for the fast reply and very nice to here that there is a full integration of spatial data and calculations on design time level.
Best, Mathias
Really great to see this 🙂
How can I setup a “spatial system” on SAP HANA Express Edition 2.0 SPS1? On the HXE website this option is announced as a part of HXE but I cant find any how-to or tutorial.
Marcus,
HANA spatial is included as a part of HXE. Once you’ve installed and configured HXE (see here), HANA spatial is accessible just as it is on HANA base, platform and enterprise editions. There are tutorials (see here) and videos (see here) and a lot more. If you’re interested in integrating ArcGIS and HANA together, see here, here and here. The last link is an FAQ that Sharon Om and I put together. Take a look and let me know if you need any additional help.
|
https://blogs.sap.com/2014/02/25/experiences-with-sap-hana-geo-spatial-features-part-1/
|
CC-MAIN-2018-17
|
refinedweb
| 1,987
| 70.13
|
Inconsistency in notifications with delays in the beta?
I have a simple script like so:
def _notification(delay=0): notification.schedule( message="foo" delay=delay, actions=[ {"title": "ok"}, {"title": "Snooze", "url": "SCRIPT_RUN_URL&argv=snooze"}, ], ) def main(): len(sys.argv) > 1 and sys.argv[1] == "snooze": _notification(delay=10*60) # 10 minutes -> seconds else: _notification() if __name__ == '__main__': main()
(I think that above should work, I'm not sure I'm just typing it up from memory. But the gist is that when I run the script I get a notification immediately with an option to 'snooze' it, which calls the same script with a 10 minute delay for the notification.)
These notifications show up on my watch just fine, and on my watch I even get the option to hit "ok" or "snooze".
This behavior seems to be extremely inconsistent though. Sometimes hitting "snooze" on the watch will trigger the second notification in 10 minutes, but sometimes it doesn't. Nothing has changed between these attempts so I can't figure out the issue, nor do I see why there would be one.
When I don't get the second notification, I can go into the Pythonista console and verify that there is a notification scheduled. What's odd is that when I go into the console and verify that the notification is scheduled, it usually does show up 10 minutes from when I verified it.
Anyone else have this issue or experienced something similar?
|
https://forum.omz-software.com/topic/5366/inconsistency-in-notifications-with-delays-in-the-beta
|
CC-MAIN-2020-29
|
refinedweb
| 245
| 53.92
|
View all headers
Path: senator-bedfellow.mit.edu!dreaderd!not-for-mail
Message-ID: <computer-lang/java/gui/faq_1163655788@rtfm.mit.edu>
Supersedes: <computer-lang/java/gui/faq_1161059116@rtfm.mit.edu>
Expires: 30 Dec 2006 05:43:08 GMT
X-Last-Updated: 2006/06/09
Organization: none
From: cljg_faq@gmx.de (Thomas Weidenfeller)
Newsgroups: comp.lang.java.gui,comp.lang.java.programmer,comp.answers,news.answers
Subject: comp.lang.java.gui FAQ
Followup-To: comp.lang.java.gui
Approved: news-answers-request@MIT.EDU
Originator: faqserv@penguin-lust.mit.edu
Date: 16 Nov 2006 05:43:55 GMT
Lines: 2448
NNTP-Posting-Host: penguin-lust.mit.edu
X-Trace: 1163655835 senator-bedfellow.mit.edu 570 18.181.0.29
Xref: senator-bedfellow.mit.edu comp.lang.java.gui:134802 comp.lang.java.programmer:721761 comp.answers:64352 news.answers:311545
View main headers
comp.lang.java.gui FAQ
________________________________________________________________________
Table of Contents
PART I =================================================================
SECTION 1 - Introduction
Q1.1 What is this, and what does it contain?
Q1.2 What's not in here?
Q1.3 Where do I find a copy of the FAQ?
Q1.4 There are so many Java FAQs.
Which is the right, official one?
Q1.5 Does Sun support or endorse this FAQ?
Q1.6 I noticed broken links in the FAQ.
Don't you verify them before publishing?
Q1.7 Is there an HTML, Word, <whatever format> version of the FAQ?
Q1.8 What is AWT?
Q1.9 What is Swing?
Q1.10 What is SWT?
SECTION 2 - The comp.lang.java.gui Newsgroup
Q2.1 What is the newsgroup's charter? What are acceptable topics?
Q2.2 Which topics or posting are not welcome in the newsgroup?
Q2.3 Where can I find an archive of the newsgroup?
Q2.4 What is an SSCCE?
Q2.5 Why don't people like top-posting? What is top-posting?
Q2.6 Is there more about posting to newsgroups and asking questions?
Q2.7 Does Sun support or endorse the newsgroup?
SECTION 3 - The Top 5 Questions
Q3.1 My GUI freezes or doesn't update. What to do?
Q3.2 How do I update the GUI from another thread?
Q3.3 I have arranged all my widgets nicely on a window. Then I
changed the OS / Java version / font / PLAF. Now everything is
broken. What's going on?
Q3.4 My graphics on a Canvas/JPanel/JComponent, etc. gets
corrupted, or I get a null pointer exception when trying
to draw. How can I avoid this?
Q3.5 How to create a transparent or non-rectangular window?
SECTION 4 - Architecture
Q4.1 What is this Model-View-Controller (MVC) stuff?
Q4.2 What is the Swing single-threading issue?
Q4.3 What is the right way to start a Swing GUI?
Q4.4 What is full-screen exclusive mode?
Q4.5 What is active rendering?
PART II ================================================================
SECTION 5 - Window / [J]Frame / [J]Dialog (Top-Level Containers)
Q5.1 How can I ensure a window is always on top of all other windows
using AWT or Swing?
Q5.2 How can I (de)iconify a window?
Q5.3 How can I replace/remove the icon in the title bar (window
decoration) of a [J]Frame?
Q5.4 How to replace the icon in the title bar (window decoration)
of a [J]Dialog?
Q5.5 My modal dialog goes behind the main window. How can I ensure
it is in front instead?
Q5.6 How to bind the escape key to the JDialog cancel operation?
Q5.7 How can I implement my own JFrame/JDialog close handling?
Q5.8 How Do I center a window on the screen? How do I get the
screen size?
Q5.9 How to ensure a minimum or maximum window size?
Q5.10 How to ensure a particular aspect ration of a window?
Q5.11 How can I delegate the window placement to the window system
or manager?
Q5.12 I need to take some toolbar (dock, panel) size into account when
calculating a window position an/or size. How?
Q5.13 My window layout is displayed incorrectly. I have to move
the window, before the layout is right. What's wrong?
Q5.14 How can I display a Splash Screen at the start of my Program?
SECTION 6 - [J]Component (Widgets)
6.1 General Questions
Q6.1.1 How do I position components (widgets) on a window?
Q6.1.2 How to create a transparent widget?
Q6.1.3 How to create a non-rectangular widget?
Q6.1.4 What are Insets?
Q6.1.5 How do I find a component's top-level container (e.g.
the window)?
6.2 JTree
Q6.2.1 I changed the data / structure for my JTree, but the display
doesn't get updated. What's going on?
Q6.2.2 How do I set a custom icon for a node?
Q6.2.3 How do I remove all my nodes from a JTree at once?
6.3 Styled Text / JEditorPane / JTextPane
Q6.3.1 Can I use RTFEditorKit to read RTF documents created by Word?
Q6.3.2 I have problems using the Swing HTML parser to parse all
kinds of HTML. Is this normal?
Q6.3.3 Some of my CSS styles don't work out. Is this normal?
Q6.3.4 Can I use Swing's HTML support to write a web browser?
Q6.3.5 Can I use Swing's HTML support to build an on-line
help system or e-book?
Q6.3.6 If HTML support is really so broken in Java, what is it
good for?
6.4 [J]TextArea
Q6.4.1 I append text to a JTextArea. How to ensure the text
area is always scrolled down to the end of the text?
Q6.4.2 How to use several different fonts (styles, sizes) in
one [J]TextArea?
6.5 [J]Label / [J]Button
Q6.5.1 How can I have multiple Lines in a [J]Label?
Q6.5.2 I want to have a hyperlink in a [J]Label. How can I do this?
Q6.5.3 How do I make a JButton the default button in a JDialog?
SECTION 7 - JScrollPane
Q7.1 I added a component (e.g. a JPanel with an image) to a
scrollpane, but the scrollpane doesn't show it at the right
size / without scrollbars, etc. What's wrong?
PART III ===============================================================
SECTION 8 - Graphics & Painting
Q8.1 What is the equivalent of AWT's Canvas in Swing?
Q8.2 When drawing on a JPanel, the background is garbled.
Q8.3 How do I generate some charts / plots in Java?
Q8.4 How to draw some graphs in Java?
Q8.5 I want to write a diagram editor. Where to start?
Q8.6 How do I draw lines between JLabels on a JPanel?
Q8.7 How to debug graph painting?
Q8.8 I need to draw a tree. How?
Q8.9 I need an algorithm for drawing ...
Q8.10 When I subclass JPanel/JComponent, I need to override paint(),
right?
Q8.11 Why does drawImage() fail when I try to display a loaded image?
Why are the width and height of my loaded image both zero?
Q8.12 How do I resize (zoom in/out) my Graphics?
Q8.13 Where do I find the icons which are used by Swing
itself?
Q8.14 Where do I find typical application icons?
SECTION 9 - Fonts
Q9.1 Which Fonts can I use? Can I use font <xyz>?
Q9.2 How to turn on text antialiasing in Swing?
Q9.3 Why do some of my characters get displayed as squares?
SECTION 10 - Other Common Questions
Q10.1 My GUI has rendering problems when the JMenu opens over my
top Panel ...
Q10.2 Can I use Swing for Applets?
Q10.3 How do I change a color/font/etc. globally for an
application?
Q10.4 How do I get all the UIDefaults, and what do they mean?
Q10.5 Why is Swing so slow?
SECTION 11 - Non-GUI Questions
Q11.1 How do I do a text/console UI in Java?
Q11.2 How can I do this JavaScript thing on my web site?
Q11.3 I want to make ...
SECTION 12 - Resources
12.1 Sun's Java Web Site
12.2 Other Sun Sites
12.3 Icons
12.4 Miscellaneous Examples, Tips and Tricks
12.5 Style Guides
12.6 SDK Documentation
12.7 More Swing
12.8 Online Magazines
12.9 Java 2D API
12.10 Java 3D API
12.11 General Java
12.12 More?
Q12.12.1 But I need more!
SECTION 13 - Improvement Suggestions
SECTION 14 - Acknowledgments
________________________________________________________________________
PART I
========================================================================
SECTION 1 - Introduction
~~~~~~~~~~~~~~~~~~~~~~~~
Q1.1 What is this, and what does it contain?
This is the FAQ for the comp.lang.java.gui newsgroup. It mostly deals
with Java Standard Edition Swing issues, and contains some AWT
information, too.
In many cases these are also topics many readers would like NOT to see
discussed again soon.
Q1.2 What's not in here?
This is not a general introduction to programming, Java programming, or
GUI programming. Further it is assumed that the reader is familiar with
Java and GUI terminology.
Also, the following topics are either not covered at all or just cursory
touched, since they are not often discussed in c.l.j.g, have own groups,
and/or the FAQ author is not knowledgeable about them:
* J2ME GUI programming
* Java 3D programming (see <news:comp.lang.java.3d>)
* Java game programming
* Computer graphics algorithms
(see <news:comp.graphics.algorithms>)
Q1.3 Where do I find a copy of the FAQ?
1) The FAQ is regularly posted to
<news:comp.lang.java.gui>
2) At Usenet archives like
<>
<>
<>
3) Just search an archive like
<comp.lang.java.gui">>
4) With the author's permission people have placed (sometimes older)
versions of the FAQ on web sites, too, e.g.
<>
<>
5) There is even a Japanese translation around:
<>
Q1.4 There are so many Java FAQs.
Which is the right, official one?
There is probably not THE FAQ. Everyone can start an FAQ, and many have
done so (and many have stopped after a few weeks).
Q1.5 Does Sun support or endorse this FAQ?
No, it is just a newsgroup FAQ. Sun probably doesn't know about it.
NOTE: The author of this FAQ does not have any inside information or
contacts to Sun's Java or GUI development team and has never been
contacted by Sun. Therefore, the FAQ's author is not in a
position to forward suggestions to Sun or help with expedited
answers from Sun. Please refrain from such requests.
See also: "Q2.7 Does Sun support or endorse the newsgroup?"
Q1.6 I noticed broken links in the FAQ.
Don't you verify them before publishing?
No, I don't. I rely on feedback from readers. Also, links might break
at any time, e.g. just seconds after a link has been verified.
Q1.7 Is there an HTML, Word, <whatever format> version of the FAQ?
There is no such official version. Some people went through the effort
to convert the FAQ to HTML. I suggest to use the
<>
software to create am HTML version for personal usage.
See also: "Q1.3 Where do I find a copy of the FAQ?"
Q1.8 What is AWT?
AWT (The Abstract Window Toolkit) is Sun's first Java GUI toolkit. It
is rather limited and uses the native GUI components of the operating
system.
Unless you have to support an old VM, Swing is usual the better choice
for a Java GUI toolkit.
Q1.9 What is Swing?
Swing is Sun's second attempt at a Java toolkit. It is rich in
functions and widgets, and is considered the standard Java GUI
toolkit. Nowadays it is bundled with the Java 2 Standard Edition.
Most parts of Swing are written in Java, especially most of the GUI
components. Swing uses some parts of AWT in order to gain access to the
native GUI system for event handling and top-level containers. It is
build on AWT's lightweight component framework.
Q1.10 What is SWT?
SWT is an alternative GUI toolkit from IBM. Unlike AWT and Swing, it is
not part of the Java 2 Standard Edition. You have to obtain it
separately for the platforms you want to support (it uses a native
library).
SECTION 2 - The comp.lang.java.gui Newsgroup
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Q2.1 What is the newsgroup's charter? What are acceptable topics?
The voting for the group with the group's charter passed on
1997-04-10:
<>
A longer history of comp.lang.java.* reorganizations can be found in
<
va-reorg>
Here is an excerpt from the '97 reorg charter (Note, "all groups"
refers to all the Java groups from that voting, including
comp.lang.java.gui):
CHARTER: all groups
The normal practice should be that most articles are posted to one
single, correct group ONLY. Cross-posting is only appropriate when
the problem is hard to categorize or when it legitimately concerns
more than one group. Answers should be posted to a single group only
once the nature of the problem has been ascertained. Many articles of
this sort should go to comp.lang.java.help (only).
It is not appropriate to post binary class files or long (longer than
one or two screenfuls) source listings on any of these groups.
Instead, the post should reference a WWW or FTP site (short source
snippets to demonstrate a particular point or problem are fine).
END CHARTER.
[...]
CHARTER: comp.lang.java.gui
This unmoderated group is for any and all discussion relating to
GUI toolkits or window frameworks in Java. Topics include the AWT,
Netscape's IFC, Microsoft's planned AFC, Visix's Vibe toolkit, among
others. The newsgroup will also be the appropriate place for
discussion of the JDK event model, mouse and keyboard issues,
bugs in windowing code, and graphics programming in Java. If it
concerns something that can be seen on the screen, it belongs in this
group.
END CHARTER.
One will note the list of ancient Java GUI technologies, and the
absence of Swing. It is safe to say, that nowadays most discussions are
about Swing, plus a few about AWT and Java printing.
Q2.2 Which topics or posting are not welcome in the newsgroup?
Of course, this question is never asked, but over the time, it has
turned out that certain types of postings are not welcome, even if Java
related. This includes:
* Issues answered in this FAQ are issues most posters don't want
to see discussed again soon.
* Posting your homework.
* Advocacy. Goto comp.lang.java.advocacy instead.
* Postings urging the readers to help. Especially in
conjunction with whining. No one in the group is paid to help
you. No one owns you anything.
* Public and hidden advertising. You think you are too clever
to be caught? Well, read this thread in our sister group
c.l.j.programmer first, and watch how some business lost all
its reputation:.
0307010403.67c54a5f%40posting.google.com
* Postings which just contain a statement like "Help! It does
not work!", without any additional information, like the
exact error message, source code, or even a hint what "it" is
supposed to mean.
* Postings demonstrating unwillingness to learn are not
welcome, too. And learning starts by reading the API
documentation before posting.
* Test messages are not welcome. Instead, use alt.test.*, and
learn how newsgroups work.
* Postings written in "elite hacker" style or txt message/chat
style.
See also: "Q2.4 What is an SSCCE?"
Q2.3 Where can I find an archive of the newsgroup?
See e.g.
<comp.lang.java.gui">>
Q2.4 What is an SSCCE?
Short/small, self contained, compilable, example (source code).
It would be best if you provide such short (see the group's charter)
example source code in your first request for help. When asked for one,
please don't complain that your source code is too large, too tricky,
too secret for being cut down to a reasonable size and posted. You have
the problem, and you asked in a public forum, so it is in your interest
to provide the requested information.
For more information about hacking some example code together, go to
<>
Q2.5 Why don't people like top-posting? What is top-posting?
See the following Question & Answer (well, Answer & Question) section:
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on Usenet and in e-mail?
-- Common Usenet signature
Q2.6 Is there more about posting to newsgroups and asking questions?
Yes, see e.g. the following for making the most out of a newsgroup
(ignore the hacker slang):
<>
[The author of that web page has requested a notice that he is not
a general help desk for all your problems].
<>
Also see the newsgroups:
<news:news.newusers.questions>
<news:news.answers>
And RFC 1855. E.g. at
<>
<>
Q2.7 Does Sun support or endorse the newsgroup?
From time to time a poster could be spotted apparently working for
Sun's Swing development team and answering questions. But that hasn't
happened in a long time. You sometimes see announcements posted to the
group, treating the group as as write-only media. But that's it.
It is safe to say that the newsgroup isn't of much interest for Sun,
and that suggestions or informed opinions posted to the group will most
likely not be seen, noted or followed-up by Sun.
You might want to try
<>
or
<>
if you want to suggest some changes to Java. Good luck.
See also: "Q1.5 Does Sun support or endorse this FAQ?"
SECTION 3 - The Top 5 Questions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Q3.1 My GUI freezes or doesn't update. What to do?
Most likely you are blocking the event dispatching thread (EDT).
Offload time-consuming tasks from your event listeners to separate
threads.
You can do the necessary implementation by hand, it is rather simple:
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
//
// Do some time consuming task
//
...
//
// Update the GUI from within the task
// synchronous: invokeAndWait()
// asynchronous: invokeLater()
//
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//
// GUI code
//
}
});
}
}).start(); // start the thread
}
Or you can use existing frameworks like the SwingWorker class from
Sun. See the series of articles in
<>
SwingWorker is earmarked for inclusion into Java Standard Edition 1.6.
For some special cases you can give paintImmediately() a look. See
<>
for some information about using paintImmediately().
See also: "Q3.2 How do I update the GUI from another thread?"
Q3.2 How do I update the GUI from another thread?
If you have to update the GUI from another thread (e.g. once you
offloaded a time consuming task from the EDT to another thread) you
should use the javax.swing.SwingUtilities.invokeLater() or
javax.swing.SwingUtilities.invokeAndWait(). Often you want
invokeLater().
The code is rather simple. E.g. when using an anonymous class:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Code to be executed on the EDT
}
}
);
// Current thread will immediately continue here
And
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// Code to be executed on the EDT
}
}
);
// Current thread will wait until code has been executed on
// the EDT.
Again, see
<>
for more details.
See also: "Q3.1 My GUI freezes or doesn't update. What to do?"
Q3.3 I have arranged all my widgets nicely on a window. Then I
changed the OS / Java version / font / PLAF. Now everything is
broken. What's going on?
This sounds as if you don't use layout managers, but instead hard-coded
component sizes and widgets. If you want to avoid this problem, there
is no way around using layout managers, or implementing your own
geometry management from scratch.
Q3.4 My graphics on a Canvas/JPanel/JComponent, etc. gets
corrupted, or I get a null pointer exception when trying
to draw. How can I avoid this?
Do not use Component.getGraphics(). Instead, subclass and override the
paint() (AWT), or paintComponent() (Swing) method.
Component.getGraphics() simply can't work. Java's normal drawing mode
is called 'passive rendering'. It is based on a callback mechanism.
The drawing code is supposed to sit passively there until Java asks it to
draw something by calling your paint()/paintComponent() method.
At that moment you are supposed to provide the Component with the
drawings you would like to do by using the provide Graphics/Graphics2D
drawing context. You are not supposed to "push" graphics information
into a component using getGraphics() or any other means.
This mechanism is necessary so Java can support graphics systems which
don't remember a window's contents when it is obscured (e.g. overlayed
by another window). When the window becomes visible again, such
graphics systems have to ask the application to reconstruct the window
content. Therefore, paint()/paintComponent() is supposed to be the
memory of a component. getGraphics(), however, doesn't have any
recollection of previous drawing operations. So once a drawing done via
getGraphics() is lost, it can't be reconstructed. There is nothing in
there that stores the old drawing data, and there is nothing in
AWT/Swing which informs getGraphics() to do some re-drawing.
In addition, there are situations where Component.getGraphics() simply
returns null. This is a defined behavior of the method. And finally,
most users of getGraphics() forget to dispose the Graphics object after
usage, thus creating a resource leak.
See
<>
for more information about Java's normal painting model.
For very special cases (games, animations, slide shows, etc.), you might
want to flip to an 'active rendering' mode. Active rendering best works
when you wholly own the screen in full-screen exclusive mode.
See also: "Q4.4 What is full-screen exclusive mode?"
Q3.5 How to create a transparent or non-rectangular window?
You can't in a good, platform independent way.
Although particular Swing components can be 'transparent', the
problem is the top-level window. That window is always rectangular, and
in almost all Java implementations non-transparent.
Depending on your circumstances, platform, etc., one of the following
might (partly) work:
1) Ugly Hack, all platforms, Java 1.3+
One hack is to take a snapshot of the underlying screen region using
java.awt.Robot.createScreenCapture(rectangle). And then using that
snapshot as a background image for the window. If the background
changes, the illusion is gone.
<>
is a JFrame subclass which uses Robot to add transparency.
2) Windows
The nativeskin.jar of the Skin LnF at
<>
provides a Windows-only region feature for building non-rectangular
windows. It comes with a native Win32 library, so applications
written with this library are not portable to other platforms.
It should in principle be possible to write a similar library for
other GUI systems (e.g. X11 with the very common shape extension).
3) Apple OS X
Apple's Java for OS X observes the alpha-component of the window
background color, like one would expect from any Java
implementation. Therefore, any amount of transparency of a
top-level window can be configured by just constructing an
appropriate Color object and setting it as background color. E.g.
the following sets a completely transparent background:
window.setBackground(new Color(0, 0, 0, 0));
Non rectangular-looking windows can be constructed by
- Turning the normal window decoration off (if any), and
- Using an image (in a format which supports an alpha component,
e.g. PNG) as the window background.
4) Applet
An alternative for applets which might be good enough in some cases
can be found here:
<>
See also: "Q6.1.2 How to create a transparent widget?"
"Q6.1.3 How to create a non-rectangular widget?"
SECTION 4 - Architecture
~~~~~~~~~~~~~~~~~~~~~~~~
Q4.1 What is this Model-View-Controller (MVC) stuff?
MVC is a way to structure an application. It is based on the idea of
separating the presentation of data from the data itself. MVC
originated in the Smalltalk world and has since then become a common
design pattern.
Swing uses a variant of MVC (not THE original MVC as Smalltalk users
will point out).
The following TSC article contains a good description of Swing's
architecture and MVC variant:
<>
Q4.2 What is the Swing single-threading issue?
There is really no issue. With very few exceptions Swing is not thread
safe. But it can be safely used in a multi-threaded environment if the
necessary precautions are taken.
There are three simple things to take care of, not more:
1. Call all Swing API methods from the event dispatching thread
(EDT), unless the API documentation states that a method can
be called from another thread (is thread safe).
NOTE: The API documentation has been known to be wrong in
the past. Check Sun's bug parade when in doubt.
2. If you are not in the EDT, but need to call a Swing API
method, use either invokeAndWait() or invokeLater() to
schedule your code for execution on the EDT.
3. Do not block the EDT. That is, don't run time-consuming
tasks on the EDT. Instead, run these tasks in a separate
thread and use an invoke...() method to update the GUI from
that separate thread.
There is really nothing more to it.
See also: "Q3.1 My GUI freezes or doesn't update. What to do?"
"Q3.2 How do I update the GUI from another thread?"
"Q4.3 What is the right way to start a Swing GUI?"
Q4.3 What is the right way to start a Swing GUI?
Sun almost silently changed the recommended GUI startup procedure. At
the beginning of 2004 the examples in Sun's GUI tutorial were changed,
and some rather short "explanation" was given. The explanation can be
summarized as: "There is a threading bug somewhere in Swing. To work
around, already build and start the GUI from the EDT". No more useful
information is provided, e.g. if Sun knows the root cause of the bug
and intends to fix it.
So now the official way to build and start (calling setVisible(true))
the GUI is to use invokeLater(). The shortest version of a GUI
application's main() method becomes:
public static void main(String[] args) {
invokeLater(new Runnable() {
public void run() {
//
// Build and start the GUI here.
//
}
});
}
See also: "Q4.2 What is the Swing single-threading issue?"
Q4.4 What is full-screen exclusive mode?
As the name implies, a means to use the whole screen exclusively for
your applications, like it is e.g. needed for games, industrial control
applications, or slide shows. It was introduced with java 1.4.
You are much closer to the graphics hardware then in normal mode. This
requires some programming techniques which are different from normal
Swing/AWT programming. Full-screen exclusive mode is often used together
with active rendering. See
<>
Q4.5 What is active rendering?
Active rendering is an a drawing method where you 'push' your graphics
on the screen instead of the usual callback-based method ('passive
rendering') where you wait until you are asked to draw something.
Active rendering results in a completely different application
architecture, and is only recommended for games, animations, etc. It
works best in full-screen exclusive mode. It is often combined with
page-flip BufferStrategy.
See also: "Q4.4 What is full-screen exclusive mode?"
"Q3.4 My graphics on a Canvas/JPanel/JComponent, etc. gets
corrupted, or I get a null pointer exception when trying
to draw. How can I avoid this?"
PART II
========================================================================
SECTION 5 - Window / [J]Frame / [J]Dialog (Top-Level Containers)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Q5.1 How can I ensure a window is always on top of all other windows
using AWT or Swing?
1) Before Java 1.5 you couldn't at all:
AWT and Swing didn't provide this feature. All you could do was to
use a (modal) [J]Dialog, and make sure the [J]Dialog is provided
with the correct parent/owner in the constructor.
2) Since Java 1.5:
You have Window.setAlwaysOnTop(), which is inherited by the other
top-level containers like JFrame. However, the implementation is
incomplete, and not supported on all platforms. There are especially
problems with a number of Unix version / Window manager version
combinations.
Q5.2 How can I (de)iconify a window?
1) Before Java 1.2 you had to revert to native calls.
2) Since Java 1.2 you can use [J]Frame.setState().
3) Since Java 1.4 you can use [J]Frame.setExtendedState(), too.
setExtendedState() provides more features than setState().
Q5.3 How can I replace/remove the icon in the title bar (window
decoration) of a [J]Frame?
Use setIconImage().
To revert to the platform's default icon use:
frame.setIconImage(null);
On some platforms this might remove the icon. Alternatively you can try
a transparent Image if you don't want to have an icon.
Q5.4 How to replace the icon in the title bar (window decoration)
of a [J]Dialog?
There is only a partial solution to this problem, and it is not
recommended.
A dialog gets its icon from its parent frame. You can create a dummy
frame which you don't show, set the icon of that dummy frame, and use
it in the constructor of the dialog as the dialog's owner:
JFrame dummy = new JFrame();
Image icon = ...
dummyFrame.setIconImage(icon);
JDialog dialog = new JDialog(dummy);
However, this is dangerous. Certain GUI behavior depends on a correct
[J]Frame (parent window) <-> [J]Dialog (child window) relation.
Introducing a dummy parent breaks this relation. Things which can go
wrong include (de)iconising of all windows of an application, and
ensuring a modal dialog is always placed on-top of the main window.
Q5.5 My modal dialog goes behind the main window. How can I ensure
it is in front instead?
Make sure you have properly set up the 'owner' of the dialog in the
dialog's constructor. Don't use null, and don't use a dummy frame (to
set the dialog's icon).
Q5.6 How to bind the escape key to the JDialog cancel operation?
First the bad news. Some JComponent, like JComboBox or JTable use the
escape key by themselves. As a result, the following will not work,
unless you manage to remove the escape key handling from these
components.
To bind the escape key to some operation use code like it follows:
final String ESC_ACTION_KEY = "ESC_ACTION_KEY";
theDialog.getRootPane().getActionMap().put(
ESC_ACTION_KEY,
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//
// perform the action associated with the escape key
//
// e.g. inform all window listeners, or just call
// dispose()
//
}
});
theDialog.getRootPane().getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
ESC_ACTION_KEY
);
Q5.7 How can I implement my own JFrame/JDialog close handling?
Ironically, by setting the JDialog, JFrame, or JInternalFrame default
close operation to do nothing:
theJDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
And then adding an own window listener:
theJDialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
//
// Ask for closing confirmation,
// perform any necessary cleanup, etc. here.
// Close window if desired.
//
// we.getWindow().dispose(); // close window
}
});
Q5.8 How Do I center a window on the screen? How do I get the
screen size?
1) Manually, pre 1.4:
Use java.awt.Toolkit.getDefaultToolkit().getScreenSize() to get the
screen size, and do the math:
import java.awt.*;
Dimension winSize = win.getSize();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
win.setLocation(
(screenSize.width - winSize.width) / 2,
(screenSize.height - winSize.height) / 2
);
2) Since 1.4:
Window.setLocationRelativeTo(null);
Q5.9 How to ensure a minimum or maximum window size?
You can't in a good way under most conditions, and only in a limited
way under some conditions.
Swing and AWT ignore the minimumSize and maximumSize attributes under
most conditions. E.g. if your GUI system allows you to interactively
resize a window to the size of 1 x 1 pixels Swing/AWT will happily
allow this.
1) General hack and pre Java 1.4:
A few ugly hacks are possible to correct the size after the
unwanted resizing happened. They are ugly, because the window snaps
back, due to the fact that the original resizing is not prevent but
just corrected with another resizing.
This correction can e.g. be done with an event listener, listening
to window component resizing events. Or it can be done by overriding
the doLayout() method. In both cases, the actual size can be
obtained with getWidth()/getHeight() and, if the size is not
acceptable, corrected with setSize() (which triggers the second
resizing and makes the window jump).
2) Since Java 1.4:
In Java 1.4 JFrame.setDefaultLookAndFeelDecorated() was added. It
interacts in an undocumented way with the resizing. When set to
true, and when the platform allows a L&F window decoration, and when
that L&F window decoration is painted by Java (e.g. the Metal window
decoration), then the resizing behavior observes the limits as given
by the layout - usually.
In Java 1.4 a strange bug could sometimes be observed. When using
the platform's default L&F, and not the Metal L&F, then
JFrame.setDefaultLookAndFeelDecorated(true) changes only the
decoration to the Metal L&F decoration, but the window contents as
such is still drawn using the default PLAF. This results in a
strange mixture of L&Fs. However, the resize limits are observed by
such strange-looking windows.
3) Java 1.5:
JFrame.setDefaultLookAndFeelDecorated() still interacts with
resizing. And the multi-L&F bug has been kind of fixed. "Fixed" in
the sense that when JFrame.setDefaultLookAndFeelDecorated() is set
to true, not only the windows decoration is changed to the Metal
L&F, but also the window contents. Despite the fact that actually
the default L&F should be in force.
The conclusion is that a combination of Java 1.5, the Metal L&F, and
JFrame.setDefaultLookAndFeelDecorated(true) provides a reasonable
resizing behavior.
See also: "Q5.10 How to ensure a particular aspect ration of a window?"
Q5.10 How to ensure a particular aspect ration of a window?
You can't in a good way. You can use similar hacks as the ones for
enforcing a minimum or maximum window size.
See also: "Q5.9 How to ensure a minimum or maximum window size?"
Q5.11 How can I delegate the window placement to the window system
or manager?
First of all, you of course need to use a window manager or system which
is capable of placing the windows by its own. The rest depends on the
Java version:
1) Before Java 1.5:
You have no control over the behavior. If you don't specify an
explicit window position this might be interpreted as the position
(0, 0) and the window might be placed there, or it might be
interpreted as a request to position the window where it best fits.
The same might happen when you explicitly specify (0, 0) as the
position. Some systems interpret this as a request to place the
window where it best fits, others just position the window at (0, 0).
2) Since Java 1.5:
Sun has added a hack for specifying the desired behavior. If the
java.awt.Window.locationByPlatform system property is set to true, a
window manager can place a window with the origin (0, 0) or no
specified origin at will. If the property is false, a window with the
origin (0, 0) is indeed positioned at (0, 0).
The behavior can also be specified on a per window, per
setVisible(true) basis by using Window.locationByPlatform(true)
immediately before setVisible(true).
Q5.12 I need to take some toolbar (dock, panel) size into account when
calculating a window position an/or size. How?
The information is not available on all platforms. If you are lucky,
Toolkit.getScreenInsets() delivers information about the screen border
space occupied by the toolbar (dock, panel, or whatever your window
system uses). You can uses this information in your calculations.
Insets i = theWindow.getToolkit().getScreenInsets(
theWindow.getGraphicsConfiguration()
);
Do not assume that the desired size is e.g. always in Insets.bottom.
Many graphics systems allow to move the toolbar to the top or a side of
the screen, too. Or they allow to have multiple toolbars. Always take
all four values into account.
In general, for cross-platform compatibility, it is best to not rely on
this information at all. If it is essential for your application then at
least provide some configuration means to manually specify some screen
border space. This way people on systems where the information is not
available can still use your application as desired by you.
See also: "Q6.1.4 What are Insets?"
Q5.13 My window layout is displayed incorrectly. I have to move
the window, before the layout is right. What's wrong?
It is likely that you have changed the layout after you showed the
window. The layout is not redone in such cases, unless you tell the
container to do so. It is best to first finish the construction of
the window before showing it. If you really can't do this, then
1) for AWT:
Call invalidate() followed by validate() on the window.
2) for Swing:
Call revalidate() on the JComponent (JPanel) of which you changed
the layout.
Alternatively one can call pack() after invalidating the window.
Sometimes it is recommended to follow the validate()/revalidate() call
with a repaint(). This should not be necessary, If you have to do so,
it might be a component's opaque handling and or
paint()/paintComponent() method is broken.
See also: "Q8.1 What is the equivalent of AWT's Canvas in Swing?"
"Q8.2 When drawing on a JPanel, the background is garbled."
"Q3.4 My graphics on a Canvas/JPanel/JComponent, etc. gets
corrupted, or I get a null pointer exception when trying
to draw. How can I avoid this?"
Q5.14 How can I display a Splash Screen at the start of my Program?
In general, if you add a splash screen to your application, be nice to
your users and allow it to be turned off via some configuration option.
Splash screens can become very annoying.
1) Up and including Java 1.5
Use an (AWT) Window to display some image. Even if your application
has a Swing based GUI, you should only use AWT classes to build the
splash screen. You will anyhow have to wait until the VM comes up, but
you avoid having to wait for the loading of the huge amount of Swing
classes if you restrict yourself to AWT.
2) Since 1.6
The VM has a command line option for specifying a splash screen
image. That image is displayed even before the VM runs any Java
code. It can be an animated GIF.
java -splash:splashImage.gif ...
Java 1.6+ also has an API for accessing and manipulating the splash
screen once the Java program is running. See the
java.awt.SplashScreen class.
And Java 1.6+ has a corresponding Manifest file keyword for
specifying a splash screen image:
SplashScreen-Image: splashImage.gif
SECTION 6 - [J]Component (Widgets)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6.1 General Questions
Q6.1.1 How do I position components (widgets) on a window?
You add them to [J]Panels and use one or more of the many layout
managers that come with Java (one for each [J]Panel). And you leave the
exact calculation of the position to the layout managers.
Learning the layout managers is essential to AWT and Swing
programming. Many people don't buy this and think they can get away
without. Later they come to the newsgroup and whine because their GUIs
don't work on other platforms, or don't look good when resized. But
whining will not change their GUIs or the way AWT/Swing works. You have
been warned.
See and work through:
<>
Q6.1.2 How to create a transparent widget?
First of all it should be noted that being able to have transparent
widgets does not guarantee a transparent window, where the desktop
shines through. In fact, in general the non-transparent top-level
window is where transparency stops.
Since the introduction of the lightweight framework in Java 1.1 it is
possible for a Component subclasses (if lightweight) to have
transparent parts if properly implemented. Lightweight Swing Components
are a special case, since Swing adds a switching mechanism so Swing
components can basically be switched to have a transparent or filled
background.
So there are three different cases:
1) Component (excluding Swing and heavyweight) subclasses
All it takes is a subclass of Component with a paint()
implementation that only draws the non-transparent parts.
If an existing lightweight Component is subclassed to build a
transparent component, it should be made sure that the superclass
doesn't fill the background with the background color in the paint()
method.
2) JComponent (Swing) subclasses
The Swing JComponent subclasses can usually be switched between
painting all pixels within their boundaries or not. This, purely as
a side-effect, effectively allows the programmer to control if the
JComponent's background is non-transparent or transparent.
This behavior is a side-effect of the opaque contract between
JComponents and the Swing repaint manager.
setOpaque(false)
kindly ask a JComponent not to paint all pixels within its
boundaries. For most, but not all, Swing components this results in
a transparent background. If opaque is false, their paintComponent()
method simply does not fill the background before painting the
component. Also, the repaint manager, it it finds a component with
isOpaque() == false, walks the component hierarchy to find the
component below the current one. Because that one needs to be
repainted first, to provide the background.
Setting setOpaque(false) doesn't work for all JComponents. E.g. some
contain nested component (e.g. JScrollPane) which need to be changed
to be transparent, too. Or some PLAFs ignore the opaque attribute
and always paint every pixel within their bounds. This behavior is
not illegal, it is still covered by the opaque contract. But it
means that the desired side-effect (transparency) of setting opaque
to false will not work.
3) Heavyweight Components
Transparent heavyweight components are not supported in Sun's
Java implementation.
See also: "Q3.5 How to create a transparent or non-rectangular window?"
"Q6.1.3 How to create a non-rectangular widget?"
Q6.1.3 How to create a non-rectangular widget?
The boundaries of a Component (widget) in Java are always rectangular.
Non-rectangular Components can be faked by implementing Components with
a transparent background.
Java will still treat these components as rectangular objects. E.g. The
standard layout managers always use the rectangular boundaries to
layout Components. If another behavior is required for transparent
Components (e.g. partly overlapping boundaries) custom layout mangers
need to be implemented.
See also: "Q3.5 How to create a transparent or non-rectangular window?"
"Q6.1.2 How to create a transparent widget?"
Q6.1.4 What are Insets?
1) Simple answer:
Insets is a data type, describing additional space around some type
of rectangle space, e.g. a component. A better choice of words would
have been border space.
2) More detailed answer:
There is no consistent usage of the term or the Insets data type in
AWT or Swing. Originally Insets were used in AWT to describe the size
of window decorations, like the size of a Frame's title bar, and
borders in a GridBagLayout. Over the time Insets popped up in all
sorts of places in AWT and Swing. Often there is no exact definition
of what an Insets data type describes, especially in relation to the
size of an item.
For a particular usage of Insets one has to figure out if the Insets
describe additional or subtractive space. Roughly, one has to figure
out, often by experiment, which of the following holds true for a
particular situation:
usable size = item size - insets
total size = item size
or
usable size = item size
total size = item size + inset
The exact relation doesn't matter in the trivial case
Insets = {0, 0, 0, 0}
Q6.1.5 How do I find a component's top-level container (e.g.
the window)?
Use
SwingUtilities.getRoot()
6.2 JTree
Q6.2.1 I changed the data / structure for my JTree, but the display
doesn't get updated. What's going on?
Most likely you are directly manipulating the TreeNodes, instead of
updating the data via the TreeModel. TreeNodes don't have any means to
inform the JTree about changes. This is the job of the TreeModel.
If you use DefaultTreeModel, all the event notification mechanisms are
already implemented. If you use an own implementation of TreeModel, you
need to implement the necessary event firing yourself.
Don't call repaint() on the JTree. The JTree painting is not broken.
Your event notification is. Get your event notification right.
Q6.2.2 How do I set a custom icon for a node?
If you just want to change the icon for all nodes from the default, get
a DefaultCellRenderer, use the set...Icon() methods, and set the
renderer to be used by the JTree.
If you, however, need different icons for different nodes, then the
following three steps are involved.
1. Create your own TreeNode implementation (or subclass an existing
TreeNode implementation). The following code fragment shows some
suggestions.
public class ABCTreeNode implements TreeNode {
//
// a. Add some means to the TreeNode to identify itself, e.g.
//
public int getType() { /* return a type id */ }
//
// b. Or let the TreeNode return a corresponding Icon
// (possibly a shared instance):
//
// public Icon getLeafIcon() { /* return icon */ }
// public Icon getOpenIcon() { /* return icon */ }
// public Icon getClosedIcon() { /* return icon */ }
//
// c. Or just rely on the type of your subclass (to be
// checked with instanceof). You will have to have an
// own subclass for each node which needs a different
// icon.
//
//
// d. Or let the TreeNode return some layout info object
// which then provides getXXXIcon() methods.
//
// public TreeNodeInfo getInfo() { /* return info object */ }
//
...
}
2. Subclass DefaultTreeCellRenderer. Override
getTreeCellRendererComponent():
public class ABCTreeCellRenderer extends DefaultTreeCellRenderer {
Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
{
//
// Continue, depending on your ABCTreeNode
// implementation,
//
//
// a. If you use a getType() method:
//
ABCTreeNode node = (ABCTreeNode)value;
switch(node.getType()) {
case: ...
setLeafIcon(...);
setOpenIcon(...);
setClosedIcon(...);
break;
}
//
// b. If you use a getIcon() method:
//
// ABCTreeNode node = (ABCTreeNode)value;
// setLeafIcon(node.getLeafIcon());
// setOpenIcon(node.getOpenIcon());
// setClosedIcon(node.getClosedIcon());
//
//
// c. If you rely on the type:
//
// if(value instanceof ABCTreeNode) {
// setLeafIcon(...);
// setOpenIcon(...);
// setClosedIcon(...);
// } else if(value instanceof ...) ...
//
//
// d. Use the info object:
//
// ABCTreeNode node = (ABCTreeNode)value;
// ABCTreeNodeInfo info = node.getInfo();
// setLeafIcon(info.getLeafIcon());
// setOpenIcon(info.getOpenIcon());
// setClosedIcon(info.getClosedIcon());
//
//
// Finish with:
//
return super.getTreeCellRendererComponent(
tree, value,
sel, expanded, leaf,
row,
hasFocus);
}
...
}
3. Finally, use JTree.setCellRenderer() to set your renderer.
Q6.2.3 How do I remove all my nodes from a JTree at once?
Just replace the model. Deleting all nodes individually is a waste of
time.
JTree's API documentation does not indicate if it is permissible to use
null as a model, but it is known to work in Sun's reference
implementation:
tree.setModel(null);
If you don't trust his code, create an empty model and use it instead
of null.
6.3 Styled Text / JEditorPane / JTextPane
Q6.3.1 Can I use RTFEditorKit to read RTF documents created by Word?
Well, you can try. The RTFEditorKit is, however, very limited. There is
a subtle hint in the RTFEditorKit API documentation. It points out that
the Swing team "hops" to improve the class in the future. This hint is
there since the first release of the class years ago.
The newer your Word is, the less likely it is that the RTFEditorKit can
read the RTF. There have been reports about crashes when using RTF
generated by the latest Word version.
Q6.3.2 I have problems using the Swing HTML parser to parse all
kinds of HTML. Is this normal?
Unfortunately it is. The Swing HTML parser is the old HotJava parser
(Sun's pure Java web browser, once a separate product). It is limited
and hasn't been updated for a long time. In principle it can deal with
HTML 3.2 and style sheets. In practice it is picky.
Use another parser if you have problems, or convert your HTML with HTML
Tidy or its Java port JTidy before trying to read it.
<>
<>
Q6.3.3 Some of my CSS styles don't work out. Is this normal?
Yes, for the same reasons as described in the previous answer. See the
class javax.swing.text.html.CSS for a list of the officially supported
CSS attributes, and brace yourself for some more deviations.
Q6.3.4 Can I use Swing's HTML support to write a web browser?
You can, but the resulting browser will suffer from the limitations of
Swing's HTML parser and CSS handling. The parser was in fact originally
developed for Sun's HotJava web browser. But this was years ago, and
HotJava was never a serious competitor in the browser business.
To get some ideas have a look at
<>
Q6.3.5 Can I use Swing's HTML support to build an on-line
help system or e-book?
Sure you can. Or, you could take Sun's JavaHelp, which does exactly
this. It uses the Swing HTML components to parse and render help text
or other text written in HTML. It also provided for navigation and
other common help features.
Q6.3.6 If HTML support is really so broken in Java, what is it
good for?
As long you control the generation of the HTML it is quite usable. E.g.
the JavaHelp system uses Swing's HTML parser and display capabilities.
If you need to handle real-world HTML from sources not under your
control, you better look for some other parser. E.g.
<>
gets recommended often.
6.4 [J]TextArea
Q6.4.1 I append text to a JTextArea. How to ensure the text
area is always scrolled down to the end of the text?
textarea.setCaretPosition(textarea.getDocument().getLength());
Q6.4.2 How to use several different fonts (styles, sizes) in
one [J]TextArea?
You can't. Use a J[Editor|Text]Pane.
6.5 [J]Label / [J]Button
Q6.5.1 How can I have multiple Lines in a [J]Label?
1) Label
You can't. Use a TextArea instead, and turn editing of the TextArea
off.
2) JLabel
2.a) Use HTML markup in the label's Text. E.g.:
theJLabel.setText("<html>Line 1<br>Line 2<br>Line 3</html>");
2.b) Or use a JTextArea.
Q6.5.2 I want to have a hyperlink in a [J]Label. How can I do this?
You probably don't want to have a label, but a button.
Just configure a JButton so it looks like a link. E.g. use HTML to
format the button's text, and remove the button's border:
b = new JButton("<html><a></a><html>");
b.setBorderPainted(false);
Provide the button with an ActionListener to handle the ActionEvent
when the button is clicked. Implement whatever is desired in the event
handler. E.g. start an external web browser.
b.addActionListener(new ActionListener() {
actionPerformed(ActionEvent e) {
// start web browser
}
});
Q6.5.3 How do I make a JButton the default button in a JDialog?
It is rather counter-intuitive, by telling the root pane of the JDialog
about the button:
theJDialog.getRootPane().setDefaultButton(theJButton);
Some PLAFs might ignore this setting.
SECTION 7 - JScrollPane
~~~~~~~~~~~~~~~~~~~~~~~
See also: "Q6.1.2 How to create a transparent widget?"
"Q6.4.1 I append text to a JTextArea. How to ensure the text
area is always scrolled down to the end of the text?"
Q7.1 I added a component (e.g. a JPanel with an image) to a
scrollpane, but the scrollpane doesn't show it at the right
size / without scrollbars, etc. What's wrong?
Ensure that the component you added does return its desired size via
getPreferredSize(). E.g. if you have a JPanel holding an image, ensure
that the JPanel's getPreferredSize() returns the size of the image.
PART III
========================================================================
SECTION 8 - Graphics & Painting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See also: "SECTION 3 - The Top 5 Questions"
Q8.1 What is the equivalent of AWT's Canvas in Swing?
It depends on your purpose, and on the level of compliance you want to
have with the Swing opaque handling.
Use
a) JPanel, if you want to have a "complete" component with a
UI delegate which handles opaque settings (if
paintComponent() is correctly overridden).
b) JComponent, if you intend to always draw every pixel in the
area of the component (and break the opaque attribute API
contract, don't worry, most likely no one will notice). If
you need to have your own special key and mouse processing,
you might also want to start with JComponent and create
your own UI delegate.
c) You could even start higher up in the inheritance chain.
java.awt.Component is lightweight since Java 1.1. However,
you will not get Swing additions like double-buffering.
d) Canvas. No joke. Under very special circumstances (e.g.
game programming, accelerated graphics) AWT's Canvas might
be the right thing to use, even under Swing. Under normal
circumstances, however, this is not the right choice,
because it brings the problem of mixing heavyweight and
lightweight components.
If this is all Greek to you, use JPanel. And remember, if you use
JComponent or JPanel, override paintComponent(), not paint().
Q8.2 When drawing on a JPanel, the background is garbled.
It is likely that you managed to break the opaque handling of the
component. Your JPanel instance promises (via getOpaque()) to draw
each and every pixel under its influence, but doesn't.
Start your paintComponent() method with a call to
super.paintComponent(g) (which honors the opaque attribute and fills
the background with the background color). Also, check the setting of
the opaque flag, and have a look at the TSC article about "Painting".
See the list of resources at the end for a link.
Q8.3 How do I generate some charts / plots in Java?
If you want to do the drawing in Java, consider using a chart drawing
library. E.g.
<>
<>
get recommended often. The web site also has a list of other chart
libraries.
If you just have to plot some (scientific) data, and if you can live
with an external C program, consider using gnuplot
<>
Millions of scientific papers around the world have been illustrated
with gnuplot output.
Use Runtime.exec() to pipe the plot commands and data into gnuplot, or
just write the data to a file and use gnuplot separately.
Q8.4 How to draw some graphs in Java?
Non-trivial graph drawing is a serious business. If you want to do it
all by yourself, reserve some time and start studying graph drawing
algorithms. See the question "I need an algorithm for drawing ..." for
information where to start searching for such algorithms. Then, or in
parallel, start studying the Java 2D API.
If you don't want to concern yourself with the algorithm
implementation, use a graph library like:
<>
<>
Or check if the algorithm used in Sun's GraphLayout applet demo is
suitable for your purpose. The source comes with every SDK, see the
directory
demo/applets/GraphLayout
in you SDK installation.
If you can live with an external C tool, give The Dot a try. It is part
of graphviz at
<>
Or, if you don't require a Java solution and if you are on a Unix with
a complete troff installation, including pic, you can use pic for
typesetting simple graphs.
See also: "Q8.9 I need an algorithm for drawing ..."
Q8.5 I want to write a diagram editor. Where to start?
Consider using a framework like
<>
<>
<>
for a start. You also might want to familiarize yourself with many of
the design patterns in
Gamma, E.; Helm, R.; Johnson, R.; Vlissides, J.: Design
Patterns: Elements of reusable object-oriented Software.
Addison-Wesley professional computing series. Brian W.
Kernighan, Consulting Editor. Reading, MA: Addison-Wesley,
1994.
And (if you manage to find the old publications), the early work on
UniDraw and IDraw by Vlissides is also interesting (in C++).
Q8.6 How do I draw lines between JLabels on a JPanel?
You are apparently trying to draw a graph by using normal widgets to
draw the nodes of your graph. This is not a good idea. Consider using
the Java 2D API (nowadays part of J2SE) to draw the complete graph.
Have a look at java.awt.geom for predefined shapes. Also check out
Sun's 2D Programmer's Guide.
Q8.7 How to debug graph painting?
The best way is probably to use a debugger and step through the
paint[Component]() method. There is also the rather obscure
JComponent.setDebugGraphicsOptions() method in Swing. It can be used
to turn several kinds of debugging output on or off.
Please note that setDebugGraphicsOptions(0) does not turn debugging off.
Instead setDebugGraphicsOptions(DebugGraphics.NONE_OPTION) is needed.
See also: "SECTION 12 - Resources"
Q8.8 I need to draw a tree. How?
This seems to be a common homework question, so please have a look at
the "Which topics are not welcome in the newsgroup?" to understand why
this answer is intentionally vague.
If the fixed layout of JTree suits your needs, you could start reading
the JTree API documentation.
Or you could use a simple (recursive) algorithm. E.g
x(node) = K * level(node), and
y(node) = M * inorder_rank(node).
gives very ugly trees, but trees. If this doesn't get you started, ask
your professor or tutor for more hints. Consult your text book about
(inorder) tree traversal, and consult
<>
Q8.9 I need an algorithm for drawing ...
First of all, it really helps to know a little bit about math and
geometry. It also helps to know a little bit about coordinate
transformations. Then start with the FAQ for
<news:comp.graphics.algorithms>
which is at
<>
Q8.10 When I subclass JPanel/JComponent, I need to override paint(),
right?
Wrong. You are supposed to override paintComponent(), not paint(). You
would override paint() only when subclassing Canvas.
Swing has a slightly different painting model than AWT. Have a look at
the painting article in TSC. This is highly recommended reading if you
plan to do any kind of drawing or develop a custom component.
See also: "SECTION 12 - Resources"
Q8.11 Why does drawImage() fail when I try to display a loaded image?
Why are the width and height of my loaded image both zero?
The image has most likely not finished loading. Use a
java.awt.MediaTracker to monitor the loading of the image (see the
MediaTracker API documentation for details and an example).
Alternatively, use javax.swing.ImageIcon to load the image. It already
contains the necessary MediaTracker handling.
Q8.12 How do I resize (zoom in/out) my Graphics?
First of all, it is best to not touch your original data if the
resizing is only for display purposes.
So, if you just want to resize the graphics for display purposes you
have to work on three areas:
1. Use an AffineTransform to construct an appropriate transformation
(see its scale() method). You can also use the Graphics2D.scale()
convenience method instead. In both cases, however, you should
ensure that you reset the Graphics2D object in your paintComponent()
method to its original transformation before leaving the method.
2. When you do zooming, it might be handy to not only scale the
graphics, but to also resize the JPanel on which you are drawing, so
the JScrollPane in which you have placed the JPanel updates its
scrollbars accordingly. Be aware, however, that the JPanel size is
in device coordinate space, while your geometry data is hopefully in
user coordinate spaces.
double zf = 1.0;
public void setZoom(double zf) {
// better do some sanity check on the
// zoom factor, too
this.zf = zf;
theJPanel.setPreferredSize(baseWidth * zf, baseHeight *zf);
theJPanel.repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//
// Save the old AffineTransform state of the
// graphics object. Either by remembering the
// AffineTransform, or by just working on a
// copy of the Graphics object.
//
// Variant (a): Save the old AffineTransform
Graphics2D g2d = (Graphics2D)g;
AffineTransform orig = g2d.getTransform();
//
// Variant (b): use a copy of the Graphics context
// Graphics2D g2d = (Graphics2D) ((Graphics2D)g).create();
//
// Now scale the Graphics context
//
g2d.scale(zf, zf);
// ~~~ Draw graphics here ~~~
//
// Reset Graphics state before leaving
// Variant (a): If old AffineTransform has been saved:
// Reset transformation
g2d.setTransform(orig);
//
// Variant (b): If a copy of the graphics was used:
// Just destroy copy
// g2d.dispose();
}
3. If you provide some means to select parts of the graphics or
interact in some other way with the graphics using the mouse, you
have to scale (divide by the zoom factor) the mouse event
coordinates, too. You could also use an AffineTransform with the
inverse scaling for this, but for the simple linear scaling used for
zooming, dividing the coordinates will do.
The easiest is probably to do this calculation in the event handler
which is supposed to provide the interaction with the graphics.
Sometimes it is suggested to use the glass pane to intercept all
mouse events of the JPanel and transform them before forwarding.
Q8.13 Where do I find the icons which are used by Swing
itself?
Most of them are hard-coded, and a lot of them don't have any
documented public API and are hidden in the PLAF's implementation. Some
can be found in javax.swing.plaf.basic.BasicIconFactory, the ones for
Metal can be found in javax.swing.plaf.metal.MetalIconFactory.
In general, most PLAFs list their icons in the UIDefaults.
See also: "Q10.4 How do I get all the UIDefaults, and what do they mean?"
Q8.14 Where do I find typical application icons?
See also: "12.3 Icons"
SECTION 9 - Fonts
~~~~~~~~~~~~~~~~~
See also: "Q6.4.2 How to use several different fonts (styles, sizes) in
one [J]TextArea?"
"Q3.3 I have arranged all my widgets nicely on a window. Then I
changed the OS / Java version / font / PLAF. Now everything is
broken. What's going on?"
"Q10.3 How do I change a color/font/etc. globally for an
application?"
"Q10.4 How do I get all the UIDefaults, and what do they mean?"
Q9.1 Which Fonts can I use? Can I use font <xyz>?
See the API documentation of the Font class for a start:
<>
Q9.2 How to turn on text antialiasing in Swing?
First of all, people have reported mixed results with using
antialiasing in Swing. The improvement is sometimes not as expected,
depending on the font, font size (it works better with larger fonts),
font renderer in use, and e.g. monitor resolution. So it is best to
test the results on the target platform, and make it a configurable
option.
1) Before Java 1.5:
Turning text antialiasing on for one particular component is
relatively simple, turning it on for all components of a GUI is a
nightmare.
To turn antialiasing on for a component you have to subclass and
override paintComponent():
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON
);
g2.setRenderingHint(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY
);
super.paintComponent(g2);
}
}
To turn antialiasing on for a whole GUI you would have to subclass
all used components the way described above, and then only use this
components. Or use a PLAF which does this for you. Such PLAFs are
e.g.
<>
<>
2) Since Java 1.5
It is now possible to globally turn on text antialiasing by setting
the system property "swing.aatext" to "true" on the command line.
The pre Java 1.5 methods still work, too.
Q9.3 Why do some of my characters get displayed as squares?
1) If this happens in a GUI
Java didn't find matching a visual representation (glyph) in the
font you used. In such a case Java uses a square to denote that it
doesn't know how to draw the character.
The fix depends on what you intended to do:
1a) If you indeed intended to display the character in the GUI, then
you need to find and use a font which contains the glyph for the
character.
<>
has some information which glyphs can be found in Java 1.5's
bundled physical fonts.
The documents at
<>
<>
describes how Java's font lookup happens, and how this can be
changed on VM level. However, using java.awt.createFont() is much
more preferable than requiring an end-user to change the VM
configuration.
1b) If you didn't intend to display the character, then you probably
felt victim to the fact that many Java widgets don't interpret
control characters like new-lines in Strings.
For example JLabel or JButton do not do this. Instead, they just
try to render the character with a glyph. But usually a font
doesn't contain glyphs for control character code points. So you
get squares instead.
If you need to get control characters interpreted, then in AWT you
would need to implement an own widget (based on a Canvas), which
lays-out the text as desired. In Swing you can use HTML formating
for most widgets:
// Does not work:
JLabel jl = new JLabel("Line1\nLine2");
// Use this instead:
JLabel jl = new JLabel("<html>Line1<br>Line2</html>");
If you don't want the characters at all, you have to remove them
from the String.
2) You tried to print to the text console
This is not a GUI related issue. Most likely the console works with
a character set which doesn't contain that character at all.
SECTION 10 - Other Common Questions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Q10.1 My GUI has rendering problems when the JMenu opens over my
top Panel ...
Swing (JMenu) and AWT (Panel) components do not mix well.
See
<>
for things you have to pay attention to.
Q10.2 Can I use Swing for Applets?
You can, if you know that the users of your applets have a Java version
installed which supports Swing. Swing was first shipped with Java 1.2
(it was available earlier as a separate download). Java 1.2 is an old
Java version. You will most probably not develop a Swing application
with it. As a consequence, it is likely that your users need browsers
which support even later Java versions and match your development
version.
Sun provides the Java plug-in in the JRE to update the legacy Java
versions of some browsers to a current Java version. Your applet users
might have to download and install the JRE with the plug-in
separately:
Programmers:
<>
Consumers:
<>
Alternatively, you should consider to provide your Swing program as an
application, not an applet, and use Java Web Start to deploy it:
<>
JavaWebStart is nowadays also a part of the JRE.
Q10.3 How do I change a color/font/etc. globally for an
application?
1) In case you are using Metal, the best way is to implement an own
javax.swing.plaf.metal.MetalTheme, and set it via
javax.swing.plaf.metal.MetalLookAndFeel.setCurrentTheme().
2) For other PLAFs, there is no common API. You can either try to
figure out some undocumented feature, or use the also undocumented
UIDefaults, from which most of the common PLAFs take definitions for
colors, fonts, etc.
See also: "Q10.4 How do I get all the UIDefaults, and what do they mean?"
Q10.4 How do I get all the UIDefaults, and what do they mean?
The UIDefaults contain all kinds of undocumented default settings for
the current PLAF, like colors, icons, fonts, etc. One can guess the
meaning of most of them from the key name, but the keys change for
different PLAFs and VM implementations.
UIManager.getDefaults() returns the UIDefaults. The returned data type
implements, among other things, the Map interface. One can iterate over
this map and display all key/value pairs. There are several small
programs out there doing exactly this, e.g. a popular one is
ShowUIDefaults.java
Q10.5 Why is Swing so slow?
Swing is slow in the hands of unexperienced GUI programmers. In fact,
it has become a common excuse among these to blame Swing for their own
shortcomings. Shortcomings which for example include a lack of
understanding of the Swing event model or of the repainting mechanism.
Abusing a layout manager is also very popular.
See also: "Q3.1 My GUI freezes or doesn't update. What to do?"
"Q3.2 How do I update the GUI from another thread?"
"Q3.4 My graphics on a Canvas/JPanel/JComponent, etc. gets
corrupted, or I get a null pointer exception when trying
to draw. How can I avoid this?"
"Q4.2 What is the Swing single-threading issue?"
SECTION 11 - Non-GUI Questions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Q11.1 How do I do a text/console UI in Java?
Java is not well-suited for non-graphical user interfaces. You need
platform specific libraries for any sophisticated text UI.
The most common ones are based on the Unix curses/ncurses library, like
JCurses:
<>
Note: there happen to be several different libraries out there by the
name JCurses or jcurses which are not entirely compatible.
Another possibility is charva, a text-base UI toolkit on Linux mimicking
the Swing API:
<>
Q11.2 How can I do this JavaScript thing on my web site?
Java is not JavaScript. Try
<news:comp.lang.javascript>
or another suitable JavaScript newsgroup.
Q11.3 I want to make ...
First, programmers usually don't "make" things, they program things :-)
Precise language helps when you try to communicate with other
programmers.
The first step to program something is to learn a programming language
like Java. Then you need some knowledge about algorithms and data
structures. For Java you also throw in some object-oriented concepts
and principles. But that's not all. There are many more things to
learn, and you can't rush things. See
<>
Since this is the comp.lang.java.gui FAQ, you should also know that it
takes specific skills to develop good or excellent graphical user
interfaces. GUI programming is not just about stirring some widgets
together. It is about good taste, a devotion to details, some knowledge
about color choices, font styles, human-computer-interaction (HCI),
style guides, etc. pp. Especially, Java GUI programming is not HTML
"programming".
In short, if you are in a rush to "make" something, if you can't be
bothered to learn the basics, consider something simpler than Java and
its GUI toolkits. And no, whining doesn't help.
SECTION 12 - Resources
~~~~~~~~~~~~~~~~~~~~~~
There are many good on-line resources regarding Java GUI programming
out there. The following list is limited by intention to resources
which get recommended often on c.l.j.g, including resources from
regulars.
12.1 Sun's Java Web Site
* Sun's Swing learning by example tutorial (previously the Example
Tutorial, and before that the Quick-Start Tutorial):
<>
* Sun's complete Swing Tutorial:
<>
* The courses at
<>
* Sun's Swing Connection (TSC) (Swing developer's site):
<>
With the TSC article index (Swing architecture, Swing and threads,
painting architecture, etc.):
<>
12.2 Other Sun Sites
There are some GUI articles (some of them dated) at:
<>
12.3 Icons
It is suggested to check the licenses of each icon collection before
using them in any products.
Sun's well hidden set of Icons for Swing's Metal LnF:
<>
More icons:
<>
(the link to javalobby.org on that page is broken)
The Ximian Open-Office icons (very nice):
<>
Gnome Icons:
<>
SVG BlueSphere Icon Theme:
<>
KDE Icons:
<>
<>
12.4 Miscellaneous Examples, Tips and Tricks
A collection of examples for doing nice things with Swing components
(some are a little bit outdated):
<>
Originally from
<>
which is now off-line.
Christian Kaufhold's Java and Swing info (including JTable info):
<>
Jeanette's notes (including JTable remarks):
<>
Marco Schmidt's Java resource page (Java imaging information)
<>
Karsten Lentsch's company web page:
<>
12.5 Style Guides
Java Look and Feel Design Guidelines:
<>
Java Look and Feel Design Guidelines: Advanced Topics:
<>
12.6 SDK Documentation
GUI Information in the SDK documentation is commonly overlooked, but
worth some reading:
See your local SDK installation, or
Abstract Window Toolkit (AWT)
<>
Swing
<>
2D Graphics and Imaging
<>
Image I/O
<>
Print Service
<>
Input Method Framework
<>
Accessibility
<>
Drag-and-Drop data
<>
Swing Examples in the SDK:
See the directory demo/jfc in your Java SDK installation.
12.7 More Swing
Swing class-hierarchy chart
<>
jGuru Swing FAQ
<>
CodeGuru Swing Examples
<>
12.8 Online Magazines
JavaWorld has regular GUI articles. The magazine closed shop on
2004-01-02, but was re-launched March 2004.
<>
12.9 Java 2D API
The Programmer's Guide
<>
See also the other SDK documentation.
The 2D Tutorial (a light introduction, avoids the tough stuff):
<>
Sample code
See the demo/jfc directory of your SDK installation. Same as:
<>
12.10 Java 3D API
There is a separate newsgroup. see
<news:comp.lang.java.3d>
<comp.lang.java.3d">>
12.11 General Java
The Java Tutorial:
<>
All kinds of tutorials:
<>
Roedy's Java Glossary:
<>
12.12 More?
Q12.12.1 But I need more!
Look at the source code. Every SDK comes with the source code of the
public parts of the API. The source code is packed in a file called
src.zip or src.jar (older SDKs), usually right in the top level
directory of your SDK installation.
Also, learn how to use a search engine like
<>
SECTION 13 - Improvement Suggestions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please mail suggestions, corrections, updates, etc. to the author
"cljg_faq" at the host "gmx.de". Your "Subject:" line must contain the
string
[cljg]
somewhere in the line, including the square brackets. Otherwise your
mail will be discarded automatically. In addition, the address is
heavily spam-protected. So if you mail from a spam-invested network,
there is little chance to reach the author. Your alternative is to post
to c.l.j.g.
If you suggest a new entry, please also provide the answer, not only
the question.
SECTION 14 - Acknowledgments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This FAQ contains contributions and help from:
Andrew Thompson, David Postill, Manish Hatwalne, Hiwa, Jeanette.
# # #
|
http://www.faqs.org/faqs/computer-lang/java/gui/faq/
|
CC-MAIN-2016-30
|
refinedweb
| 12,430
| 68.57
|
Quarkus: application upgrades with helloworld from JBoss EAP Quickstart
The previous post was about how Quarkus combines MicroProfile and Spring. Recall that Quarkus It is positioned as “ultra-fast subatomic Java”, it is also “Kubernetes-oriented Java-stack, sharpened by GraalVM and OpenJDK HotSpot and compiled from the best libraries and standards.” Today we will show how to upgrade existing Java applications using the capabilities of Quarkus, using an example helloworld applications from the Red Hat JBoss Enterprise Application Platform (JBoss EAP) Quickstart repositorywhich uses the CDI and Servlet 3 technologies supported in Quarkus.
It is important to note here that both Quarkus and JBoss EAP focus on using tools that are built to the maximum standards. Don’t have an app running on JBoss EAP? Not a problem, it can be easily migrated from the current application server to JBoss EAP using Red Hat Application Migration Toolkit. After that, the final and working version of the upgraded code will be available in the repository github.com/mrizzi/jboss-eap-quickstarts/tree/quarkusin the module helloworld.
When writing this post were used Quarkus Guides, primarily Creating your first application and building a Native executable.
We get a code
First, create a local repository clone JBoss EAP quickstarts:
$/
See how the original helloworld works
Actually, the essence of this application is clear from the name, but we will upgrade its code strictly scientific. Therefore, to begin with, look at this application in its original form.
Expand helloworld
1. Open the terminal and go to the root of the JBoss EAP folder (you can download it here), i.e. to the EAP_HOME folder.
2. Start the JBoss EAP server with the default profile:
$ EAP_HOME/bin/standalone.sh
Note: on Windows, the EAP_HOME bin standalone.bat script is used to run.
After a couple of seconds, the following should appear in the log:
)
3. Open in the browser 127.0.0.1: 8080 and see this:
Fig. 1. JBoss EAP Homepage.
4. Follow the instructions in the manual Build and deploy the quickstart: deploy helloworld and execute (from the project root folder) the following command:
$ mvn clean install wildfly:deploy
After successful execution of this command in the log, we will see something like the following:
[INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 8.224 s
So, the first deployment of the helloworld application on JBoss EAP took just over 8 seconds.
Testing helloworld
Acting strictly on leadership Access the applicationopen in browser 127.0.0.1: 8080 / helloworld and see this:
Fig. 2. Source Hello World from JBoss EAP.
Make changes
Change the input parameter createHelloMessage (String name) from World to Marco:
writer.println("
" + helloService.createHelloMessage("Marco") + "");
Again, run the following command:
$ mvn clean install wildfly:deploy
Then we refresh the page in the browser and see that the text has changed:
Fig. 3. Hello Marco at JBoss EAP.
Roll back helloworld deployment and shut down JBoss EAP
This is optional, but if you want to cancel the deployment, you can do this with the following command:
$ mvn clean install wildfly:undeploy
To shut down the JBoss EAP instance, simply press Ctrl + C in the terminal window.
Upgrading helloworld
Now let’s upgrade the original helloworld application.
Create a new branch
Create a new working branch after the quickstart project finishes:
$ git checkout -b quarkus 7.2.0.GA
Change the pom.xml file
We will start changing the application from the pom.xml file. So that Quarkus can insert XML blocks into it, execute the following command in the helloworld folder:
$ mvn io.quarkus:quarkus-maven-plugin:0.23.2:create
When writing this article, version 0.23.2 was used. Quarkus often has new versions, you can find out which version is the latest on the website github.com/quarkusio/quarkus/releases/latest.
The above command will insert the following elements into pom.xml:
- Property
specifying the version of Quarkus to use.
- Block
to import Quarkus BOM (bill of materials) so as not to add a version for each Quarkus dependency.
- The quarkus-maven-plugin plugin, which is responsible for packaging the application and providing development mode.
- A native profile for creating application executables.
In addition, we manually make the following changes to pom.xml:
- Pull out the tag
out of block and place it above the tag . Since in the next step we will remove the block then you need to save
- Delete block
, since when working with Quarkus this application will no longer need the parent pom from JBoss.
- Add tag
and place it under the tag . The version number can be specified as you want.
- Delete tag
, since this application is no longer a WAR, but a regular JAR.
- We modify the following dependencies:
- Change javax.enterprise: cdi-api dependency to io.quarkus: quarkus-arc, removing
providedbecause (according to the docks) this Quarkus extension provides injection dependencies of CDI.
- Change the org.jboss.spec.javax.servlet: jboss-servlet-api_4.0_spec dependency to io.quarkus: quarkus-undertow, removing
providedbecause (according to the docks) this Quarkus extension provides support for servlets.
- We remove the org.jboss.spec.javax.annotation: jboss-annotations-api_1.3_spec dependency, since they come bundled with the dependencies we just changed.
The version of the pom.xml file with all changes is located at github.com/mrizzi/jboss-eap-quickstarts/blob/quarkus/helloworld/pom.xml.
Please note that the above mvn io.quarkus: quarkus-maven-plugin: 0.23.2: create command not only changes the pom.xml file, but also adds a number of components to the project, namely the following files and folders:
- The mvnw and mvnw.cmd file and the .mvn: Maven Wrapper folder allow you to run Maven projects of a given version of Maven without installing this version itself.
- Docker folder (in the src / main / directory): here are examples of Dockerfiles for native and jvm modes (along with the .dockerignore file).
- Resources folder (in the src / main / directory): here lies an empty application.properties file and a sample Quarkus index.html start page (for details, see Run the modernized helloworld).
Launch helloworld
To test the application, we use quarkus: dev, which launches Quarkus in development mode (for more details see this section in the manual Development mode)
Note: this step is expected to lead to an error, because we have not yet made all the necessary changes.
Now run the command to check:249)
So, it doesn’t work … And why?
The UnsatisfiedResolutionException exception points cannot be found (although both of these classes are in the same package).
It’s time to get back to documentation and read how Inject works in Quarkus, and therefore Contexts and Dependency Injection (CDI). Therefore, we open the Contexts and Dependency Injection guide in the section Bean discovery we read: “A bean class that does not have a defining bean annotation is not searched.”
We look at the HelloService class – it really does not have such an annotation. Therefore, it must be added so that Quarkus can search and find a bean. And since this is a stateless object, we can well add the @ApplicationScoped annotation as follows:
@ApplicationScoped public class HelloService {
Note: here the development environment may ask you to add the required package (see the line below), and this will have to be done manually, like this:
import javax.enterprise.context.ApplicationScoped;
If in doubt, which scope should be used when the source bean’s is not set at all, study the documentation JSR 365: Contexts and Dependency Injection for Java 2.0 — Default scope.
Now again, we try to run the application with the command ./mvnw compile quarkus: dev:
$ .]]
Now everything goes without errors.
We launch the upgraded helloworld
As written in the log, open in the browser 0.0.0.0: 8080 (Quarkus start page by default) and see this:
Fig. 4. Start page of Quarkus dev.
The WebServlet annotation for this application has the following context definition:
@WebServlet("/HelloWorld") public class HelloWorldServlet extends HttpServlet {
Therefore, go to the browser on 0.0.0.0: 8080 / HelloWorldto and see the following:
Fig. 5: The Quarkus dev page for the Hello World application.
Well, everything works.
And now we are making changes to the code. Note that the ./mvnw compile quarkus: dev command is still working and we are not going to stop it. Now let’s try to apply the same – trivial – changes to the code itself and see how Quarkus makes life easier for the developer:
writer.println("
" + helloService.createHelloMessage("Marco") + "");
Save the file and then refresh the web page to see Hello Marco, as shown in the screenshot below:
Fig. 6. Hello Marco page in Quarkus dev.
Now check the output in the terminal:
The page refresh triggered the detection of changes in the source code, and Quarkus automatically performed the stop-start procedure. And all this was completed in just 0.371 seconds (here it is, that very “ultrafast subatomic Java”).
Build helloworld into a JAR package
Now that the code works as it should, we pack it with the following command:
$ ./mvnw clean package
This command creates two JAR files in the / target folder: the helloworld-.jar file, which is a standard artifact assembled by the Maven team together with the project classes and resources. And the helloworld file is runner.jar, which is an executable JAR.
Please note that this is not an uber-jar, since all dependencies are simply copied to the / target / lib folder (and not packaged into a JAR file). Therefore, to run this JAR from another folder or on a different host, you need to copy both the JAR file and the / lib folder there, given that the Class-Path element in the MANIFEST.MF file in the JAR package contains an explicit listing of the JARs from lib folders.
To learn how to create uber-jar applications, refer to the manual Uber-jar creation.
Launch helloworld packed in JAR
Now you can run our JAR using the standard java command:
$ java -jar ./target/helloworld-
-runner.jar INFO [io.quarkus] (main) Quarkus 0.23.2 started in 0.673s. Listening on: INFO [io.quarkus] (main) Profile prod activated. INFO [io.quarkus] (main) Installed features: [cdi]
After all this is done, go to the browser on 0.0.0.0: 8080 and check that everything is working as it should.
Putting helloworld into a native executable
So, our helloworld works as a standalone Java application using Quarkus dependencies. But you can go further and turn it into a native executable file.
Install GraalVM
First of all, for this you need to install the necessary tools:
1. Download GraalVM 19.2.0.1 from github.com/oracle/graal/releases/tag/vm-19.2.0.1.
2. Expand the downloaded archive:
$ tar xvzf graalvm-ce-linux-amd64-19.2.0.1.tar.gz
3. Go to the untar folder.
4. Run the command below to download and add a native image:
$ ./bin/gu install native-image
5. We register the folder created in step 2 into the environment variable GRAALVM_HOME:
$ export GRAALVM_HOME={untar-folder}/graalvm-ce-19.2.0.1)
For more information and installation instructions on other OSs, see the manual. Building a Native Executable — Prerequisites.
Build helloworld into a native executable
Read the manual Building a Native Executable — Producing a native executable: “And now we will create a native executable file for our application to reduce its launch time and disk size. The executable file will have everything necessary to run the application, including the JVM machine (or rather, its truncated version, containing only what is required to run the application) and our application itself. ”
To create a native executable, you must enable the Maven native profile:
$ ./mvnw package -Pnative
Our assembly took one minute and 10 seconds, and the final helloworld file – runner f was created in the / target folder.
Run the native executable file helloworld
In the previous step, we got the executable / target / helloworld – runner. Now run it:
$ ./target/helloworld-
-runner INFO [io.quarkus] (main) Quarkus 0.23.2 started in 0.006s. Listening on: INFO [io.quarkus] (main) Profile prod activated. INFO [io.quarkus] (main) Installed features: [cdi]
Open again in the browser 0.0.0.0: 8080 and check that everything works as it should.
To be continued!
We believe that the method of modernizing Java applications using the capabilities of Quarkus considered in this post (albeit with the simplest example) should be actively applied in real life. In this case, you are likely to encounter a number of problems, the solution of which we will partially consider in the next post, which will focus on how to measure memory consumption in order to evaluate performance improvements, an important part of the whole process of application modernization.
|
https://prog.world/quarkus-application-upgrades-with-helloworld-from-jboss-eap-quickstart/
|
CC-MAIN-2022-21
|
refinedweb
| 2,119
| 57.67
|
Using ColdFusion Builder's debugger for Flex and Ajax
This is probably one more blog entry of mine that falls into the “obvious” category, but until I tried it today I didn’t know it was possible so hopefully I’m not the only one. I don’t normally use the debugger in ColdFusion Builder. There isn’t anything wrong with it - it just doesn’t really mesh with the way I like to write code. On the flip side, I make a heck of a lot of use out of the debugger in Flash Builder. Why do I use it more there and less in ColdFusion? No idea. That being said, a reader this week asked me an interesting question. He is using Flash Builder and wanted to know about debugging on the server side. I knew you could debug the Flex side of course. You can also easily debug the network communications. What I wasn’t sure of was how I’d handle debugging on the ColdFusion Builder side when I’m actually using Flash Builder. The debuggers in both products aren’t related. (Well, I assume they share some code at the Eclipse level.) Here is what I found out.
I began by creating a super simple CFC to act as my service. I put some bogus code in there just to give me a few lines of logic.
component {
remote function double(numeric x) {
var thisisdumb = now();
var thisismoredumb = randRange(1,1000);
var result = arguments.x*2;
return result;
}
}
Over in Flash Builder I then created an extremely simple front end.
<
<mx:method
</mx:RemoteObject>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
public function handleFault(evt:FaultEvent):void {
mx.controls.Alert.show(evt.toString())
}
public function handleResult(evt:ResultEvent):void {
resultValue.text = evt.result.toString()
}
public function tryIt():void {
doubleService.double(initialValue.text);
}
]]>
</fx:Script>
<s:HGroup>
<s:TextInput
<s:Button
<s:TextInput
</s:HGroup>
</s:Application>
All this code does is take input from the first field and send it to my CFC. When the result is returned I place it in the second field. I hit run in Flash Builder and confirmed everything worked. I then went to ColdFusion Builder (I don't run my installs in the same Eclipse package) and switched to the ColdFusion Debugging perspective. I put a breakpoint on one of the lines and then I clicked the little green bug to start up the debugging session. This launched double.cfc in the browser which gave me the normal CFC view.
Now at this point I then switched back to my browser tab containing my Flex app. I entered another number, hit the button, and voila - all of a sudden CFBuilder is blinking in my task bar. I could see nothing being displayed in the Flex app and when I alt-tabed over to CFBuilder I was in the middle of a debugging session.
When I let the method carry on, my data was returned to Flex. I tried the same thing in a simple Ajax based application and it also worked.
Even better - I then switched over to Aptana and converted my jQuery example into a simple AIR application. I ran it and once again - the result was 'hung' up while I debugged in ColdFusion Builder.
Cool! So - as I said, I guess this is 100% expected, but it never occurred to me to try using CFBuilder's debugger like this. I can actually see myself using it more now.
|
https://www.raymondcamden.com/2010/11/04/Using-ColdFusion-Builders-debugger-for-Flex-and-Ajax/
|
CC-MAIN-2018-51
|
refinedweb
| 593
| 66.33
|
I have been trying to create a program which the teacher log in to view the scores of a test of a school class. The scores are stored in a text file like this:
Charlotte:7 Charlotte:4 Charlotte:3 Chelsea:2 Chelsea:9 Chelsea:5 Jeff:1 Jeff:10
As you can see there are multiple scores for each student, I need to be able to sort these scores by highest score out of the class with each student's highest score. I've worked out how to sort it by each student's highest score with the following code but I now need to sort those highest scores of the students into the highest to lowest scored in the class.
import operator import collections d = collections.defaultdict(lambda: collections.deque(maxlen=3)) with open("class {0}.txt".format(Class)) as f: #these lines adds the text file into the dictionary for line in f: name,score = line.strip().split(":") d[name].append(score) #The next lines gets each students highest score for k in d: high = max(d[k]) k + " " + " ".join(map(str, high))
The error is in the following lines, where i've tried to sort the list of 'high scores' into highest to lowest
print(sorted(high, reverse=True))
It currently prints out this:
['7']
I have worked out how to sort it by each student's highest score but I am stuck on how to sort each highest score into highest to lowest.
Could someone give me some pointers or help on how I could sort the list and print it out like this..
Jeff 10 Chelsea 9 Charlotte 7
Thanks!
Edited by psvmr
|
https://www.daniweb.com/programming/software-development/threads/492556/trouble-sorting-dictionary-into-highest-to-lowest
|
CC-MAIN-2018-17
|
refinedweb
| 279
| 74.32
|
We are looking for a place to stay for two nights in Soweto in the 1st week of July. Three adults and a 14 year old. Best option I've found so far seem to be the Soweto Hotel. Looks fine. Anyone able to suggest additional options?
Here are a few options you could look at:
Don't let the word "backpackers" put you off!
safarinow.com/go/MamaLolosGuestHouseSoweto
exploresoweto.com/the-rose-bed-and-breakfast/
Enjoy!
I second Lebo's Soweto Backpackers
If you are adventurous and want a genuine Soweto experience, there's a brand new (as of September 2013) backpackers hotel in Kliptown. There are private rooms and small shared dormitories. Prices start at 85Rand. I spent time in Kliptown recently working on an art/photography project and was shown around this place by the friendly owner.. It was clean, spacious and newly renovated. The address is 1848 Fourth Street, Contact: Nomsa tel: 0784318306 or 0789993458 This is not for everyone, only those who want to see and experience the real Soweto: Kliptown Backpackers If I return (I live in New York City) I would stay here.
|
https://www.tripadvisor.com/ShowTopic-g312587-i13197-k6586060-Lodging_Place_to_stay_in_Soweto-Soweto_Greater_Johannesburg_Gauteng.html
|
CC-MAIN-2016-40
|
refinedweb
| 190
| 63.7
|
DOM::CSSRule
#include <css_rule.h>
Detailed Description
The
CSSRule interface is the abstract base interface for any type of CSS statement .
This includes both rule sets and at-rules . An implementation is expected to preserve all rules specified in a CSS style sheet, even if it is not recognized. Unrecognized rules are represented using the
CSSUnknownRule interface.
Definition at line 53 of file css_rule.h.
Member Enumeration Documentation
An integer indicating which type of rule this is.
Definition at line 68 of file css_rule.h.
Member Function Documentation
The parsable textual representation of the rule.
This reflects the current state of the rule and not its initial value.
Definition at line 77 of file css_rule.cpp.
Definition at line 109 of file css_rule.cpp.
If this rule is contained inside another rule (e.g.
a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns
null .
Definition at line 101 of file css_rule.cpp.
The style sheet that contains this rule.
Definition at line 93 of file css_rule.cpp.
see cssText
- Exceptions
-
HIERARCHY_REQUEST_ERR: Raised if the rule cannot be inserted at this point in the style sheet.
NO_MODIFICATION_ALLOWED_ERR: Raised if this style sheet is readonly.
- Exceptions
-
INVALID_MODIFICATION_ERR: Raised if the specified CSS string value represents a different type of rule than the current one.
Definition at line 85 of file css_rule.cpp.
The type of the rule, as defined above.
The expectation is that binding-specific casting methods can be used to cast down from an instance of the
CSSRule interface to the specific derived interface implied by the
type .
Definition at line 69 of file css_rule.cpp.
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2020 The KDE developers.
Generated on Wed Jul 1 2020 22:44:41 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online.
|
https://api.kde.org/frameworks/khtml/html/classDOM_1_1CSSRule.html
|
CC-MAIN-2020-29
|
refinedweb
| 327
| 60.31
|
How to avoid Thread.Sleep in your production code in .NET
Avoiding Thread.Sleep in production code in .NET using C#
I am pretty sure any of us used Thread.Sleep method to pause the current thread execution. Mostly this is used to simulate long running process during the test or debug.
While this is fine to use for testing, if your intention is to actually schedule thread execution this is probably wrong way of doing it, simply because Thread.Sleep does not actually take as many milliseconds as you pass to the method as a parameter. Instead it only guarantees that it will halt the thread for at least that many seconds because it is based on timeslices number which defers for different Windows versions. More about this you can read in article Thread.Sleep is a sign of a poorly designed program.
So OK, Thread.Sleep is a big NO NO, but what can we use instead?
There are few suggestions what can you use to schedule a Thread execution. On the highest level you can use Quartz.NET library, but if you do not require any big logic for scheduling the execution this is a bit an overhead.
One of the things that can be use is System.Threading.AutoResetEvent in combination with System.Timers.Timer class. Tho following is an example of using Timer and AutoResetEvent in an infinite loop, a most common place where Thread.Sleep is used by mistake.
using System; using System.Threading; using System.Timers; namespace NoThreadSleep { class Program { static System.Timers.Timer timer = new System.Timers.Timer(1000) { AutoReset=true}; static AutoResetEvent autoResetEvent = new AutoResetEvent(false); static void Main(string[] args) { timer.Elapsed += Timer_Elapsed; timer.Start(); ThreadPool.QueueUserWorkItem((state) => { while (true) { Console.WriteLine(DateTime.Now); autoResetEvent.WaitOne(); } }); Console.ReadLine(); } private static void Timer_Elapsed(object sender, ElapsedEventArgs e) { autoResetEvent.Set(); } } }
Instead of relying to Thread.Sleep slicing we will actually have out Timer setting the event and schedule the Thread execution. Since it is AutoResetEvent instead ManualResetEvent, once the thread executes, we'll have our event reset automatically.
When you run the code above you will get properly printed out time string with interval of 1 second which is the timer interval set
2018-03-26 16:24:37
2018-03-26 16:24:38
2018-03-26 16:24:39
2018-03-26 16:24:40
2018-03-26 16:24:41
2018-03-26 16:24:42
2018-03-26 16:24:43
2018-03-26 16:24:44
2018-03-26 16:24:45
2018-03-26 16:24:46
2018-03-26 16:24:47
2018-03-26 16:24:48
This is only one of the ways to avoid Thread.Sleep. It is one of the most simpler way of scheduling the Thread execution.
References
-
-
-
-
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
|
https://dejanstojanovic.net/aspnet/2018/march/how-to-avoid-threadsleep-in-your-production-code-in-net/
|
CC-MAIN-2021-04
|
refinedweb
| 507
| 67.96
|
The beta V8 Version 7.4 is now available, with the potential to expand the engine’s footprint to platforms such as Apple iOS. V8 is Google’s open source JavaScript and WebAssembly engine for the Chrome browser. It is a staple in both the Chrome browser and the Node.js JavaScript runtime.
Where to download Google V8
You can the download the production version of Google V8 from the Chromium V8 repo.
Future version: What’s new in V8 Version 7.4
With the production version due in April 2019, Google V8 beta 7.4 has the following new features:
- JIT-less V8, in which JavaScript execution is supported without allocating executable memory at runtime. This could allow expansion of V8 onto platforms such as Apple iOS, smart TVs, and game consoles. The default configuration of V8 has relied on the ability to allocate and modify executable memory at runtime. But there are situations where it can be desirable to run the engine without allocating executable memory, such as platforms that have prohibited write access to nonexecutable memory for nonprivileged applications, including iOS. Also, disallowing writes to executable memory reduces the attack surface of the application for exploits. With the JIT-less mode, V8 switches to an interpreter-only mode for JavaScript; WebAssembly currently does not support this mode. JIT-less mode does come with a performance penalty, however.
- WebAssembly Threads/Atomics are now enabled on non-Android OSes. This move unlocks the use of multiple cores via WebAssembly, enabling new, computation-heavy uses on the web.
- To improve performance, Version 7.4 skips arguments adaption in some cases, reducing call overhead by 60 percent.
- Performance has been improved for calling into native accessors, which are DOM accessors.
- Preparser performance was improved by removing a deduplication involving property names. Additionally, a performance issue was fixed that involved custom UTF-8 decoding used by the source stream.
- To reduce memory overhead, support has been implemented for flushing compiled bytecode from functions during garbage collection if they have not been executed recently.
- To support private class fields, Developers can mark a field as private by prepending it with the
#prefix.
Where to download the V8 7.4 beta
You can download the V8 beta from Google’s Chromium Git repo.
Current version: What’s new in V8 Version 7.3
New features in V8 7.3 include:
- The
--async-stack-tracesflag is turned on by default.
- Zero-cost async stack traces make it easier to diagnose problems in production with asynchronous code; the
stackproperty usually sent to log files and services now provides more insight into problems.
- A faster
await, with the
--harmony-await-optimizationflag turned on by default. This is a prerequisite for
--async-stack-traces.
- Quicker startup for WebAssembly via optimizations. For most workloads, compilation is improved by 15 percent to 25 percent.
- JavaScript features such as
fromEntries(), an API to perform the inverse of
Object.entries, and
String.prototype.Matchall, an API to make it easier toapply global or sticky regular expressions to a string and iterating through all matches.
Current version: What’s new in Google V8 Version 7.2
January 2019’s Version 7.2 of V8 improves JavaScript parsing, the WebAssembly binary format, and memory.
To improve parsing speed, V8 Version 7.2 includes what Google calls the engine’s fastest-ever JavaScript parser, resulting in quicker page loading and more-responsive pages. Since V8 Version 7.0, desktop parsing speed has improved about 30 percent, Google says.
For memory, embedded built-ins that save memory by sharing generated code across multiple isolates are now supported and enabled by default on the IA32 architecture.
For WebAssembly, V8 7.2 has code-generation improvements, including the enablement of node splitting in the optimizing compiler’s scheduler and loop rotation in the back end. Also, wrapper caching has been improved and custom wrappers introduced to reduce overhead when calling imported JavaScript math functions.
Design changes to the register allocator improve performance for code patterns that will appear in a later release. Also, trap handlers in Version 7.2 improve throughput of WebAssembly code. They are implemented on Windows, MacOS, and Linux. In Chromium, they are enabled on Linux, with MacOs and Windows to follow when stability is confirmed. Plans also call for them to be available on Android.
Other new features in V8 7.2 include:
- Spread elements performance has been improved when these occur at the front of the array literal.
- A faster
async/
awaitimplementation is enabled by default. The change may be merged into the official ECMAScript specification.
- Zero-coast async stack traces enrich the
stackproperty with asynchronous call frames. This capability is available behind the
--async-stack-tracescommand-line flag.
- Support for public class fields, which expands the JavaScript syntax for simplification.
- The
ListFormatproposal, for localizing formatting of lists.
stringifynow outputs escape sequences for lone surrogates, making the output valid Unicode.
Previous version: What’s new in Google V8 Version 7.1
November 2018’s Version 7.1 of V8 features improvements in memory and performance along with enhancements for both JavaScript and the WebAssembly binary format. For memory, bytecodes for the interpreter now are embedded into the binary, saving about 200KB on average per isolate. To improve performance, the escape analysis in the TurboFan compiler is enhanced to handle local function contexts for higher order functions, when variables from the surrounding context escape to a local closure. With escape analysis, scalar replacement is performed for objects local to an optimization unit.
Other new features in V8 Version 7.1:
- For JavaScript, the
RelativeTimeformatAPI featured in the upgrade allows localized formatting of relative times, such as “yesterday,” without sacrificing performance. Also, version 7.1 supports the
GlobalThisproposal, providing a universal mechanism to access the global object even in strict functions or modules, regardless of the platform.
- For WebAssembly bytecode format,
postMessageis supported for modules. This behavior is scoped to web workers and is not extended to cross-process scenarios.
Previous version: What’s new in Google V8 Version 7.0
October 2018’s V8 Version 7.0 previews WebAssembly threads, which provide a primitive for parallel computation. To use threads in the Chrome browser, which uses V8, developers can enable it via
chrome://flags/#enable-webassembly-threads or sign up for an Origin Trial, for experimenting with new web features. WebAssembly, aka Wasm, enables compilation of code written in different languages to run on the web.
Other new features in V8 7.0 include:
- For JavaScript, the
descriptionproperty is added to
prototype, providing a more-ergonomic way to access the description. Also,
Array.prototype.sortbecomes stable in Version 7.0.
- Extension of embedded built-ins, which save memory by sharing generated code across multiple isolates. V8 Version 6.9 enabled built-ins on the X64 architecture while Version 7.0 extends them to the remaining platforms except IA-32.
Previous version: What’s new in Google V8 Version 6.9
September 2018’s V8 Version 6.9 focuses on memory and performance improvements for.
For performance, V8 Version 6.9 reduces Mark-Compact garbage collection pause times by improving
WeakMap processing. Concurrent and incremental marking now can process
WeakMaps. Previously, this work was done in the final atomic pause of Mark-Compact garbage collection. The garbage collection now also does more work in parallel to lower pause times.
For performance,
DataView methods have been reimplemented in V8 Torque, sparing a costly call to C++ compared to the previous runtime implementation. Also, calls to
DataView methods now are inlined when compiling JavaScript into the TurboFan optimizing compiler. This provides better peak performance for hot code.
V8 Version 6.9 also includes Liftoff, a baseline compiler for the WebAssembly portable code format. It is enabled by default and intended to reduce startup times for WebAssembly-based apps by generating code as quickly as possible. Code itself quality is a secondary priority for Liftoff, with code eventually to be recompiled by V8’s TurboFan compiler.
Liftoff was developed to address an issue in which the back end of the compilation process for TurboFan consumed a lot of time and memory, reducing performance of the WebAssembly code. Liftoff avoids the time and memory overhead of intermediate representation, generating machine code in a single pass over the bytecode of a WebAssembly function. Liftoff and Turbofan give V8 two compilation tiers, with Liftoff a baseline compiler for fast startup and TurboFan providing optimization for performance.
Google also plans to further improve startup time, cut memory consumption, and bring benefits of Liftoff to more users. These plans involve ports to ARM processors, for use on mobile devices. Liftoff currently works only on Intel 32- and 64-bit platforms. Other improvements under consideration include:
- Implementing dynamic tier-up for mobile devices, to accommodate lower memory volumes on these devices. Experiments are proceeding with a combination of lazy compilation with Liftoff and dynamic tier-up of hot functions in TurboFan.
- Improving Liftoff code generation performance and improving the generated code as well.
Previous version: What’s new in V8 Version 6.8
Google V8 Version 6.8, released in July 2018, focuses on performance and memory usage.
Performance has been boosted by array destructuring improvements. The optimizing compiler had not been generating ideal code for array destructuring, so the builders of V8 blocked escape analysis to eliminate temporary allocation, which made array destructuring with a temporary array as fast as a sequence of assignments.
A new implementation of Object.assign improves performance, via implementation of a fast path for JavaScript.
Performance for TypedArrays has been increased in instances when sorting is done using a comparison function.
Other new features in V8 Version 6.8 include:
- To improve execution speed with the WebAssembly portable code format, developers can use trap-based bounds checking, a memory-management optimization, on Linux x64 platforms.
- Memory consumption of SFIs (
SharedFunctionInfo) has been reduced, via compression and removal of unnecessary fields.
- Also to improve memory capabilities, a dependency on SFIs has been broken in which SFIs were unnecessarily kept alive, which had led to the risk of memory leaks.
Previous version: What’s new in V8 Version 6.7
Google’s V8 JavaScriptengine is getting enhancements for language features and security with the Version 6.7 branch, which is now in production.
Also featured in V8 6.7 are more mitigations for side-channel vulnerabilities, intended to prevent information leaks to untrusted code for JavaScript and WebAssembly.
Previous version: What’s new in V8 Version 6.6
Version 6.6 of Google’s V8 JavaScript engine focuses on JavaScript language features and code-caching capabilities.
For JavaScript,
Function.prototype.toString() returns exact slices of source code text, including whitespace and comments. V8 Version 6.6 also implements
String.prototype.trimStart() and String.prototype.trimEnd(). This capability had been available through nonstandard
trimLeft() and
trimRight() methods, which remain as aliases of the new methods to enable backward compatibility.
Additionally, line and paragraph separator symbols can be used in string literals, thus matching JSON. Previously, these had been treated as line terminators in string literals and their usage resulted in a SyntaxError exception.
The
Array.prototype.values method gives arrays the same iteration interface as the ECMAScript 2015
Map and
Set collections. These can be interacted over by
keys,
values, or
entries by calling the same-named method. This change could be incompatible with existing JavaScript code; developers who find odd or broken behavior on a website can try to disable this feature via
chrome://flags/#enable-array-prototype-values.
|
https://www.infoworld.com/article/3252818/whats-new-in-googles-v8-javascript-engine.html
|
CC-MAIN-2021-25
|
refinedweb
| 1,919
| 50.12
|
3kronlein left a reply on Broadcasting Events Not Changing
Just for anyone else that comes across this ...
queue:restart
solves it.
vkronlein started a new conversation Broadcasting Events Not Changing
I'm writing some broadcast events and when I change the code in the event and then fire it again, it still broadcasts the old event data.
Is there some trick to ensure the new code is picked up?
So far the only way I've been able to reset this is to completely halt homestead and restart it.
Thanks.
vkronlein left a reply on Laravel-Echo-Server Installation On Forge With SSL Enabled With The Redis Broadcast Driver And Socket.io
I wasn't able to get the daemon to work. I have laravel-echo-server installed globally via nvm.
I used the command:
/home/forge/.nvm/versions/node/v8.15.0/bin/laravel-echo-server start
but I'm getting an error exited too quickly.
Any ideas on how to get this rolling?
vkronlein left a reply on Component Not Accessing Vuex State
@REALRANDYALLEN - Since my
fetch method returns a promise I just swapped out some variable names and added a method to set a data property like so:
<script> import { mapGetters, mapActions } from 'vuex' export default { created() { this.fetch().then((response) => { this.setCurrent() }) }, data() { return { current: '' } }, computed: { ...mapGetters({ statuses: 'statuses', latest: 'getLatest', }), }, methods: { ...mapActions({ fetch: 'fetchBuilderStatuses', }), close() { $('#status-modal').modal('hide') }, setCurrent() { this.current = this.latest.class } } } </script>
No more errors, it is laggy when you load the page though which kinda sucks, but it works for now. My production server is really fast so I think it'll be fine.
Thanks so much for your help Randy, I appreciate it.
V
vkronlein left a reply on Component Not Accessing Vuex State
@REALRANDYALLEN - No love. I still get the same error.
Here is all the JS from my component, it's pretty basic, and I've never run across this error before.
<script> import { mapGetters, mapActions } from 'vuex' export default { created() { this.fetch() }, mounted() { console.log(this.current) }, computed: { ...mapGetters({ statuses: 'statuses', current: 'getLatest', }), }, methods: { ...mapActions({ fetch: 'fetchBuilderStatuses', }), close() { $('#status-modal').modal('hide') } } } </script>
Let me know if you want to see all the vuex pieces as well.
Thanks for the help!
vkronlein left a reply on Component Not Accessing Vuex State
@REALRANDYALLEN - let me try that and report back the results.
vkronlein left a reply on Component Not Accessing Vuex State
@REALRANDYALLEN - Makes sense to consider, but even the below returns null.
mounted() { console.log(this.current) }
Furthermore I'm using
current as a model on a
div:
<div class="status" :</div>
Which is what's producing the error in the initial post.
vkronlein started a new conversation Component Not Accessing Vuex State
I have a component that has 2 vuex getters:
statuses and
getLatest which return
statuses and
latest from state.
statuses being an array and
latest is a null object.
I have an action
fetchBuilderStatuses that fetches status messages from a remote Lumen install as a json array which contains
latest which is the first message, and
statuses which is a collection of all the messages. All pretty basic, the Lumen install has CORS installed and does correctly return all the data.
I'm importing
mapActions and
mapGetters from vuex of course.
My computed object on the component looks like so:
computed: { ...mapGetters({ statuses: 'statuses', current: 'getLatest', }), },
When using the chrome vue dev tool I can see that
latest is being set in state correctly, it is an object that contains all my data as expected, as well as
statuses which is set properly as well.
But in my component I'm getting the following error:
[Vue warn]: Error in render: "TypeError: Cannot read property 'class' of null"
If I console log
this.current it is null.
This makes absolutely no sense to me. I use this same exact technique all over my app and never does this happen, my vuex state is always pulled in exactly as it should be.
Any ideas on why this might be happening?
If any additional code is needed just let me know.
vkronlein started a new conversation Homestead Box Won't Update
When running
homestead up I get the 6.4.0 available message, so then I run
homestead box update which downloads the 6.4.0 box, but then it doesn't upgrade. I run
halt then
up again and get:
==> homestead-7: A newer version of the box 'laravel/homestead' for provider 'virtualbox' is ==> homestead-7: available! You currently have version '6.3.0'. The latest is version ==> homestead-7: '6.4.0'. Run `vagrant box update` to update.
Running
homestead box list :
laravel/homestead (virtualbox, 6.3.0) laravel/homestead (virtualbox, 6.4.0)
How can I get this to update to 6.4?
vkronlein started a new conversation Accessing The User Session In A Job
Hey All.
I have a system of external applications (API's) that my users can access through a token/authorization system I built into the app.
Now they need to go the actual list of apps and connect manually. I've set up a login column in my table so that they can choose to connect on login per application, for the ones they use the most.
Currently when they connect, there is a handshake process that eventually returns a token from the external service that gets stored in their session.
When building the autoconnect on login Job, I've discovered that the session isn't able to be accessed as you normally would since the job runs independently.
I do have my user stored on the job class, how can I access that user's session from within a job.
I can add code if needed, but I think this is a pretty straight forward question.
vkronlein left a reply on Return Response For ManytoMany Attach
Yes that's the one I found when testing.
I decided to do a negative check since it's void if successful, this seems to work fine.
$insert = $user->applications()->attach($model, $pivotData); if (! $insert) { // do stuff }
Thanks for the help.
vkronlein left a reply on Return Response For ManytoMany Attach
Some sort of Builder query exception I assume, since there's no specific exception listed in the method?
vkronlein started a new conversation Return Response For ManytoMany Attach
Digging into the
InteractsWithPivotTable trait I can see that
attach returns void, but I need to figure out a way to determine if my
attach call was successful so that I can return a response message to Vue.
Anyone have a solution or any ideas for this?
vkronlein left a reply on API Calls From Datatables Not Authorized
Yeah I'm at that point, I guess I'll just move them into the web routes, but I'd still like to know why this doesn't work as expected.
Using Laravel 5.5.44 and Passport 4.0.3
vkronlein left a reply on API Calls From Datatables Not Authorized
No this app isn't in a place yet to be able to be upgraded to 5.7. I took it over about a year ago and have been trying to slowly replace all the terrible spaghetti left by the previous dev.
It's in production, making that much more difficult as the owner is constantly adding new features so as to make getting it cleaned up and refactored that much more time consuming.
And no, I'm not modifying the request anywhere.
vkronlein left a reply on API Calls From Datatables Not Authorized
This doesn't make sense. By definition, the
CreateFreshApiToken middleware adds a
laravel_token cookie to each response that contains the authenticated user's information.
When I look at the my list of cookies in Chrome I can see that the cookie exists, with my api guard set to passport, Passport should resolve this cookie to push the user model on to the request object.
Clearly this isn't happening as my request object is completely empty.
vkronlein left a reply on API Calls From Datatables Not Authorized
I need to re-answer part of your initial question.
Other api calls do work when outside the
auth:api middleware, but the call to
user returns an empty response.
Route::get('/user', function (Request $request) { return $request->user(); });
returns nothing.
Event if I just return the
$request I get nothing but an empty array.
Route::get('/user', function (Request $request) { return $request; });
Response =
[]
Something is amiss here.
vkronlein left a reply on API Calls From Datatables Not Authorized
Yes
CreateFreshApiToken is listed last in the stack.
protected $middlewareGroups = [ 'web' => [ \App\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ];
vkronlein left a reply on API Calls From Datatables Not Authorized
Thanks anyway, hopefully Bobby will chime in here, he usually finds these things straight away.
I was trying to figure out how I can intercept this before it throws the 401 to see what's happening in Passport or wherever it's failing ... but I haven't had any luck doing that yet either.
vkronlein left a reply on API Calls From Datatables Not Authorized
Config uses Passport.
Bearer token shouldn't be needed, I'm consuming my own API as per the documentation:
Yes everything works fine outside of the call to
auth:api
First time I've tried to use the middleware.
Thanks for your help.
vkronlein left a reply on API Calls From Datatables Not Authorized
Any chance I can get you to weigh in on this?
Why can't I access my own API when it's behind the
auth:api middleware? What do I need to do to fix this?
Thanks.
vkronlein left a reply on Events/Jobs Inside Event Listener Never Fire
That defeats the whole purpose of queueing the job.
vkronlein left a reply on Events/Jobs Inside Event Listener Never Fire
It seems that
queue:work doesn't listen for events, only for jobs. A listener is basically just a job, so when the initial event fires, it creates a listener job which gets picked up by the work command.
But if you fire a new event during the handle process, this event is not being listened for.
But, once I switched both to jobs, they both fire as expected.
If however you run
queue:listen this process does find new events within event handlers. Weird, but I need a queued job so skipping the events is fine.
vkronlein started a new conversation Events/Jobs Inside Event Listener Never Fire
Is there some reason why an event or job would not fire from inside the handle method of an event listener?
public function handle(SaveRecordPdf $event) { $record = $event->record; if ($this->service->publish($record)) { Log::info($record->published_filename . ' was stored successfully.'); // fire publish job PublishFile::dispatch($record); // never fires event(new SomeEvent($record)); // also never fires } }
I know I've done this in earlier versions, this app is v5.5.44
Thanks.
vkronlein left a reply on API Calls From Datatables Not Authorized
It's not a datatables issue, I can't hit anything inside the
auth:api middleware, even the default
axios.get('/api/user') .then(response => { console.log(response.data); });
fails using both axios and jquery. Always returns 401 Unathorized with the Unauthenticated message.
And before you ask, I do have
passport set as my auth driver for the api routes.
Yes, when I remove the routes from behind the middleware it works perfectly.
Here's the code that's inside the view, not sure how this would help but as requested:
@push('scripts') <script> $(document).ready(function() { $('#datatable-users').DataTable({ 'processing': true, 'serverSide': true, 'ajax': '/api/datatables/users', 'pageLength': 25 }); }); </script> @endpush
vkronlein started a new conversation API Calls From Datatables Not Authorized
Hello all.
I have some datatables being called via api in some views. There exist from the previous developer.
I just realized that they were outside of any authentication and available to the public, so I moved it inside of the
auth:api middleware and not I get a 401.
Route::group(['middleware' => 'auth:api'], function() { //dd(request()->cookie('laravel_token')); // always produces a valid token Route::get( '/datatables/users', 'Builder\[email protected]' ); });
I included the
CreateFreshApiToken middleware from Passport and with the commented out
dd call I can see that a valid token is being sent on each request.
Why would I be getting a 401?
vkronlein left a reply on Relationships Always Null
I figured, but those aren't the id's from the table.
Changed the
incrementing but no love, also needed to add
keyType = 'string' and then this did the trick.
Thanks everyone for all your help, much appreciated.
vkronlein left a reply on Relationships Always Null
They are the standard Passport migrations, let me grab them from github.
public function up() { Schema::create('oauth_access_tokens', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->integer('user_id')->index()->nullable(); $table->integer('client_id'); $table->string('name')->nullable(); $table->text('scopes')->nullable(); $table->boolean('revoked'); $table->timestamps(); $table->dateTime('expires_at')->nullable(); }); } public function up() { Schema::create('oauth_refresh_tokens', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->string('access_token_id', 100)->index(); $table->boolean('revoked'); $table->dateTime('expires_at')->nullable(); }); }
vkronlein left a reply on Relationships Always Null
array:2 [▼ 0 => array:3 [▼ "query" => "select * from `oauth_access_tokens`" "bindings" => [] "time" => 0.38 ] 1 => array:3 [▼ "query" => "select * from `oauth_refresh_tokens` where `oauth_refresh_tokens`.`access_token_id` in (?, ?, ?, ?, ?, ?, ?, ?)" "bindings" => array:8 [▼ 0 => 0 1 => 3 2 => 13 3 => 44 4 => 85 5 => 2855414 6 => 5850233 7 => 8646257075 ] "time" => 0.63 ] ]
Can you explain what the bindings are here?
vkronlein started a new conversation Relationships Always Null
I'm sure I must be missing something simple.
I've created local models for the OAuth tables created by Passport.
I'm trying to create a one to one relationship between
oauth_access_tokens and
oauth_refresh_tokens
As per the docs:
Eloquent determines the foreign key of the relationship based on the model name.
The refresh table column is
access_token_id to reference the parent table id.
namespace App; use Illuminate\Database\Eloquent\Model; class AccessToken extends Model { protected $table = 'oauth_access_tokens'; public function refresh() { return $this->hasOne(RefreshToken::class); } }
As per the docs:.
Thusly if my column name is
access_token_id and my method name is
access_token My belongs to model should like like so:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class RefreshToken extends Model { protected $table = 'oauth_refresh_tokens'; public function access_token() { return $this->belongsTo(AccessToken::class); } }
It seems that the relationships are created because I can eager load them without any errors, but they are consistently null. For both relationships.
If I call either of these:
$tokens = AccessToken::with('refresh')->get(); foreach ($tokens as $token) { $token->refresh // always has a value of null } $tokens = RefreshToken::with('access_token')->get(); foreach ($tokens as $token) { $token->access_token // always has a value of null }
What am I missing, this usually just works without a problem.
Thanks
vkronlein left a reply on File Not Found For Download
vkronlein started a new conversation File Not Found For Download
I'm getting a
FileNotFoundException using the Storage Facade when the file is indeed there. I'm looking at it in the damn folder. The path and filename are correct, I've triple checked everything ...
The weird part is I'm downloading it from another section via controller using
response()->download($same->path) and it works perfectly.
If I use
Storage::get($same->path) it returns the file as a string ... but the
download method can't seem to find it.
I've read the docs ... and I missing something obvious?
Thanks.
vkronlein started a new conversation Single Form For New And Editing Data
Can anyone tell me what's the best way for handling data for a form so that I can use my form for both editing an existing data object, or creating a new one?
If an item is being editing it's being pulled in via
mapGetters from Vuex, but it seems like if I'm doing it this way the new item form doesn't work correctly.
Should I create individual props for each form field and set them to null or data based on my pulled in Vuex computed props or is there an easier way to format this so it works consistently?
Any help would be greatly appreciated.
If you need any code please let me know what you want to see and I'll happily post it up.
vkronlein started a new conversation Computed Property Won't Render
I can't figure this one out.
I have a vuex-binding in my component that shows in the vue dev tools as correctly populated, then an additional computed property to select a given key from the object.
but when I try and render that property as v-html or v-model it throws an error
"TypeError: Cannot read property '1' of null"
computed: { ...mapGetters({ instructions: 'wizard/instructions' }), standard() { return this.instructions[this.isActive] } },
In the above,
isActive is numerical and represents a given key of the property to load
In my vuex dev tool I have
data isActive: 1 isOpen: false computed standard: "the html of the correct instruction" vuex bindings instructions: Object
In my template I have a simple bootstrap panel body div
<div class="panel-body" v-</div>
If I remove the binding to standard in the div the error stops, but with it in I get the error.
Any ideas would be helpful.
Thanks.
vkronlein left a reply on Extending ConsoleMakeCommand
Yeah honestly I think that should be changed for abstract methods. The purpose of declaring something abstract is so that it has no set up, which I think should include the signature.
We already have strict signature enforcement on Interfaces ...
Anyway, I was able to resolve it using reflection and middleware, but it should be easier to resolve this type of problem.
Thanks.
vkronlein left a reply on Extending ConsoleMakeCommand
How would I go about enforcing that a class has a given method, but making the signature flexible?
For instance I want to make my action classes all adhere to an interface that includes the
__invoke() method but can also have variables passed in, or be able to type hint classes in the signature.
I tried this:
namespace App\Domain\Contracts; interface ActionContract { public function __invoke($class = null); }
Then in my action :
public function __invoke(UserRepository $users) { return $this->responder->send(); }
But I'm getting the dreaded
must be compatible with error.
I want to ensure that the actions aren't creating traditional crud methods in order to keep the SOC principle intact by default.
I'll also need this type of functionality for my
Service classes as I want to force the handle method to receive some optional params while enforcing others.
Thanks.
vkronlein left a reply on Extending ConsoleMakeCommand
Yeah normally I would agree with you, but I really like the idea of ADR a lot. And I think the pattern in general is better for modern web apps. I'm constantly trying to clean up controllers and keep SOC and DRY principles.
@JeffreyWay has really helped me clean up my coding and reusability principles, and at least for me, ADR is the next step in this journey.
Thanks again for the assist.
vkronlein left a reply on Using Different Namespace For Controllers And How App\Http\Controllers Works.
Yeah I would recommend reading up on autoloading in PHP so you'll better understand how classes and files are loaded.
(PSR)[]
vkronlein left a reply on Trying To Get Property Of Non Object
Wow ... this is like a skit on SNL.
vkronlein left a reply on Extending ConsoleMakeCommand
I'm such and idiot ....
Look at the namespace .... should be
Commands not
Command
Thanks for your help man.
I'd love to get your opinion on how I've structured everything if you're interested.
vkronlein left a reply on Extending ConsoleMakeCommand
Any ideas?
All my other commands are working great.
vkronlein left a reply on Extending ConsoleMakeCommand
<?php namespace App\Domain\Console\Command; use Illuminate\Foundation\Console\ConsoleMakeCommand as BaseConsoleMakeCommand; class ConsoleMakeCommand extends BaseConsoleMakeCommand { /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return __DIR__.'/stubs/console.stub'; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Domain\Console\Commands'; } }
vkronlein started a new conversation Extending ConsoleMakeCommand
I'm creating an ADR version of the latest version of Laravel, mostly for my own use, but I will make it public for anyone who wants it.
As part of this I've moved all domain related stuff inside the domain directory, so this requires creating new make commands for generating classes to the correct location.
For all of these it's been very straightforward, create a new MakeCommand which extends the original one, change the namespace section, copy over the stub and make whatever changes are needed and register it in the Kernel.
Until ... the ConsoleMakeCommand.
Whoops\Exception\ErrorException : Cannot declare class App\Domain\Console\Command\ConsoleMakeCommand, because the name is already in use at /Users/vincek/Code/adr/web/app/Domain/Console/Commands/ConsoleMakeCommand.php:29 25| protected function getDefaultNamespace($rootNamespace) 26| { 27| return $rootNamespace.'\Domain\Console\Commands'; 28| } > 29| } 30|
This error doesn't make sense to me, I can't declare it in the file it's in, because it's already declared in the file it's in .... what the heck?
Can anyone explain to me how I can get this done?
Thanks.
vkronlein left a reply on LetsEncrypt 'ERROR: Challenge Is Invalid!' On Forge
What extra file?
vkronlein left a reply on Service Provider Not Publishing Config File
vkronlein started a new conversation Service Provider Not Publishing Config File
In my package, I have a config file to publish but in 5.6 it won't publish the file:
public function boot() { $this->publishes([ __DIR__ . '/../config/generator.php' => config_path('generator.php'), ]); }
When I run:
php artisan vendor:publish --provider=Empress\Generator\GeneratorServiceProvider
All I get is
Publishing complete. but nothing is published.
It will however publish if I use just
php artisan vendor:publish
I can then select the provider from the list and it does publish.
Is there something I'm missing here or something that's changed?
Thanks.
vkronlein left a reply on Laravel Is A Giant Waste Of Time
HAHAHAHAHAHA This was the best thing I've seen all month!
And to think it's been here for 2 years. Awesome.
Poor old @dazed067 is probably rocking a mullet and a Motorola flip phone, cause you know ... it takes a minute to set up that stupid iPhone ... I just wanna turn it on and start dialing.
Fabulous!
vkronlein started a new conversation API Resource Custom Conditional Pivot
The documentation stays to do a conditional pivot I have submit a closure like so:
public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'expires_at' => $this->whenPivotLoaded('role_users', function () { return $this->pivot->expires_at; }), ]; }
I have a resource that requires 10 different columns from the same pivot table, is there not a way to wrap these all within the same closure? Seems nuts to have to
whenPivotLoaded 10 different times on the same pivot table.
Anyone?
vkronlein left a reply on Checking For Deep Nested Relations For APIResources
Thanks. I searched but didn't find that one. That might work.
vkronlein started a new conversation Checking For Deep Nested Relations For APIResources
Hey All.
I have a project I've taken over that's already in production, so no blame for the database design please =)
I've been tasked to build an API which is coming along nicely, but I've run into a snag that I'd like to resolve, it's not life ending, but if there's a way to accomplish this I'd like to.
I'd like to be able to omit certain columns from my resource depending on whether relations and nested relations are loaded.
Here's the case I'm working on.
recordmodel has a product relationship
productmodel has a company relationship
recordstable has both a
company_idand
product_id
I'd like to show the model resource if the model has been loaded, or else the column value if not.
For direct relations this is a snap
In RecordResource:
$product = $this->relationLoaded('product') ? new ProductResource($this->product) : $this->product_id; return [ 'id' => $this->id, 'company_id' => $this->company_id, 'format_id' => $this->format_id, 'stage_id' => $this->stage_id, 'archived' => $this->archived, 'created' => $this->created_at->format('Y-m-d H:i:s'), 'updated' => $this->updated_at->format('Y-m-d H:i:s'), 'published_filename' => $this->published_filename, 'published_at' => $this->published_at, 'screened' => $this->screened->format('Y-m-d H:i:s'), 'inventory_type' => $this->inventory_type, 'leed_calc' => $this->leed_calc, 'leed_display' => $this->leed_display, 'no_accessory' => $this->no_accessory, 'product' => $product, ];
In ProductResource:
$company = $this->relationLoaded('company') ? new CompanyResource($this->company) : $this->company->name; return [ 'id' => $this->id, 'name' => $this->name, 'archived' => $this->archived, 'created' => $this->created_at->format('Y-m-d H:i:s'), 'updated' => $this->updated_at->format('Y-m-d H:i:s'), 'company' => $company, ];
These work perfectly since they are direct relations.
But if you look in the RecordResource array, I'd like to be able to remove the
company_id key if
company has been loaded in the ProductResource.
I know that having that
company_id in the table is redundant, but once again I didn't design the database and there's no changing it now.
Is there a way to test whether the company has been loaded from within the RecordResource given that it's nested?
Thanks.
|
https://laracasts.com/@vkronlein
|
CC-MAIN-2019-09
|
refinedweb
| 4,285
| 53.81
|
Created on 2014-11-12 10:20 by doko, last changed 2014-11-15 00:20 by Arfrever.
seen with the current 2.7 branch:
$ cat > x.py
def foo(): yield
gen = foo()
print gen.gi_frame.f_restricted
for i in gen: pass
print gen.gi_frame
gen = foo()
print gen.next()
print gen.gi_frame.f_restricted
$ python x.py
False
None
None
Segmentation fault
Program received signal SIGSEGV, Segmentation fault.
0x0000000000462b44 in frame_getrestricted (
f=Frame 0x7ffff7f58410, for file x.py, line 1, in foo (), closure=0x0)
at ../Objects/frameobject.c:383
383 ../Objects/frameobject.c: No such file or directory.
(gdb) bt
#0 0x0000000000462b44 in frame_getrestricted (
f=Frame 0x7ffff7f58410, for file x.py, line 1, in foo (), closure=0x0)
at ../Objects/frameobject.c:383
This is related to the fix for issue 14432. gen_send_ex sets f->f_tstate to NULL, so PyFrame_IsRestricted segfaults:
#define PyFrame_IsRestricted(f) \
((f)->f_builtins != (f)->f_tstate->interp->builtins)
Related change:
New changeset aa324af42c0e by Victor Stinner in branch '2.7':
Issue #14432: Generator now clears the borrowed reference to the thread state
This appears to be 2.7 only as 3.4.2 stops on the first print with AttributeError: 'frame' object has no attribute 'f_restricted', which is not a crash.
The fix for issue 14432 was applied to 3.3, but I'm pretty sure 2.x PyFrame_IsRestricted is the only problem. Nothing else should see f_tstate when it's NULL. Also, f_tstate was dropped from PyFrameObject in 3.4.
|
https://bugs.python.org/issue22851
|
CC-MAIN-2018-17
|
refinedweb
| 242
| 71.92
|
A newbie question. I have the following piece of Java code:
import acm.program.*;
import java.awt.Color;
import acm.graphics.*;
public class ufo extends GraphicsProgram{
private GRect ufo_ship;
...
Is there a short way to toggle a boolean?
With integers we can do operations like this:
int i = 4;
i *= 4; // equals 16
/* Which is equivalent to */
i = i ...
In Java can I return a boolean value with the following:
public boolean areBothEven(int i, int j) {
return (i%2 == 0 && j%2 == 0);
}
Is the expressions
!(a ==b) a!=b equivalent?
!a && b b &&!a
!a || b b ||!a
I am making a lottery program where I am asking if basically they would like a quick pick ticket. The numbers for their ticket of course would be random since ...
import java.util.Scanner;
class Practice {
public static void main(String args[]) {
System.out.println("Enter the number of treats you have:");
Scanner treatsScanner = new Scanner(System.in);
int ...
Okay, I need to be able to call a method and toggle a boolean value so that the return is different every time I need to be able to call the ...
public class MonsterTestDrive{ public static void main(String [] args){ Monster [] ma = new Monster[3]; ma[0] = new Vampire(); ma[1] = new Dragon(); ma[2] = new Monster(); for(int x=0; x<3; x++){ ma[x].frighten(x); } } } class Monster{ boolean frighten(int d){ System.out.println("arrrgh"); return true; } } class Vampire extends Monster{ boolean frighten(int x){ System.out.println("a bite"); return false; } } class Dragon extends ...
Simply stating "I get a big time error" doesn't really help us help you. WHAT exactly is the error? Is it when you try to compile or when you run it? If it's a compiler error, what is the exact text of the error? If it's during run-time, what exactly is it doing wrong - what do you expect to happen, ...
Hello, I'm trying to write a method that will accept three integers as parameters and return true if one of the integers is the midpoint between the other two integers, and order does not matter. I'd appreciate some help on how I should use boolean statements in this; would I just have an if/else statement for each possible situation? ie. if((a+b)/2 ...
Basically I am very new too java, I am an adult student and have been trying to understand return statements and Boolean expressions (used separately or together). The resources that I do have are just not clicking for me, so I was wondering if anyone could give me a crash course. Basically I under stand with Boolean the symbols such as ...
You should use a boolean or an enumated type for ***, not a String. That being said, compare strings with equals, not ==. You can also lose the extra parens -- && has lower priority, and you can also replace the if/then/else with something simpler. So [CODE] boolean bmiRange; if (g1="Male") && (bmi >= 19.1 && <= 25.8) { bmiRange=true } ...
Hey, I somewhere remember that if ... else ... can be written as booleanexpr?expr1true:expr2false ; but it doesn't work and the jvm gives " : expected as error" am i doing something wrong here? code : Vector lijst=new Vector(); for (int k=0;k
|
http://www.java2s.com/Questions_And_Answers/Java-Data-Type/Boolean/statement.htm
|
CC-MAIN-2014-10
|
refinedweb
| 548
| 66.44
|
Apache Commons/Net Jakarta License MUST be placed at the top of each and every file.
7. If you contribute to a file (code or documentation), add yourself to the authors list at the top of the file. For java files the preferred Javadoc format is:
@author <a href="mailto:user@domain.com">John Doe</a>
8. All .java files should have a @version tag like the one below.
@version $Id: code-standards.xml 561230 2007-07-31 04:17:09Z rahul $
9. Import statements must be fully qualified for clarity.
import java.util.ArrayList; import java.util.Hashtable; import org.apache.foo.Bar; import org.apache.bar.Foo;
And not
import java.util.*; import org.apache.foo.*; import org.apache.bar.*;
X/Emacs users might appreciate this in their .emacs file.
))
Thanks for your cooperation.
|
http://commons.apache.org/net/code-standards.html
|
crawl-001
|
refinedweb
| 136
| 63.76
|
A series of data points collected over the course of a time period, and that are time-indexed is known as Time Series data. These observations are recorded at successive equally spaced points in time. For Example, the ECG Signal, EEG Signal, Stock Market, Weather Data, etc., all are time-indexed and recorded over a period of time. Analyzing these data, and predicting future observations has a wider scope of research.
Plotting Time series Data:
Example:.
Download the dataset and place it in the current working directory with the filename “daily-min-temperatures.csv“.
Below is an example of loading the dataset as a Panda Series.
from matplotlib import pyplot
series = read_csv('daily-min-temperatures.csv', header=0, index_col=0, parse_dates=True, squeeze=True)
print(series.head())
Output:
Date 1981-01-01 20.7 1981-01-02 17.9 1981-01-03 18.8 1981-01-04 14.6 1981-01-05 15.8 Name: Temp, dtype: float64
plotting line chart for above dataset
from pandas import read_csv
from matplotlib import pyplot
series = read_csv('daily-min-temperatures.csv', header=0, index_col=0, parse_dates=True, squeeze=True)
series.plot()
pyplot.show()
Output:-
/>
Plotting Categorical Data
What is Categorical Data ?
Note: only a member of this blog may post a comment.
|
http://www.tutorialtpoint.net/2021/12/plotting-categorical-and-time-series-data-in-python.html
|
CC-MAIN-2022-05
|
refinedweb
| 209
| 53.98
|
I am a chess player and I like to play chess, in order to improve my chess skill recently I have decided to create a chess application which I can play with so I can further improve my chess skill and get ready to face a stronger opponent in a site like lichess. The below chess application will take me around a year to complete and I will show you all the progress from time to time.
This application will use the below tools to develop:-
- Python will be the programming language that needs to develop this application.
- Stockfish chess engine will be needed as the central mind of this application.
- stockfish module will be needed to link to the Stockfish chess engine.
- Pygame will be needed to display the graphic user interface of this chess application.
- I am using windows os to develop this application so it might not work for the user with the other OS.
In this chapter, we will first download the Stockfish chess engine from this site. I am using the 64bit version (Maximally compatible but slow) to suite my laptop. This chess engine alone does not do anything, we will need a stockfish engine wrapper which you can get from this site! There are other modules around that do the same thing but stockfish module appears to be very easy to use.
With the above two tools ready, we can now open up our PyCharm IDE and input the following code.
from stockfish import Stockfish stockfish = Stockfish("E:\StockFish\stockfish_20090216_x64") stockfish.set_position(["e2e4", "e7e6"]) print(stockfish.get_board_visual())
As you can see we first need to import the Stockfish module into our program. Next, we will pass in the path to the Stockfish chess engine as an argument when we create a Stockfish object. Next, we will set the first move for both the Milk and the Chocolate players. Finally, we will print out the chess position on the chessboard accordingly.
The chessboard looks really great but as I have mentioned before I will not use this display but instead will use PyGame to create the chess user interface for this chess application instead.
So there you have it, we have successfully installed the Stockfish module as well as downloaded the Stockfish chess engine.
What next? Next time we will install the PyGame module and show the chess pieces on the chessboard!
|
https://kibiwebgeek.com/beginning-steps-to-create-a-stockfish-chess-application/
|
CC-MAIN-2021-04
|
refinedweb
| 397
| 69.52
|
Dear ROOTers,
My various attemps failed to make a shared library for a class which uses external C structure.
A short example of code figuring out the problem is in attachment.
MyClass.tar.gz (2.06 KB)
Dear ROOTers,
Hello,
I don’t know if this is a legal source code for C/C++.
First, you have struct defined with in a namespace and without extern “C”. Then later, you define the same struct name in extern “C”. I think those are distingushed as different ones by C++ compiler. You have to be consistent. For example,
extern “C” {
struct yourstruct { … }
}
namespace yournamespace {
extern “C” struct yourstruct;
}
Thank you
Masa Goto
Hello,
A variant with the commented description of a structure produces even an error
in MyClassDict.cxx compilation. I just use these structure as prescribed method for
linkage with a fortran common.
I’ve managed to compile, link without ROOT and execute modules with
both variants of the structure description.
Is it possible to emdeb something like this in ROOT?
Valery.
Hello Valery,
Please simplify your code. I see complicated dependency between C and C++ namespace. Commeting out struct definition is not sufficient. I could compile it after separating C and C++ portion.
Thank you
Masa Goto
Hello Masa,
Even if i get rid of the namespace i don’t see the structure.
Thank you for help, Valery.
Hi,
Note that the pragma defined_in requires a full pathname.
So you need to add an explicity request to generate the dictionary for your struct.
Cheers,
Philippe.
|
https://root-forum.cern.ch/t/shared-library-for-class-which-uses-extern-struct/1155
|
CC-MAIN-2022-27
|
refinedweb
| 255
| 66.74
|
Mission5_Buzzer
In this project, you will get a buzzer buzzing. And its sound will change as you turn the potentiometer.
What you need
The parts you will need are all included in the Maker kit.
- SwiftIO board
- Shield
- Buzzer module
- Potentiometer module
- 4-pin cable
Circuit
Place the shield on top of your SwiftIO board.
Connect the potentiometer module to pin A0 using a 4-pin cable.
Connect the buzzer module to pin PWM2B (D10).
Example code
// Import the SwiftIO library to use everything in it.
import SwiftIO
// Import the board library to use the Id of the specific board.
import MadBoard
// Initialize the analog pin for the potentiometer.
let a0 = AnalogIn(Id.A0)
// Initialize the PWM output pin.
let buzzer = PWMOut(Id.PWM2B)
while true {
// Read the input voltage.
let value = a0.readPercent()
// calculate the float value into an integer to serve as frequency.
let frequency = Int(400 + 2000 * value)
// Set PWM parameters.
buzzer.set(frequency: frequency, dutycycle: 0.5)
// Set the duration of the notes.
sleep(ms: 20)
}
Background
Pulse Width Modulation (PWM)
Pulse Width Modulation (PWM) can simulate analog results digitally. The signal is still a square wave that switches between on and off. The duration of the "on-time" is called the pulse width. So this technique will change the duration of the high level relative to the low level and switch extremely quickly between them. In this way, it will simulate the voltage between fully open (3.3 volts) and off (0 volts).
In this case, if you repeat this switching pattern with LEDs fast enough, your eyes cannot notice the change and the signal seems to be a stable voltage between 0 and 3.3v. Thus the LED would show different brightness to your eyes.
Now come more concepts. A fixed time period consists of on and off time. The period is the inverse of the PWM frequency. For example, when the PWM frequency is 1000 Hz, one period is 1 millisecond..
Buzzer
The buzzer can buzz when you apply voltages. There is a diaphragm inside. But it can only generate a sound since the voltage cannot change.
- A passive buzzer needs PWM signals. When the signal switches between on and off, the internal diaphragm moves. The frequency of the signal will influence the pitch. A higher frequency will produce a higher pitch. That's how this projects works. a0 = AnalogIn(Id.A0)
let buzzer = PWMOut(Id.PWM2B)
Initialize the analog pin (A0) for the potentiometer and the PWM pin (PWM2B) for the buzzer.
while true {
let value = a0.readPercent()
let frequency = Int(400 + 2000 * value)
buzzer.set(frequency: frequency, dutycycle: 0.5)
sleep(ms: 20)
}
The potentiometer will control the buzzer all the time, so you write the code in the loop
while true.
In the loop,
- read the analog value and store it in the constant
value.
- set the PWM signal. You will need
set(frequency:dutycycle:). This method has two parameters: frequency and duty cycle. Its frequency is related to the analog value above. While the value is too small to be used as a frequency, so you do some calculations. The duty cycle doesn't really matter in this project, and you can set it to 0.5 here or any value.
- Use the function
sleep(ms:)to make each pitch will last about 20ms.
Reference
PWMOut - set the PWM signal.
AnalogIn - read the voltage from an analog pin.
SwiftIOBoard - find the corresponding pin id of SwiftIO board.
|
https://docs.madmachine.io/tutorials/swiftio-maker-kit/mission5
|
CC-MAIN-2022-21
|
refinedweb
| 578
| 69.99
|
Test-driven development is not about testing. Test-driven development is about development (and design), specifically improving the quality and design of code. The resulting unit tests are just an extremely useful by-product.
That's all I'm going to tell you about test-driven development. The rest of this article will show you how it works. Come work on a project with me; we'll build a very simple tool together. I'll make mistakes, fix them, and change designs in response to what the tests tell me. Along the way, we'll throw in a few refactorings, design patterns, and object-oriented design principles.
To make this project fun, we'll do it in Python.
Python is an excellent language for test-driven development because it (usually) does exactly what you want it to without getting in your way. The standard library even comes with everything you need in order to start developing TDD-style.
I assume that you're familiar with Python but not necessarily familiar with
test-driven development or Python's
unittest module. You
need to know only a little in order to start testing.
unittestModule
Since version 2.1, Python's standard library has included a
unittest module, based on JUnit
(by Kent Beck and Erich Gamma), the de facto standard unit test framework for
Java developers. Formerly known as PyUnit, it also runs on Python
versions prior to 2.1 with a separate download.
Let's jump right in. Here's a "unit" and its tests--all in one file:
import unittest # Here's our "unit". def IsOdd(n): return n % 2 == 1 # Here's our "unit tests". class IsOddTests(unittest.TestCase): def testOne(self): self.failUnless(IsOdd(1)) def testTwo(self): self.failIf(IsOdd(2)) def main(): unittest.main() if __name__ == '__main__': main()
Methods whose names start with the string
test with one
argument (
self) in classes derived from
unittest.TestCase are test cases. In the above example,
testOne and
testTwo are test cases.
Grouping related test cases together, test fixtures are classes that derive
from
unittest.TestCase. In the above example,
IsOddTests is a test fixture. This is true even though
IsOddTests derives from a class called
TestCase, not
TestFixture. Trust me on this.
Test fixtures can contain
setUp and
tearDown
methods, which the test runner will call before and after every test case,
respectively. Having a
setUp method is the real justification for
fixtures, because it allows us to extract common setup code from multiple test
cases into the one
setUp method.
In Python we typically don't need a
tearDown method, because we
can usually rely on Python's garbage collection facilities to clean up our
objects for us. When testing against a database, however,
tearDown
could be useful for closing connections, deleting tables, and so on.
Looking back at our example, the
main function defined in the
unittest module makes it possible to execute the tests in the same
manner as executing any other script. This function examines
sys.argv, making it possible to supply command-line arguments to
customize the test output or to run only specific fixtures or cases (use
--help to see the arguments). The default behavior is to run all
test cases in all test fixtures found in the file containing the call to
unittest.main.
Executing the test script above should produce output that resembles:
.. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK
If the second test had failed, the output would have looked something like this:
.F ====================================================================== FAIL: testTwo (__main__.IsOddTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\jason\projects\tdd-py\test.py", line 14, in testTwo self.failIf(IsOdd(2)) File "C:\Python23\lib\unittest.py", line 274, in failIf if expr: raise self.failureException, msg AssertionError ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=1)
Typically, we wouldn't have the tests and the unit being tested in the same file, but it doesn't hurt to start out that way and then extract the code or the tests later.
Guess what I have trouble remembering to do:
0 0 * * * [ `date +\%m` -ne `date -d +4days +\%m` ] \ && mail -s 'Pay the rent!' me-and-my-wife@example.org < /dev/null
That little puzzle is a line out of my crontab that emails me a reminder to pay the rent on the last four days of each month. Pathetic? Probably. It works, though. I haven't been late paying rent since I started using it.
As clever as I thought I was for coming up with this, it wasn't practical for everything--especially for events that occur only once. Also, there's no way I could teach my wife enough bash scripting techniques in order to add a reminder to our calendar.
Most people use a good old-fashioned wall calendar for this type of thing. That's not techno-geeky enough for me.
I could use Outlook or Evolution or some productivity application, but that would open up a whole new can of worms. We don't use just one computer. We both use multiple computers and operating systems at home and at work. How could we easily synchronize all of those machines?
It was after realizing that our email is available to us no matter where we were that I hit upon the motivation for my project. The email reminding me to pay the rent was with me no matter what machine I'm on because I always check my email via IMAP, so my email is accessible from everywhere.
Why not email the upcoming events in my calendar to me just like my reminder to pay the rent? Brilliant, I thought. I know just the tools that can do this, too: the BSD calendar application and the new kid on the block, pal.
My wife and I have a private wiki that we use for keeping track of notes.
It's great. Despite the fact that my wife's an accountant and not a geek, she
has no trouble using it. I figured we could use the wiki to edit our calendar
file. I would write a little cron job to fetch the calendar file--probably
using
wget--from the wiki and pipe that into whatever tool best
fit our needs.
Unfortunately, after looking at both
calendar and
pal, I discovered that neither was what I was looking for.
The calendar file format requires a <tab> character between dates and
descriptions. Since I wanted to use our personal wiki to edit the calendar
file, inserting <tab> characters would be an issue (upon hitting
<tab>, focus jumps out of the text area to the next form control).
calendar also doesn't support any of the fancy output options that
pal does.
The
pal format was much too geeky for even me to want to use,
and it didn't support the one really important use case I had so far: setting a
reminder for the last day of the month.
My wife and I sat down and came up with something both of us would want to use. Here are some examples:
30 Nov 2004: Dinner with the Darghams. April 10: Happy Anniversary! Wednesday: Piano lesson. Last Thursday: Goody night at book study. Yum. -1: Pay the rent!
Unlike the calendar format, a colon separates dates from descriptions. How Pythonic.
Like the calendar format, omitted certain fields are wildcards. The
April 10 event happens every year. The
Last Thursday event happens on the
final Thursday of every month of every year.
The
-1 event happens on the last day of every month of every year too. I
took this idea from Python's array subscript syntax, where
foo[-1]
selects the last element in the foo array. I thought it was a little geeky, but
my wife understood it right away.
My goal is to write a small application that can run from cron to read a file in this format and email my wife and me the events we have scheduled for the next seven days. That shouldn't be too hard, should it?
From this point on, I'm writing this article in real time, having contrived nothing. I didn't write the code first and then write the article--I'm writing the article as I write the code. Yes, I expect to make mistakes. In fact, I'm counting on it. Making mistakes is the best way to learn.
Being test infected means that I must write this tool by writing all of my unit tests before writing the code I expect the tests to exercise.
The first thing I do when starting a new project is to create an empty fixture that fails:
import unittest class FooTests(unittest.TestCase): def testFoo(self): self.failUnless(False) def main(): unittest.main() if __name__ == '__main__': main()
I do this out of habit, just to make sure I have everything typed in correctly and to test that the test runner can find the fixture.
Notice the class named
FooTests and its
testFoo
method. At this point I have no idea what I'm going to test first. I
just want to make sure that I have everything ready once things get going.
Let's start out easy and test the first example from above with the full day, month, and year specified for the event. In order to create this test, I need know what to test. Am I testing a class? A function?
This is where we put on our designer hats for a brief moment and try to use our experience and intuition to come up with some piece to the puzzle that will help us reach our goal. It's OK if we make a mistake here; the tests will reveal that right away, before we invest too much in this design. We certainly don't want to draft any documents filled with diagrams. Save those for later, after we have a clue about what will actually work.
For this project, I should probably create objects that can say whether they "match" a given date. These objects will act as a "pattern" for dates. (I'm using regular expressions as a metaphor here.)
Eventually, I'll have to write a parser that will read in a file and create these pattern objects, but I'll do that later. These pattern objects are probably an easier place to start.
There might be multiple types of patterns--but I won't think about that now, because I could be wrong. Instead, I'll start coding so I can let it tell me what it wants to become:
def testMatches(self): p = DatePattern(2004, 9, 28) d = datetime.date(2004, 9, 28) self.failUnless(p.matches(d))
Notice that I changed the name of the method from
testFoo to
something more appropriate, because I now have an idea about what to test. I've
also invented a class name,
DatePattern, and a method name,
matches. (The
datetime module is part of Python 2.3
and up--I had to import it at the top of my file in order to use it.)
This test, of course, fails miserably--the
DatePattern class
doesn't even exist yet! But I at least know now the name of the class I need to
implement. I also know the name and signature of one of its methods and the
signature for its
__init__ method. Here's what I can do with this
knowledge:
class DatePattern: def __init__(self, year, month, day): pass def matches(self, date): return True
Now the test passes! It's time to move on to the next test.
You probably think I'm joking, don't you? I'm not.
Test-driven development is best when you move in the smallest possible increments. You should only be writing code that makes the current failing test case(s) pass. Once the tests pass, you're done writing code. Stop!
The above code is worthless, right? It basically says that every pattern matches every date. How can I justify spending the time to come up with a "real" implementation? By adding another test:
def testMatchesFalse(self): p = DatePattern(2004, 9, 28) d = datetime.date(2004, 9, 29) self.failIf(p.matches(d))
We now have one passing test and one failing test.
I could change the
matches method to return
False
in order to make this new test case pass, but that would break the old one! I
now have no choice but to implement
DatePattern correctly so that
both tests can pass. Here's what I came up with:
class DatePattern: def __init__(self, year, month, day): self.date = datetime.date(year, month, day) def matches(self, date): return self.date == date
Both tests now pass. Woo-hoo! I'm not happy with the
DatePattern class, though. So far, it's nothing more than a simple
wrapper around Python's
date class. Why am I not just using
date instances for my "patterns"?
It might turn out that the
DatePattern class is unnecessary, but
I'm not going to make that decision on my own. Instead, I'm going to write
another test--one that I think will confirm the necessity of the
DatePattern class:
def testMatchesYearAsWildCard(self): p = DatePattern(0, 4, 10) d = datetime.date(2005, 4, 10) self.failUnless(p.matches(d))
Voilà! This test fails!
Why am I so happy about a failing test? My reasoning is simple: this
proves that the current implementation of
DatePattern is
insufficient. It can't be just a simple wrapper around
date and therefore can't be just a
date.
While typing this test, I had to make a decision about how to represent wildcards. What occurred to me first was to use
0. After all,
there's no year 0 (contrary to popular belief), month 0, or day 0. This may not
have been the best choice, but I'm going to roll with it for now.
It's time to make the new test pass (while making sure not to break the old ones):
class DatePattern: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def matches(self, date): return ((self.year and self.year == date.year or True) and self.month == date.month and self.day == date.day)
To be honest, I'm already starting to feel like I'll need to do some refactoring as I add more wildcard functionality to the class, but I want to write a few more tests first.
Let's add a test where the month is a wildcard:
def testMatchesYearAndMonthAsWildCards(self): p = DatePattern(0, 0, 1) d = datetime.date(2004, 10, 1) self.failUnless(p.matches(d))
Fixing
matches so that the test passes results in this:
def matches(self, date): return ((self.year and self.year == date.year or True) and (self.month and self.month == date.month or True) and self.day == date.day)
This method is getting uglier every time we touch it--I'm now positive that it will be my first refactoring victim.
I now have a test for using wildcards for both years and months. Will I need one for days? A pattern containing nothing but wildcards would match every day. When would that be useful?
At this point I can't think of a reason to support wildcard days, so I
won't bother writing a test for it. Because of that, I also won't bother
implementing any code to support it in the
DatePattern class.
Remember, code gets written only when there's a failing test that needs the new
code in order to pass. This prevents us from writing code that should not exist
in our application, which should help keep it from becoming unnecessarily
complex.
Let's move on. We need to support events that occur on a specified day of every week:
def testMatchesWeekday(self): p = DatePattern(
Uh, what now?
At this point, I realized that the
DatePattern class might not
be what I want to use for this test. Its
__init__ method doesn't
accept a weekday. Should I use a different class, or modify the existing
one?
I decided to modify the existing one for now, as that will require the least amount of work. If this turns out to be a bad idea, I can always refactor later.
def testMatchesWeekday(self): p = DatePattern(0, 0, 0, 2) # 2 is Wednesday d = datetime.date(2004, 9, 29) self.failUnless(p.matches(d))
This doesn't pass because
DatePattern.__init__ doesn't accept five arguments (counting
self). I modified
__init__ to
look like this:
def __init__(self, year, month, day, weekday=0): self.year = year self.month = month self.day = day self.weekday = weekday
I gave
weekday a default value so that I wouldn't need to
update the other test cases. Everything compiles and runs, but the new test case
doesn't pass.
The astute reader has probably already realized that I'm now passing in
0
for the
day argument. There's the wildcard I didn't think I would
need--now I need it!
Here's my new
matches method:
def matches(self, date): return ((self.year and self.year == date.year or True) and (self.month and self.month == date.month or True) and (self.day and self.day == date.day or True) and (self.weekday and self.weekday == date.weekday() or True))
Now all of the components of a pattern allow for wildcards. How very interesting.
With this new method,
testMatchesWeekday passes but
testMatchesFalse now fails! What gives?
I honestly can't tell why
testMatchesFalse fails by looking at
the code. This is going to call for some simple debugging. Unfortunately, I
tried to cram all of the logic for the
matches method into one
expression (spanning four lines!), so there's no place for me to insert any
print statements to help me see which part is failing. It's finally time to do
that refactoring I've been wanting to do.
The refactoring I want to apply is the Compose
Method from Joshua Kerievsky's excellent book, Refactoring to
Patterns. By extracting smaller methods from the current
matches method, I can not only make
matches clearer
but also make it possible to debug whichever part is currently causing me
grief.
This is the result:
def matches(self, date): return (self.yearMatches(date) and self.monthMatches(date) and self.dayMatches(date) and self.weekdayMatches(date)) def yearMatches(self, date): if not self.year: return True return self.year == date.year def monthMatches(self, date): if not self.month: return True return self.month == date.month def dayMatches(self, date): if not self.day: return True return self.day == date.day def weekdayMatches(self, date): if not self.weekday: return True return self.weekday == date.weekday()
The
matches method is now much clearer, don't you agree? It
might seem like a ridiculous thing to do, but writing intention-revealing code
is much more important than being clever. I was trying to be too clever before
and it caused a bug--one that I wouldn't have come across if I had done this
from the beginning.
After applying this refactoring and rerunning the tests, I expected to see
the
testMatchesFalse test still failing, but it's now passing.
Somewhere in my original logic I made an error, and I have no idea where it
was--I'll leave finding it as an exercise for the reader. In the meantime, not only do I have simpler code now but it also actually works the way I expect it to.
Take that!
Would I have noticed this bug without tests? I have no doubt that I would, but how long would it have been before I realized that this was a problem? With my unit tests, I noticed it immediately, so I knew exactly what to fix.
Wildcards essentially work for all of the components I'm testing so far. This is good, but I think the next test will cause trouble. It starts out innocently enough:
def testMatchesLastWeekday(self): p = DatePattern(0, 0, 0, 3
Er, I'm stuck again.
In case it's not obvious (and it's not--why didn't Python's
datetime module define constants for weekdays?), the
3
represents Thursday.
How do I indicate that I only want to match the last Thursday in a
month? Do I need to add yet another argument to
DatePattern.__init__?
This is where that sneaking suspicion in the back of my head is finally starting to warrant some closer attention. I might be trying to cram too much functionality into one class.
I haven't written much code yet, but that's a good thing, since it seems that
the code I have written might not have been sufficient for what I want to do
with it. Without the tests, I might not have discovered what a mess I was
writing until it was too late. At this point, I haven't invested too much time
into the
DatePattern class, so I won't feel bad about throwing it
away if that's what I'll need to do.
I have some ideas about how to restructure the code so that it's as simple and yet as functional as I want it to be, but we're going to have to save those for Part 2 of this article, which will be published shortly.
Code and tests are available for download and inspection.
Jason Diamond is a consultant specializing in C++, C#, and XML, and is located in sunny Southern California.
Return to the Python DevCenter.
|
http://www.oreillynet.com/lpt/a/5463
|
CC-MAIN-2013-20
|
refinedweb
| 3,615
| 75.1
|
This lesson introduces the course by giving you an overview of what to expect in the entire course and explains why you should care about PEP 8. You’ll see that PEP 8 exists to improve the readability of Python code, helps you collaborate well with others and makes it easier for them to understand the code you write.
What PEP 8 Is and Why You Need It
00:00 Hey there! Welcome to the Real Python guide on how to write beautiful Python code with PEP 8. In this set of videos, you’ll learn how to write code that conforms to PEP 8, understand the reasoning of why PEP 8 was laid out, and how to set up your development environment to start writing PEP 8 compliant Python. So, why should you care about PEP 8?
00:23
PEP 8 refers to a document that contains guidelines and best practices on how to write Python code. If you’re not familiar with the Zen of Python, open a terminal and
import this to see it.
00:38
Go to your terminal and start the Python interpreter. Then, just
import this, just like that. You’ll see the Zen of Python print out to your console.
00:51
This is a pretty cool Easter egg of Python that gives you some tips on how to write good Python code. If you look down here, one of the lines is
Readability counts. So, why is that?
01:06 Guido van Rossum said that “Code is read much more often than it is written.”
01:12 If you think about this, it makes sense. You may write a line of code once, but if you ever go back to refactor it or modify it, you have to read it again and know why you put it there.
01:21 This could be weeks or months after you wrote it. PEP 8 is designed to help you when you come back to a piece of code so you know why you did what you did by giving you a structure to your process.
01:34 It also helps if you want to work with others. If you and your team are all writing to the same standards of code, it becomes much easier to collaborate. This becomes especially important if you’re looking to get a development job, as you’ll be expected to work well with others.
01:49 Now that you know a little bit of the why behind PEP 8, let’s take a look at some examples so that you can start writing some beautiful Python.
Become a Member to join the conversation.
Anu on March 15, 2019
Hi All, Please could you help me understand which one is better pylint or flake8? Also, is there any way to configure flake8 with pycharm? Thanks in advance! Regards, Anu
|
https://realpython.com/lessons/what-pep-8-and-why-you-need-it/
|
CC-MAIN-2021-25
|
refinedweb
| 480
| 87.86
|
7.0 Package locking and package definition locking below.
The initial package when Allegro CL is started in the :cl-user package when not starting in the IDE and the :cg-user package when starting the IDE. To change the initial package when using the IDE, see the section Note on the initial package in cgide.htm. When not using the IDE, see The package on startup in startup.htm.
Allegro Common Lisp supports fully hierarchical packages. Hierarchical
packages, which are part of many modern languages but not part of ANSI
Common Lisp, are a convenient way to manage namespaces because you
have freedom to choose the name of the root package and then can use
any names you like for the lower-level packages, even names used by
other modules. So you can have your own
:test package
just like every other module.
The hierarchical package implementation affects output
of find-package
(either a direct call or an implicit call triggered by use of a
package qualifier or an argument to in-package or other package-related
function). When given a name containing dots, it tries to resolve the
name in a hierarchical fashion, with respect to the current value
of
*package*. This means that find-package
may have different behavior for names that contain dots depending on
the value of
*package*:
cl-user(9): (defpackage :mypack) #<The mypack package> cl-user(10): (defpackage :mypack.test) #<The mypack.test package> cl-user(11): (find-package :.test) nil cl-user(12): (in-package :mypack) #<The mypack package> mypack(13): (find-package :.test) #<The mypack.test package> mypack(14):
In the example,
(find-package :.test)
returns
nil when
*package* is
the
:cl-user package and returns
the
:mypack.test package
when
*package*
is the
:mypack package. Note that this is
non-standard behavior. The ANS says that find-package should return the same
value for the same argument regardless of the value
of
*package*.
We have implemented hierarchical packages because of the convenience it offers. Hierarchical packages:
The problem with implementing full hierarchical packages in Common
Lisp is that you need a special character to indicate the hierarchy
levels (we used a period, also called a dot) but this character
is not special in ANSI Common Lisp. Therefore, names
like
foo.bar and
.bar are legal
package names in Common Lisp and have nothing to do with
hierarchy. The hierarchical structure must be superimposed on the
standard Common Lisp package structure.
This issue manifests itself if you have packages with names containing dots, particularly dots at the beginning of the name. It also manifests itself in the treatment of nicknames. We discuss both of these issues below.
Note that we give package names as keywords (
:foo
for the
foo package). In modern Lisp, symbol names
are case-sensitive and the
:foo package has name
"foo". In ANSI Lisp, symbol names are case-insensitive and
the
:foo package has name "FOO". In the remainder
of this discussion, we will use lowercase names and the examples are
from a modern implementation (with occasional reminders of the
issue). See case.htm for a discussion of modern and
ANSI Lisps.
Here is the terminology we will use when discussing hierarchical packages:
foopackage,
(defpackage :.bar)creates a package with name ".bar" (in a modern Lisp, ".BAR" in an ANSI Lisp). It does not create the package
:foo.barand
(find-package :.bar)returns the
:.barpackage, not the
foo.barpackage (assuming the
foo.barpackage has not also been created explicitly).
:.bar-- or a trailing dot --
:bar.). For example
foo.bar.baz. (Multiple consecutive dots --
:bar..baz-- are also not allowed.) If all the ancestor packages exist, this package will be relative to them and using relative name will work when applicable.
:..barand
.bar.bazbut not
.bar..bazor
.bar.). When trying to find the package named by a relative name, the system will combine the relative name with the current package name as described below. If that does not find a package, then a package with that absolute name will be looked for.
(defpackage :foo.bar (:nicknames :foobar))is an example.
:flat toption to defpackage or make-package.
(defpackage :foo.bar (:nicknames :foo.b) (:flat t))is an example.
(defpackage :a.b (:nicknames :anick.bnick.cnick))is an example.
(defpackage :foo.bar (:nicknames :baz.b))is an example. Note the parent package (
:fooin this case) need not exist when the package is created.
For
:flat
t nicknames, they are used as specified regardless of
whether they contain dots. So
(defpackage :foo (:nicknames
:baz.bar) (:flat t)) creates a package with
name
:foo and nickname
:baz.bar
and (assuming no other definitions are
relevant)
(find-package :bar.baz) will return the
:foo package while
(find-package :.bar) will return
nil. Nicknames are further discussed
in Section 2.5 Package nicknames: absolute and relative below.
name1.name2.[...]nameN.name. The parent of that package is is
name1.name2.[...]nameN. All packages
name1,
name1.name2, etc. through
name1.name2.[...]nameNare ancestor packages. So for package
:foo.bar.baz,
:foo.baris the parent and it and
:fooare ancestors.
[name of B].[name]. So
:foo.bar.bazand
:foo.barare both subpackages of
:foo.
Hierarchical packages are defined by indicating the hierarchy with dots (periods) in names. For package names, singleton dots can appear separating the various package ancestors, but there cannot be a leading dot, a trailing dot, or any multiple consecutive dots (if any of those appear, the specified name is the absolute name of the package which is not in a hierarchy). For relative names, there must be at least one leading dot but can be any number, and there can be singleton dots elsewhere, but no trailing dot.
The problem is dots are not special characters and so Common Lisp
allows any number of dots in package names. However, dots do matter in
the hierarchical package implementation. As said above, hierarchical
packages affect what package is found by
(find-package
:<name>) directly or implicitly with
<name>::<symbol> and
in package arguments to operators. Mixing
packages with names that beging with a dot with relative package names
can result in unexpected results because of shadowing and name
conflicts. Here is an example:
;;):
You might think you should avoid package names beginning with a dot
entirely, but one can imagine scenarios where such names might be
useful. Suppose in your hierarchy, every package has a subpackage with
relative name
:.test. You may wish to also create a
:.test package (with
(defpackage
:.test)) so
(find-package :.test) will
never return
nil regardless of the value of
*package*. But
outside of that case, leading dots in package names should likely be
avoided.
Because a dot (period) delimits levels of the package hierarchy, a trailing dot does not make sense in a hierarchical scheme: it should be followed by a name lower in the hierarchy but there is no name.
Therefore, package names or nicknames ending with one or more dots are considered flat names (not hierarchical names).
A package name containing one or more single dots (but no multiple
consecutive dots, no leading dot, and no trailing dot) is potentially
a hierarchical package. So
(defpackage
:foo.bar.baz) is potentially a hierarchical package, with
name "foo.bar.baz" and potential ancestors the
:foo
package and the
:foo.bar package, if they exists. When
the
:foo package and
the
:foo.bar packages are defined, then the
:foo.bar.baz package becomes a hierarchical package
and rules for resolving relative names will apply. This rules are
described in Section 2.6 Resolving relative package names
below.
To repeat and important point: a package become hierarchical when all its potential ancestor packages exist. The package will be immediately hierarchical if they already exist when the package is created. It becomes hierarchical later if the ancestor packages do not exist but are created later.
Package nicknames are specified by the
:nicknames
option to defpackage/argument
to make-package. The
nickname will be hierarchical if it has the same number of dots, the
same parent (everything up to the last dot), and is not specified as
flat. In that case, relative names can be used when the current
package is the parent package (or one of its ancestors). (Nicknames
ending in a dot are an anomaly discussed
in Section 2.8 Hierarchical package anomalies below.) Nicknames
without dots, with a different number of dots, or with a different
parent are absolute (or flat) nicknames and can be used to find the
package regardless of the value of
*package*.
Consider the following example:
cl-user(2): (defpackage :newpack) #<The newpack package> cl-user(3): (defpackage :newpack.test (:nicknames :mytest :different-parent.nopt :a..lot...of...dots...newpt :newpack.npt)) #<The newpack.test package> ;; The full nicknames all work, flat or relative: cl-user(4): (find-package :mytest) #<The newpack.test package> cl-user(5): (find-package :different-parent.npt) #<The newpack.test package> cl-user(6): (find-package :a..lot...of...dots...newpt) #<The newpack.test package> cl-user(7): (find-package :newpack.npt) #<The newpack.test package> cl-user(8): (find-package :.npt) ;; relative name but not in the right package to resolve ;; the relative name. See below when *package* is ;; the :newpack package. nil cl-user(9): (in-package :newpack) #<The newpack package> ;; The possible relative nicknames are :.nopt, :.newpt, and :.npt ;; from nicknames :different-parent.nopt, :a..lot...of...dots...newpt, ;; and :newpack.npt. But only the last works when in the :newpack ;; package. All the rest have something which disqualifies them. newpack(10): (in-package :newpack) #<The newpack.test package> newpack(11): (find-package :.nopt) ;; :different-parent.nopt has the right number of dots but ;; a different parent. nil newpack(12): (find-package :.newpt) ;; :a..lot...of...dots...newpt has too many dots. nil newpack(13): (find-package :.npt) ;; This one is a proper relative package nickname. #<The newpack.test package> newpack(14): (find-package :.newpt) nil newpack(11): (find-package :newpack.npt) ;; relative nicknames only work as relative names. Their full ;; name is not a nickname. nil newpack(15):
If the
:flat option to defpackage/keyword argument to
make-package is
specified true, the name is stored in the flat hashtable rather than as part of a hierarchy and all nicknames defined are made absolute nicknames
whether or not they contain dots (see
Extensions to cl:make-package,
cl:disassemble, cl:truename, cl:probe-file, cl:open,
cl:apropos and cl:defpackage and cl:in-package, both in
implementation.htm, for more information on
extensions to defpackage and make-package.)
The fact that the name is stored in the flat hashtable is an
implementation detail which may have no visible consequences to the
user (so
(defpackage :foo) and
(defpackage
:foo.bar (:flat t)) ctreates
packages
:foo and
:foo.bar, and
even though
:foo.bar is
flat,
(find-package :.bar)
when
*package*
is the
:foo package returns
the
:foo.bar package). The consequences to
nicknames is, howver, significant, as we discuss next.
In this example, we specify nicknames containing dots but also specify
:flat t. As a result, all the nicknames are
absolute nicknames and none work as relative nicknames.
cl-user(53): (defpackage :pack1) #<The pack1 package> cl-user(54): (defpackage :pack1.flatpack (:nicknames :.fpk :a..lot.of..dots :.pack1.gp :flatpk) (:flat t)) #<The pack1.flatpack package> cl-user(55): (find-package :.fpk) ;; absolute nickname, not relative #<The pack1.flatpack package> cl-user(56): (find-package :a..lot.of..dots) ;; absolute here too #<The pack1.flatpack package> cl-user(57): (find-package :flatpk) ;; this one is always absolute #<The pack1.flatpack package> cl-user(58): (in-package :pack1) #<The pack1 package> pack1(59): (find-package :.gp) ;; Without :flat t, this would work ;; as a relative nickname nil pack1(60): (find-package :.fpk) ;; this is an absolute nickname and ;; so works (it just looks like a relative ;; nickname) #<The pack1.flatpack package> pack1(61): (find-package :a..lot.of..dots) ;; absolute nickname #<The pack1.flatpack package> pack1(62):
When find-package is
passed an actual package name or an absolute nickname, the associated
package is returned (except perhaps when the name looks like a
relative name,
see Section 2.8 Hierarchical package anomalies). When it is passed
a relative name, it tries to resolve that name with respect to the
current package (the value of
*package* and returns the package
found, if any. find-package tries to resolve relative
names with
*package* before it looks for an
absolute name that resembles the relative name but it will find the
absolute name if there is no relative name resolution.
A relative package name is a name that starts with any number
of dots (but at least one) and may contain additional single dots, but
does not end with a dot and contains no additional multiple
consecutive dots. So
:.foo,
:...foo,
:.foo.bar, and
:..foo.bar.baz
are all relative names but
:[any character beside a
dot][pehaps more characters],
:p.foo,
:..foo..bar, and
:.foo. are not.
When there are multiple dots at the beginning, they are treated
analogously with initial dots in pathnames, with a single dot meaning
the current package, two dots meaning the parent of the current
package, and more than two meaning ancestors of the current package
further back.
(find-package :.) always returns the
current package.
(find-package :..) returns the
parent of the current package, if there is one (and signals an error
if there is not).
Here are multiple examples of resolving relative pathnames. Note that resolving relative package names is done by explicit calls to find-package and also by implicit calls, such as finding the package indicated by a package qualifier to a symbol or finding the package in a call to in-package.
In these examples, we assum that packages
named
mypack,
mypack.foo,
mypack.foo.bar,
mypack.foo.baz,
mypack.bar,
mypack.bar.baz,
foo, and
foo.bar, have all been created:
Because Allegro CL implements true hierarchical packages, relative nicknames can be used in place of relative names at any level, and absolute nicknames can also be used, as the following example shows:
cl-user(78): (defpackage :zpack (:nicknames :zpa)) #<The zpack package> cl-user(79): (defpackage :zpack.foo (:nicknames :.zfo :zop)) #<The zpack.foo package> cl-user(80): (defpackage :zpack.foo.bar) #<The zpack.foo.bar package> cl-user(81): (find-package :zpa.foo) #<The zpack.foo package> cl-user(82): (find-package :zpa.zfo) #<The zpack.foo package> cl-user(83): (find-package :zpack.zop.bar) ;; zop is an absolute nickname nil cl-user(84): (find-package :zop.bar) ;; so this works #<The zpack.foo.bar package> cl-user(85): (in-package :zpack) #<The zpack package> zpa(86): (find-package :.zop) ;; again, an absolute nickname nil zpa(87): (find-package :.zfo) #<The zpack.foo package> zpa(90): (in-package :zpack.foo.bar) #<The zpack.foo.bar package> zpack.foo.bar(91): (find-package :.) #<The zpack.foo.bar package> zpack.foo.bar(92): (find-package :..) #<The zpack.foo package> zpack.foo.bar(93): (find-package :...) #<The zpack package> zpack.foo.bar(94): (find-package :...foo) #<The zpack.foo package> zpack.foo.bar(95):
Because implementing hierarchical packages makes dots into special characters, you may see behavior which is unexpected or (at first) unintuitive (and also not what standard Common Lisp would do). This has been true since partial hierarchical packages were first introduced and remains true now that fully hierarchical packages have been implemented.
;;):
:flat tin the defpackage or make-package form (see Extensions to cl:make-package, cl:disassemble, cl:truename, cl:probe-file, cl:open, cl:apropos and cl:defpackage and cl:in-package, both in implementation.htm, for more information on extensions to defpackage and make-package), specifying a nickname ending in a dot (like
(:nicknames :foo.bar.baz.)) will follow the relative nickname rule of ignoring everything up to the last dot, and so the nickname will be "." which in any case names the current package. In some cases, you may get an error.
nilif the string obtained from its argument does not name a package. However, if passed a name beginning with more than one dots, it tries to find the parent of the current package, and (if necessary) the parent of that package, and so on until all dots are resolved. If at any point there is no parent, then an error is signaled. So:
zpack.foo.bar(106): *package* #<The zpack.foo.bar package> zpack.foo.bar(107): (find-package :.) #<The zpack.foo.bar package> zpack.foo.bar(108): (find-package :..) #<The zpack.foo package> zpack.foo.bar(109): (find-package :...) #<The zpack package> zpack.foo.bar(110): (find-package :....) Error: The parent of package #<The zpack package> does not exist.
BETA NOTE: The correct behavior for these cases is still under review. Behavior may change in the final release.
Allegro CL typically puts newly created packages under the following top-level names:
The use of these top-level names as packages in applications might run into problems with Allegro CL. Note that all current package names (such as excl, system etc.) will also be used.
To facilitate using hierarchical packages, there are the functions package-parent and package-children.
Package-local nicknames were implemented by a patch for Allegro CL 10.1 released in August, 2019. This document assumes that patch has been applied. See sys:update-allegro for information on applying patches.
The Allegro CL hierarchical package feature (described above in the
section Section 2.0 Hierarchical Packages) allows packages
to be arranged in hierachies so that programmers may use shorter
labels for packages when the current value of
*package* is a package higher in the
hierarchy. However the shorter name needed to start with one of more
dots.
But another way to define local nickanmes does away with leading
dots. It allows a package to have a specified nickname in a specified
package (called the housing package). When the housing package
is the current package, that is the value of
*package*, the local nickname
applies. Local nicknames can be specified when a housing package is
created with defpackage or make-package.
(See Extensions to
cl:make-package and cl:defpackage and cl:in-package
in implementation.htm.) Local nicknames can also be
added with the function add-package-local-nickname.
Here is an example:
cl-user(9): (defpackage :bar (:intern #:x)) #<The bar package> ;; Using the new :LOCAL-NICKNAMES option, we specify that when the current ;; package is :MYPACK, :B is a nickname of the :BAR package (the value of ;; :LOCAL-NICKNAMES is a list (NICKNAME PACKAGE-NAME)) cl-user(10): (defpackage :mypack (:use :cl :excl) (:local-nicknames (:b :bar))) #<The mypack package> ;; While the current package is :CL-USER, there is no package ;; named :B: cl-user(11): (find-package :b ) nil cl-user(12): (in-package :mypack) #<The mypack package> ;; BUT when the current package is :MYPACK, :B is a nickname of the ;; :BAR package: mypack(13): (find-package :b ) #<The bar package> mypack(14): (eq 'b::x 'bar::x) t
Even though you an get similar behavior with hierarchical packages, it
is not the same. If you are importing code from elsewhere or using
Lisp libraries from elsewhere, redefining packages so they are
hierarchical may not be easy and does cause your code to diverge from
the code base. But with package-local nicknames, you can define a
nickname and use it when the housing package is the value of
*package*. Local nicknames are a
feature of the definition of the housing package. The definition of
the package given a local nickname does not define or even name the
local nickname (except perhaps by chance: a package definition may
specify a nickname for a package which happens to be the same as a
local nickname but in that case, the local nickname is redundant.)
The local nickname can be any name except the name or nickname of the
housing package, any name for the
common-lisp
package (including a nickname like
cl
and
lisp), and any name for
the
keyword package (again including nicknames
although none are defined in Allegro CL initially).
It is important to understand that if a local package nickname is the same
as the name or nickname of another package, it shadows that name for
other package. So if a package has name
:foo and no
nicknames, and
:foo is selected as a local package
nickname for some other package, say the :bar
package, in the housing package
:mypack, then when
:mypack is the current
package,
:foo always points to
package
:bar, so
(find-package
:foo) returns the
:bar package
and
foo::x names the symbol
x in
the
:bar package. See the example below
under Losing print/read consistency.
The following functions have been defined to support local package nicknames:
The existing function package-alternate-name has been modified to
return a local nickname rather than the global alternate name for
packages which have local nicknames in the package that is the current
package. The effect of a non-
nil value for
the variable
*print-alternate-package-name* has also
been changed to work with package local nicknames.
Here are some example using package local nicknames:
;; We define a package without nicknames (in real life, this ;; might be a package from imported software): (defpackage :valuetest (:use :excl :cl)) ;; Here is another package with nickname :v created by another ;; developer on a project: (defpackage :validate (:use :cl :excl) (:nicknames :v)) ;; And here is the package you are working with, :mypack. You specify ;; :v as the local nickname for the :valuetest package and so ;; :v is not the nickname for the :validate package when *package* ;; is the :mypack package: (defpackage :mypack (:use :cl :excl) (:local-nicknames (:v :valuetest))) ;; Here is a transcript of some interactions: ;; :v is the nickname for the :validate package unless the value ;; of *package* is the :valuetest package: cl-user(9): (find-package :v) #<The validate package> ;; When *print-alternate-package-name* is nil, the package name ;; is used by the printer: cl-user(10): (setq *print-alternate-package-name* nil) nil cl-user(11): 'v::x validate::x ;; When *print-alternate-package-name* is non-nil, the first ;; local nickname is used if there is one, otherwise the first ;; actual nickname: cl-user(12): (setq *print-alternate-package-name* t) t cl-user(13): 'v::x v::x cl-user(14): (package-nicknames :v) ("v") cl-user(15): (package-nicknames :validate) ("v") cl-user(16): (package-nicknames :valuetest) nil ;; Now we make *package* be the :mypack package. There :v is ;; the local nickname of the :valuetesy package and that shadows ;; the use of :v as the nickname of the :validate package: cl-user(17): (in-package :mypack) #<The mypack package> mypack(18): (find-package :v) #<The valuetest package> ;; The package-nicknames function only returns actual nickname, not ;; local nicknames: mypack(19): (package-nicknames :valuetest) nil mypack(20): (package-nicknames :validate) ("v") ;; *print-alternate-package-name*, when nil, causes the full package ;; name of the local nickname to be used: mypack(21): (setq *print-alternate-package-name* nil) nil mypack(22): 'v::x valuetest::x mypack(23): (setq *print-alternate-package-name* t) t mypack(24): 'v::x v::x mypack(25):
Package-local nicknames may be the same as the names or nicknames of
other packages. When this happens and the value
of
*package* is
the relevant housing package, and
*print-alternate-package-name* is true, when
the printer prints a package-qualified symbol it may use a nickname
which does not name the package
when
*package* has a different value. We see this
in the examples above.
valuetest::x prints
as
v::x when
*package* is the
:mypack package, but
reading
v::x when
*package* is
:cl-user results in
validate::x.
That is all to be expected. The same thing happens with hierarchical
packages.
:.test refers
to
:pack1.pack2.test
when
*package* is
:pack1 or
:pack1.pack2 but refers
to
opack.test when
*package* is
:opack.
But things get more complicated when either of these hold:
*print-alternate-package-name*is
niland a local package nickname is the same as another package's name.
*print-alternate-package-name*is true and the name and every nickname of another package are all also local package nicknames.
Here are some examples:
cl-user(4): (defpackage :foo (:nicknames :f1)) #<The foo package> cl-user(5): (defpackage :fire) #<The fire package> cl-user(6): (defpackage :bar (:nicknames :b1)) #<The bar package> cl-user(7): (defpackage :baz) #<The baz package> cl-user(8): (defpackage :mypack1 (:use :excl :cl) (:local-nicknames (:foo :fire) (:bar :baz) (:b1 :baz))) #<The mypack1 package> ;; The values of these variable are the symbol X in the package ;; which is part of the variable name. They are all in the CL-USER ;; package. cl-user(11): (defvar *foo-x* 'foo::x) *foo-x* cl-user(12): (defvar *bar-x* 'bar::x) *bar-x* cl-user(13): (defvar *baz-x* 'baz-x) *baz-x* cl-user(14): (defvar *fire-x* 'fire::x) *fire-x* ;; Now we make the current package MYPACK1, which has various ;; local nicknames: cl-user(14): (in-package :mypack1) #<The mypack1 package> ;; FOO is the local nickname of the FIRE package: mypack1(15): (find-package :foo) #<The fire package> ;; Therefore FOO::X and FIRE::X are EQ: mypack1(16): (eq 'foo::x 'fire::x) t ;; When *PRINT-ALTERNATE-PACKAGE-NAME* is NIL, the printer uses the ;; package name regardless of local nicknames: mypack1(17): (setq *print-alternate-package-name* nil) nil ;; So it prints FOO::X for a symbol in the FOO package even though FOO ;; is the nickname of the FIRE package: mypack1(18): user::*foo-x* foo::x mypack1(19): user::*fire-x* fire::x mypack1(20): (eq * **) nil ;; When *PRINT-ALTERNATE-PACKAGE-NAME* is true, the printer uses the ;; local nickname: mypack1(21): (setq *print-alternate-package-name* t) t ;; The local nickname of the BAZ package is BAR, so BAZ::X is printed ;; BAR::X: mypack1(22): user::*baz-x* bar::x ;; The nickname for th BAR package (B1) is shadowed so the printer must ;; use the package name even though it is also shadowed: mypack1(23): user::*bar-x* bar::x mypack1(24): user::*baz-x* bar::x ;; The two symbols print the same but are not the same symbol: mypack1(25): (eq * **) nil
So print/read consistency can be lost even when the value
of
*package*
does not change. This is a consequence of allowing local nicknames to
be the same as package names and (global) package nicknames. Now local
package nicknames are a tool to assist one developer among many to use
convenient local nicknames in code in that developer's own
package. Shadowing names and nicknames of other packages is not the
intention but presumably only happens when the other package is not
relevant for current development.
In addition to the hierarchical packages named in Section 2.9 has permitted using the principal nickname (defined to be
first in the nickname list) instead of the actual name by setting the
value of the variable
*print-nickname* to true. This worked well for
most things but had severe limitations. In particular, the only way to
use the actual package name when
*print-nickname* was to have no nickname. But
sometimes you want nicknames and you want to use the actual name
instead of the nickname (actual names may not also be a nickname).
Allegro CL now supports an alternate name. This must be the package name or one of the nicknames. The laternate name is defined when a package is created with defpackage or make-package.
When
*print-alternate-package-name* is true, the
alternate name will be used. If the alternate name is not specified
and
*print-alternate-package-name*, the principal
nickname is used (that is, the first nickname is the list returned
by package-nicknames). If the package has
no nicknames, the package-name is used.
The alternate package name can be specified by the
new
:alternate-name option to defpackage and keyword argument to
make-package. See
Extensions to cl:make-package,
cl:disassemble, cl:truename, cl:probe-file, cl:open,
cl:apropos and cl:defpackage and cl:in-package, both in
implementation.htm, for more information on
extensions to defpackage and make-package.
The alternate name can be accessed by the package-alternate-name function. If no alternate name is specified, the altername name is the first in the list of nicknames or the package name if there are no nicknames. The alternate, if explicitly specified, must be either the package name or one of the nicknames.
Allegro CL allows you to specify whether you want the alternate
package name or the package name as the qualifier. The following
variable
*print-alternate-package-name* controls which
is used. Note that certain utilities (e.g. apropos and the debugger) bind this variable to
true and so always use the alternate name.
The principal nickname of some of the packages of interest to users
are listed next (
nil means no defined
nicknames). The alternate name is in bold.-2022, Franz Inc. Lafayette, CA., USA. All rights reserved.
This page was not revised from the 10.0 page.
Created 2019.8.20.
|
https://franz.com/support/documentation/10.1/doc/packages.htm
|
CC-MAIN-2022-33
|
refinedweb
| 4,868
| 56.25
|
0
Hi,
Sorry for my ignorance but the problem I have is probably so simple that I cannot seem to find an answer for it.
I am just learning about the Java.Util Package but in following my course module I am getting an error.
here is the simple code :
import java.util.*; public class Main { public static void main(String[] args) { Calendar c = new Calendar.[U]getInstance();[/U] System.out.println(c.getTime()); System.out.println(c.getClass()); } }
now here is the error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code at javautilpack2.Main.main(Main.java:19) Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)
the get.Instance is underlined (red) (netbeans)
My reckoning is that for some reason the Calendar class cannot be found? or the method?
Sorry people normally I would be able to find the problem if it was just the code but unfortunately I have not come accross this kind of error in my course yet.
|
https://www.daniweb.com/programming/software-development/threads/342030/simple-problem
|
CC-MAIN-2016-50
|
refinedweb
| 165
| 58.28
|
How do i get my program to keep going until the end is reach of a number? For example 22/7 = pie. How do i get the program to keep giving numbers after pie instead of stoping after 9 or 10 decimal get my program to keep going until the end is reach of a number? For example 22/7 = pie. How do i get the program to keep giving numbers after pie instead of stoping after 9 or 10 decimal places?
Look at using the BigDecimal class.
This is what i have so far:
Problem is when i run it i get this error:
I thought ROUND_CEILING was supposed to get rid of needing to round?I thought ROUND_CEILING was supposed to get rid of needing to round?Exception in thread "main" java.lang.ArithmeticException: Rounding necessary at java.math.BigDecimal.divideAndRound(BigDecimal.java:1452) at java.math.BigDecimal.setScale(BigDecimal.java:2406) at java.math.BigDecimal.setScale(BigDecimal.java:2449) at pie.Pie.main(Pie.java:27) Java Result: 1
Can you post a small complete program that compiles, executes and shows the error?
import java.lang.Math; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.*; /** * * */ public class Pie { /** * @param args the command line arguments */ public static void main(String[] args) { double num = 22; double num2 = 7; double total = num/num2; BigDecimal big = new BigDecimal(total); System.out.println((big.setScale(BigDecimal.ROUND_CEILING))); // TODO code application logic here } }
thats what i have that is giving the error
What do you expect that to do?What do you expect that to do?big.setScale(BigDecimal.ROUND_CEILING)
Have you set the rounding first?Have you set the rounding first?ArithmeticException: Rounding necessary
I dont want it to round. I want the pie to continue forever until i shut down the program.
I thought big.setscale(BigDecimal.ROUND_CIELING) would continue to count after the decimals with no set length.
Print out the value of BigDecimal.ROUND_CEILING to see its value.
What happens when you leave the call to setScale() out?
the output = 2
Then the code was executing: setScale(2)
Try calling setScale(9999) and see what happens.
It enters a lot of 0's. It does not continue answering the equation tho. Why is that?
I don't know why the program stops executing.I don't know why the program stops executing.It does not continue
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/27446-no-ending-after-decimal-point.html
|
CC-MAIN-2015-48
|
refinedweb
| 400
| 61.93
|
import
Use import in a sentence
“ I told the man that it was not an export, but an import and was not the same thing at all. ”
Was this Helpful? YES NO 2 people found this helpful.
“ You may want to try and import some resources you need if you can get a better price that way. ”
Was this Helpful? YES NO 4 people found this helpful.
“ The import occurred last month as we wanted to have all of our inputs sourced from abroad to be received ahead of time. ”
Was this Helpful? YES NO 9 people found this helpful.
Show more usage examples...
|
http://www.investorwords.com/2383/import.html
|
CC-MAIN-2019-39
|
refinedweb
| 104
| 94.76
|
An Introduction to Java.util.Hashtable Class
Last modified: December 31, 2019
1. Overview
Hashtable is the oldest implementation of a hash table data structure in Java. The HashMap is the second implementation, which was introduced in JDK 1.2.
Both classes provide similar functionality, but there are also small differences, which we'll explore in this tutorial.
2. When to Use Hashtable
Let's say we have a dictionary, where each word has its definition. Also, we need to get, insert and remove words from the dictionary quickly.
Hence, Hashtable (or HashMap) makes sense. Words will be the keys in the Hashtable, as they are supposed to be unique. Definitions, on the other hand, will be the values.
3. Example of Use
Let's continue with the dictionary example. We'll model Word as a key:
public class Word { private String name; public Word(String name) { this.name = name; } // ... }
Let's say the values are Strings. Now we can create a Hashtable:
Hashtable<Word, String> table = new Hashtable<>();
First, let's add an entry:
Word word = new Word("cat"); table.put(word, "an animal");
Also, to get an entry:
String definition = table.get(word);
Finally, let's remove an entry:
definition = table.remove(word);
There are many more methods in the class, and we'll describe some of them later.
But first, let's talk about some requirements for the key object.
4. The Importance of hashCode()
To be used as a key in a Hashtable, the object mustn't violate the hashCode() contract. In short, equal objects must return the same code. To understand why let's look at how the hash table is organized.
Hashtable uses an array. Each position in the array is a “bucket” which can be either null or contain one or more key-value pairs. The index of each pair is calculated.
But why not to store elements sequentially, adding new elements to the end of the array?
The point is that finding an element by index is much quicker than iterating through the elements with the comparison sequentially. Hence, we need a function that maps keys to indexes.
4.1. Direct Address Table
The simplest example of such mapping is the direct-address table. Here keys are used as indexes:
index(k)=k, where k is a key
Keys are unique, that is each bucket contains one key-value pair. This technique works well for integer keys when the possible range of them is reasonably small.
But we have two problems here:
- First, our keys are not integers, but Word objects
- Second, if they were integers, nobody would guarantee they were small. Imagine that the keys are 1, 2 and 1000000. We'll have a big array of size 1000000 with only three elements, and the rest will be a wasted space
hashCode() method solves the first problem.
The logic for data manipulation in the Hashtable solves the second problem.
Let's discuss this in depth.
4.2. hashCode() Method
Any Java object inherits the hashCode() method which returns an int value. This value is calculated from the internal memory address of the object. By default hashCode() returns distinct integers for distinct objects.
Thus any key object can be converted to an integer using hashCode(). But this integer may be big.
4.3. Reducing the Range
get(), put() and remove() methods contain the code which solves the second problem – reducing the range of possible integers.
The formula calculates an index for the key:
int index = (hash & 0x7FFFFFFF) % tab.length;
Where tab.length is the array size, and hash is a number returned by the key's hashCode() method.
As we can see index is a reminder of the division hash by the array size. Note that equal hash codes produce the same index.
4.4. Collisions
Furthermore, even different hash codes can produce the same index. We refer to this as a collision. To resolve collisions Hashtable stores a LinkedList of key-value pairs.
Such data structure is called a hash table with chaining.
4.5. Load Factor
It is easy to guess that collisions slow down operations with elements. To get an entry it is not enough to know its index, but we need to go through the list and perform a comparison with each item.
Therefore it's important to reduce the number of collisions. The bigger is an array, the smaller is the chance of a collision. The load factor determines the balance between the array size and the performance. By default, it's 0.75 which means that the array size doubles when 75% of the buckets become not empty. This operation is executed by rehash() method.
But let's return to the keys.
4.6. Overriding equals() and hashCode()
When we put an entry into a Hashtable and get it out of it, we expect that the value can be obtained not only with same the instance of the key but also with an equal key:
Word word = new Word("cat"); table.put(word, "an animal"); String extracted = table.get(new Word("cat"));
To set the rules of equality, we override the key’s equals() method:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Word)) return false; Word word = (Word) o; return word.getName().equals(this.name); }
But if we don’t override hashCode() when overriding equals() then two equal keys may end up in the different buckets because Hashtable calculates the key’s index using its hash code.
Let’s take a close look at the above example. What happens if we don’t override hashCode()?
- Two instances of Word are involved here – the first is for putting the entry and the second is for getting the entry. Although these instances are equal, their hashCode() method return different numbers
- The index for each key is calculated by the formula from section 4.3. According to this formula, different hash codes may produce different indexes
- This means that we put the entry into one bucket and then try to get it out from the other bucket. Such logic breaks Hashtable
Equal keys must return equal hash codes, that’s why we override the hashCode() method:
public int hashCode() { return name.hashCode(); }
Note that it's also recommended to make not equal keys return different hash codes, otherwise they end up in the same bucket. This will hit the performance, hence, losing some of the advantages of a Hashtable.
Also, note that we don’t care about the keys of String, Integer, Long or another wrapper type. Both equal() and hashCode() methods are already overridden in wrapper classes.
5. Iterating Hashtables
There are a few ways to iterate Hashtables. In this section well talk about them and explain some of the implications.
5.1. Fail Fast: Iteration
Fail-fast iteration means that if a Hashtable is modified after its Iterator is created, then the ConcurrentModificationException will be thrown. Let's demonstrate this.
First, we'll create a Hashtable and add entries to it:
Hashtable<Word, String> table = new Hashtable<Word, String>(); table.put(new Word("cat"), "an animal"); table.put(new Word("dog"), "another animal");
Second, we'll create an Iterator:
Iterator<Word> it = table.keySet().iterator();
And third, we'll modify the table:
table.remove(new Word("dog"));
Now if we try to iterate through the table, we'll get a ConcurrentModificationException:
while (it.hasNext()) { Word key = it.next(); }
java.util.ConcurrentModificationException at java.util.Hashtable$Enumerator.next(Hashtable.java:1378)
ConcurrentModificationException helps to find bugs and thus avoid unpredictable behavior, when, for example, one thread is iterating through the table, and another one is trying to modify it at the same time.
5.2. Not Fail Fast: Enumeration
Enumeration in a Hashtable is not fail-fast. Let's look at an example.
First, let's create a Hashtable and add entries to it:
Hashtable<Word, String> table = new Hashtable<Word, String>(); table.put(new Word("1"), "one"); table.put(new Word("2"), "two");
Second, let's create an Enumeration:
Enumeration<Word> enumKey = table.keys();
Third, let's modify the table:
table.remove(new Word("1"));
Now if we iterate through the table it won't throw an exception:
while (enumKey.hasMoreElements()) { Word key = enumKey.nextElement(); }
5.3. Unpredictable Iteration Order
Also, note that iteration order in a Hashtable is unpredictable and does not match the order in which the entries were added.
This is understandable as it calculates each index using the key's hash code. Moreover, rehashing takes place from time to time, rearranging the order of the data structure.
Hence, let's add some entries and check the output:
Hashtable<Word, String> table = new Hashtable<Word, String>(); table.put(new Word("1"), "one"); table.put(new Word("2"), "two"); // ... table.put(new Word("8"), "eight"); Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Word, String> entry = it.next(); // ... } }
five four three two one eight seven
6. Hashtable vs. HashMap
Hashtable and HashMap provide very similar functionality.
Both of them provide:
- Fail-fast iteration
- Unpredictable iteration order
But there are some differences too:
- HashMap doesn't provide any Enumeration, while Hashtable provides not fail-fast Enumeration
- Hashtable doesn't allow null keys and null values, while HashMap do allow one null key and any number of null values
- Hashtable‘s methods are synchronized while HashMaps‘s methods are not
7. Hashtable API in Java 8
Java 8 has introduced new methods which help make our code cleaner. In particular, we can get rid of some if blocks. Let's demonstrate this.
7.1. getOrDefault()
Let's say we need to get the definition of the word “dog” and assign it to the variable if it is on the table. Otherwise, assign “not found” to the variable.
Before Java 8:
Word key = new Word("dog"); String definition; if (table.containsKey(key)) { definition = table.get(key); } else { definition = "not found"; }
After Java 8:
definition = table.getOrDefault(key, "not found");
7.2. putIfAbsent()
Let's say we need to put a word “cat“ only if it's not in the dictionary yet.
Before Java 8:
if (!table.containsKey(new Word("cat"))) { table.put(new Word("cat"), definition); }
After Java 8:
table.putIfAbsent(new Word("cat"), definition);
7.3. boolean remove()
Let's say we need to remove the word “cat” but only if it's definition is “an animal”.
Before Java 8:
if (table.get(new Word("cat")).equals("an animal")) { table.remove(new Word("cat")); }
After Java 8:
boolean result = table.remove(new Word("cat"), "an animal");
Finally, while old remove() method returns the value, the new method returns boolean.
7.4. replace()
Let's say we need to replace a definition of “cat”, but only if its old definition is “a small domesticated carnivorous mammal”.
Before Java 8:
if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) { table.put(new Word("cat"), definition); }
After Java 8:
table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition);
7.5. computeIfAbsent()
This method is similar to putIfabsent(). But putIfabsent() takes the value directly, and computeIfAbsent() takes a mapping function. It calculates the value only after it checks the key, and this is more efficient, especially if the value is difficult to obtain.
table.computeIfAbsent(new Word("cat"), key -> "an animal");
Hence, the above line is equivalent to:
if (!table.containsKey(cat)) { String definition = "an animal"; // note that calculations take place inside if block table.put(new Word("cat"), definition); }
7.6. computeIfPresent()
This method is similar to the replace() method. But, again, replace() takes the value directly, and computeIfPresent() takes a mapping function. It calculates the value inside of the if block, that's why it's more efficient.
Let's say we need to change the definition:
table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value);
Hence, the above line is equivalent to:
if (table.containsKey(cat)) { String concatination=cat.getName() + " - " + table.get(cat); table.put(cat, concatination); }
7.7. compute()
Now we'll solve another task. Let's say we have an array of String, where the elements are not unique. Also, let's calculate how many occurrences of a String we can get in the array. Here is the array:
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
Also, we want to create a Hashtable which contains an animal as a key and the number of its occurrences as a value.
Here is a solution:
Hashtable<String, Integer> table = new Hashtable<String, Integer>(); for (String animal : animals) { table.compute(animal, (key, value) -> (value == null ? 1 : value + 1)); }
Finally, let's make sure, that the table contains two cats, two dogs, one bird and two mouses:
assertThat(table.values(), hasItems(2, 2, 2, 1));
7.8. merge()
There is another way to solve the above task:
for (String animal : animals) { table.merge(animal, 1, (oldValue, value) -> (oldValue + value)); }
The second argument, 1, is the value which is mapped to the key if the key is not yet on the table. If the key is already in the table, then we calculate it as oldValue+1.
7.9. foreach()
This is a new way to iterate through the entries. Let's print all the entries:
table.forEach((k, v) -> System.out.println(k.getName() + " - " + v)
7.10. replaceAll()
Additionally, we can replace all the values without iteration:
table.replaceAll((k, v) -> k.getName() + " - " + v);
8. Conclusion
In this article, we've described the purpose of the hash table structure and showed how to complicate a direct-address table structure to get it.
Additionally, we've covered what collisions are and what a load factor is in a Hashtable. Also, we've learned why to override equals() and hashCode() for key objects.
Finally, we've talked about Hashtable‘s properties and Java 8 specific API.
As usual, the complete source code is available on Github.
|
https://www.baeldung.com/java-hash-table
|
CC-MAIN-2020-50
|
refinedweb
| 2,317
| 59.09
|
REST¶
Introduction¶
In this section we’ll look at how you could go about implementing a RESTful web service with Morepath.
REST stands for Representational State Transfer, and is a particular way to design web services. We won’t try to explain here why this can be a good thing for you to do, just explain what is involved.
REST is not only useful for pure web services, but is also highly relevant for web application development, especially when you are building a single-page rich client application in JavaScript in the web browser. It can be beneficial to organize the server-side application as a RESTful web service.
Elements of REST¶
That’s all rather abstract. Let’s get more concrete. It’s useful to refer to the Richardson Maturity Model for REST in this context. In REST we do the following:
- We uses HTTP as a transport system. What you use to communicate is typically JSON or XML, but it could be anything.
- We don’t just use HTTP to tunnel method calls to a single URL. Instead, we model our web service as resources, each with their own URL, that we can interact with.
- We use HTTP methods meaningfully. Most importantly we use
GETto retrieve information, and
POSTwhen we want to change information. Along with this we also use HTTP response status codes meaningfully.
- We have links between the resources. So, one resource points to another. A container resource could point to a link that you can
POSTto create a new sub resource in it, for instance, and may have a list of links to the resources in the container. See also HATEOAS.
Morepath has features that help you create RESTful applications.
HTTP as a transport system¶
We don’t really need to say much here, as Morepath is of course all
about HTTP in the end. Morepath lets you write a bare-bones view using
morepath.App.view(). This also lets you pass in a
render
function that lets you specify how to render the return value of the
view function as a
morepath.Response. If you use JSON, for
convenience you can use
morepath.App.json() has a JSON
render function baked in.
We could for instance have a
Document model in our application:
class Document(object): def __init__(self, title, author, content): self.title = title self.author = author self.content = content
We can expose it on a URL:
@App.path(model=Document, path='documents/{id}') def get_document(id=0): return document_by_id(id)
We assume here that a
document_by_id() function exists that
returns a
Document instance by integer id from some database, or
None if the document cannot be found. Any way to get your model
instance is fine. We use
id=0 to tell Morepath that ids should be
converted to integers, and to with a
BadRequest if that is not
possible.
Now we need a view that exposes the resource to JSON:
@App.json(model=Document) def document_default(self, request): return { 'type': 'document', 'id': self.id, 'title': self.title, 'author': self.author, 'content': self.content }
Modeling as resources¶
Modeling a web service as multiple resources comes pretty naturally to
Morepath. You think carefully about how to place models in the URL
space and then expose them using
morepath.App.path(). Each model
class can only be exposed on a single URL (per app), which gives them
a canonical URL automatically.
A collection resource could be modelled like this:
class DocumentCollection(object): def __init__(self): self.documents = [] self.id_counter = 0 def add(self, doc): doc.id = self.id_counter self.id_counter += 1 self.documents.append(doc) return doc
We now want to expose this collection to a URL path
/documents. We
want:
- when you
GET
/documentswe want to get the ids documents in the collection.
- when you
POSTto
/documentswith a JSON body we want to add it to the collection.
Here is how we can make
documents available on a URL:
documents = DocumentCollection() @App.path(model=DocumentCollection, path='documents') def get_document_collection(): return documents
When someone accesses
/documents they should get a JSON structure
which includes ids of all documents in the collection. Here’s how to
do that (for
GET, the default):
@App.json(model=DocumentCollection) def document_collection_default(self, request): return { 'type': 'document_collection', 'ids': [doc.id for doc in self.documents] }
We also want to allow people to
POST new documents (as a JSON POST
body):
@App.json(model=DocumentCollection, request_method='POST') def document_collection_post(self, request): json = request.json result = self.add(Document(title=json['title'], author=json['author'], content=json['content'])) return request.view(result)
We use
Request.view() to return the JSON structure for the added
document again. This is handy as it includes the
id field.
HTTP response status codes¶
When a view function returns normally, Morepath automatically sets the
response HTTP status code to
200 Ok.
When you try to access a URL that cannot be routed to a model because
no path exists, or because the function involved returns
None, or
because the view cannot be found, a
404 Not Found error is raised.
If you access a URL that does exist but with a request method that is
not supported, a
405 Method Not Allowed error is raised.
What if the user sends the wrong information to a view? Let’s consider
the
POST view again:
@App.json(model=DocumentCollection, request_method='POST') def document_collection_post(self, request): json = request.json result = self.add(Document(title=json['title'], author=json['author'], content=json['content'])) return request.view(result)
What if the structure of the JSON submitted is not a valid document
but contains some other information, or misses essential information?
We should reject it if so. We can do this by raising a HTTP error
ourselves. WebOb, the request/response library upon which Morepath is
built, defines a set of HTTP exception classes
webob.exc that
we can use:
@App.json(model=DocumentCollection, request_method='POST') def document_collection_post(self, request): json = request.json if not is_valid_document_json(json): raise webob.exc.HTTPUnprocessableEntity() result = self.add(Document(title=json['title'], author=json['author'], content=json['content'])) return request.view(result)
Now we raise
422 Unprocessable Entity when the submitted JSON body
is invalid, using a function
is_valid_document_json that does the
checking.
is_valid_document could look this:
def is_valid_document_json(json): if json['type'] != 'document': return False for name in ['title', 'author', 'content']: if name not in json: return False return True
load¶
The code that checks the validity of the POST or PUT body in the view
can be moved out into a
load function that you can use in multiple
views:
def load(request): if not is_valid_document_json(json): raise webob.exc.HTTPUnprocessableEntity() return request.json @App.json(model=DocumentCollection, request_method='POST', load=load) def document_collection_post(self, request, json): result = self.add(Document(title=json['title'], author=json['author'], content=json['content'])) return request.view(result)
The return value of the
load function is passed in as a third argument into
the view function. This means that you can also do conversion of input in the
load function and reuse it between views. And if the load fails to work you
get a 422 status code.
Linking: HATEOAS¶
We’ve now reached the point where many would say that this is a RESTful web service. But in fact a vital ingredient is still missing: hyperlinks. That ugly acronym HATEOAS thing.
Morepath makes it easy to create hyperlinks, so we won’t have to do much. Before we had this for the collection view:
@App.json(model=DocumentCollection) def document_collection_default(self, request): return { 'type': 'document_collection', 'ids': [doc.id for doc in self.documents] }
We can change this so instead of ids, we return a list of document URLs instead:
@App.json(model=DocumentCollection) def document_collection_default(self, request): return { 'type': 'document_collection', 'documents': [request.link(doc) for doc in self.documents], }
Now we’ve got HATEOAS: the collection links to the documents it contains. The developers looking at the responses your web service sends get a few clues about where to go next. Coupling is looser.
We have HATEOAS, so at last we got true REST. Why is hyperlinking so often ignored? Why don’t more systems implement HATEOAS? Perhaps because they make linking to things too hard or too brittle. Morepath instead makes it easy. Link away!
|
https://morepath.readthedocs.io/en/stable/rest.html
|
CC-MAIN-2018-51
|
refinedweb
| 1,379
| 50.84
|
Products > Computers
Devuan 4.0 Released As Debian 11 Without Systemd
<< < (13/13)
ve7xen:
--- Quote from: Nominal Animal on October 26, 2021, 12:57:16 am ---Then prove your counterclaims, and stop making this personal. Declaring something a 'falsehood' has zero value, if you provide zero verifiable facts, only your own opinions.
--- End quote ---
I refuted most of them in my second-last post, and you responded to only one of them. I am not making this personal, I am presenting the facts as I am aware of them, and expect you to either counter my refutations, or by not responding, admit that you are have no response and were wrong.
--- Quote ---I claim that that kind of pressure is the main reason for friction between systemd developers and 'competing' projects, and causes technically inferior solutions to be accepted simply to avoid the social repercussions a rejection would cause.)
--- End quote ---
Okay, I have said, I don't care about the politics, and don't care to learn the history. However engineers tend to be strongheaded people. There are more than a few democratic technical selection committees that have chosen this path, and I think your assertion that the same inferior solution has become accepted among so many separate communities of such people is dubious at best. The corollary of course is that these people must be either incompetent or malicious, and you have repeatedly alluded to that being your point here.
--- Quote ---By "subsumption", I refer to how systemd has a special status in the project, and how Lennart Poettering was granted maintainer status in the dbus source repository.
dbus is the software package based on this in Debian and RHEL derivatives, and has a direct dependency on systemd (specifically, a build dependency on libsystemd-dev), and cannot be built or used in Debian or RHEL without systemd.
--- End quote ---
It is rather common for maintainers of ports to be granted maintainer status. The systemd functionality is there for effective use on systemd systems. There is also Windows-specific code in dbus, so that it can be built and used effectively there. Do you object to that? How about the optional X11 code? dbus does not require systemd as a build dependency, though it can integrate with it on systems where it is present, such as Debian and RHEL, and when built as such, it will obviously be a runtime dependency. You can easily see in the Gentoo ebuild for example that it can be built without systemd and works just fine that way.
This should be pretty obvious because lots of *nix-y stuff, especially for the desktop, uses dbus, yet works just fine on *BSD or even Windows where systemd is obviously absent. Your claim that systemd has 'subsumed' dbus is just categorically incorrect; at best the two are loosely coupled.
--- Quote ---Devuan uses a fork of the freedesktop Git repo, so that any changes can be backported while removing any added systemd dependencies. The reason for the Devuan fork from Debian is clearly stated in the announcement, and is centered on two things: the behaviour of the systemd developers, and the design and central/monolithic role of systemd in a Linux system. The first one is subjective; but the latter is contrary to the Unix philosophy and modular design, both found reliable and useful for several decades now. Even more importantly, the more I view systemd sources or get notified of its issues, the more I am convinced that its developers do not have the necessary skill to even implement their own design without critical security issues and creating new single-point failure modes.
--- End quote ---
Great, the more ports the merrier. If it has technical merit, it will succeed and displace Debian and other distributions that have been taken over by these malicious and incompetent actors. I'm all for that, this is what open source is all about. But don't promote it with false claims and drama.
--- Quote ---However, true dependency-based service management does require source-level changes.
The reason I showed the API needed for true dependency-based init and service management, was to show how minimal the source-level changes are.
--- End quote ---
A way to advertise more granular service availability would be nice, but I don't think it displaces the need for a meta-description of the dependencies (in other words, decoupling the application and the system setup). I would like to see the advertisements side of this, but consumed by systemd or similar as part of the dependency graph. It would be pretty straightforward to implement on top of dbus, and I'm kind of surprised it doesn't exist. Nothing stopping someone from working on this, of course.
As I described, if you want the dependencies described within the application, that means that we need some kind of central authority to enumerate how particular 'abstract' dependencies are to be described in this system (e.g. how does 'the X11 server is ready' get described in a system-agnostic way, allowing for different implementations of X11, different locations of its unix or network sockets etc). This creates a lot of management overhead and friction, and seems needlessly...bureaucratic and centralized. I think it is a lot less flexible if all your dependency nodes ultimately trace back to some central management authority.
Or you do it in an ad-hoc way that would be very fragile, tightly coupled between applications, and not very portable. As nctnico outlined, this depdendency resolution really needs to be managed by the packagers / system administrators, it's not practical to push it into the hands of the application developers that should not need to know much or care about the configuration of the system they are running on and creates a bunch of new problems and makes this opaque and rigid to the user.
There are a lot of other technical tradeoffs here too. You end up with a ton of long-lived processes that sit with their code in RAM indefinitely. It makes dependency loops and race conditions impossible to catch without a supervisor that is aware of the entire dependency state of the system - and then we are back where we...well...are. It puts the dependencies and services opaquely behind the binary, and not in an easily administrator-viewable fashion. Current state is difficult to interrogate without a supervisor. It leads to a lot of boilerplate code in applications. It doesn't help at all with managing things like network/mount namespaces, capabilities, permissions and the like. It's certainly a viable approach as part of a larger system, but to claim that it is *the* approach is arrogant as all get out. There are good reasons that this has not been widely adopted as the primary way of solving these problems, despite it being an old idea.
--- Quote ---The changes made to various core services due to systemd are much more extensive, and make those services dependent on systemd: to use that same source in a system without systemd, you need to do changes. At best, those are just build configuration, but often require patching. udev, the device manager used in Linux is an excellent example of this. It was initially designed by Greg KH and Kay Sievers as part of the kernel, but was later subsumed/incorporated into systemd. udev is an excellent design, but because of its subsumption to systemd, users who don't want to use systemd have to use something else; typically eudev (which is to udev what Devuan is to Debian: tries to keep up with the good stuff, but drop the systemd dependency).
--- End quote ---
It's the *only* example of this, and I'm not happy about it either, but it is not really a technical problem. There's no reason for packaging it with systemd, but it can still be built and used without systemd on the system, as far as I know, and Gentoo offers this and no patches are required to do it. But yeah, this is not very cool.
--- Quote ---So, in the case of dbus and udev –– in my opinion, very important core services! ––, the choice is currently whether you use them with systemd, or with anything else except systemd (like OpenRC, runit, SysV, or something else).
--- End quote ---
If someone wanted to maintain it, it would not be difficult to provide alternate builds of dbus and udev (and likely some others) that do not have a runtime dependency on systemd, for use on such systems. The issue here is that nobody wants to maintain an alternate init on these distributions, not that it would be difficult to implement or that systemd is blocking it. On a dynamically built system like Gentoo it is more or less trivial, and lo and behold, it's a 'supported' (as it goes on Gentoo) option there.
--- Quote ---The API approach I described does not make that distinction at all. The reason for incorporating it into POSIX would be the same why the GNU getline()/getdelim() got incorporated into POSIX: because it is something that is needed and useful in systems programming.
In the cases where you'd run a daemon that relies on that API on a system without dependency support, the API calls would do-nothing, and the service would still work as it would under SysV init or systemd.
--- End quote ---
I think you're missing the big picture here. Yes, implementing the advertising of services this way would not be difficult or a big change, but for it to actually be useful for system management, there would be a ton of infrastructure that would need to be built up around it *and actively managed* which is not really something that POSIX does, it gets updated what every 10 years or so? I'm not opposed to adding something like this to what we have today in a holistic manner, used where it makes sense for things like 'network is up' or 'X server is running', but we already have all the pieces in place. All that is needed is a standardized dbus interface to pass these messages.
--- Quote ---The competition alone between software projects will drive "evolution". The history of free/open source computing is replete with examples.
--- End quote ---
Agreed, we will see what happens here.
--- Quote from: ve7xen on October 25, 2021, 08:27:12 pm ---The 'abject dismissal' is 'that has been tried, and does not work well/reliably enough'. Your counterclaim is "but it does for me, so you're wrong", and makes no sense.
--- End quote ---
In your view your solution is perfect, and the solution that the vast majority of people have settled on (it is not just me that it works for, clearly) is suitable to be dismissed without due consideration. You will need a much stronger argument than 'I don't like it' or 'I don't like how it is managed' or even 'it is limited in this way' to dismiss it as you have. And part of that will include addressing the shortcomings of your own proposals and how the tradeoff favours your solution. You have not acknowledged that your solution is limited in any way.
--- Quote ---The difference you seem to insist on, to me, looks semantical. What matters, is the practical relationship.
--- End quote ---
Precisely, and practically speaking, dbus is completely independent from systemd. It can build and work fine on any *nix, as well as Windows, whether or not systemd is present. It is a clear refutation of your claim that it has been 'subsumed' by systemd. Yes, it has systemd-specific code, as it does for Windows, or as glibc does for FreeBSD.
--- Quote ---Have you considered whether you understand their relationship? Or have you just assumed that because they use separate git trees, and don't share too many maintainers and members, is proof enough that my characterization must be incorrect?
--- End quote ---
Your claim can be dismissed on its face, because there is ample evidence of dbus-daemon working as designed on systems without systemd. Ergo, it must not depend on systemd.
--- Quote ---No, that is just a side effect of my peculiar deficiencies in writing English. I only do technical English, and nowadays neither speak nor listen to it socially, so any such subtext anyone assigns to my output is incorrect: there should be none (except for self-deprecating dad jokes when emoticons are used), and the text interpreted with as little emotional content as possible. Any observable subtext otherwise is an error on my part, but I assure you, it is NOT INTENTIONAL. If you care to, you can find posts on this forum where I discuss exactly this problem a year or two ago.
The only fraction of system administrators and distribution developers that 'I think I know better', is the fraction that says "but it works for me, so you're wrong". And the reason there is that they don't seem to know anything to back their opinions, just personal beliefs.
--- End quote ---
No, this is not a language deficiency. It follows directly from your assertions that systemd is not appropriate and that better solutions should be chosen, and that distributions should not have allowed systemd to become integral to their systems. By making those claims, you are calling the decisions of the vast majority of distribution maintainers and system administrators that actively chose to use or implement systemd in their systems into question. Sure, you are only directly deriding the systemd team, as far as I can tell, but you are also insisting that their approach is incorrect and that anyone supporting it is also incorrect in choosing it.
--- Quote ---You have provided nothing but your own opinion, no reason to consider your opinions valid or even relevant.
--- End quote ---
We are starting to get to a point where you are admitting that the technical assertions you have made are mostly untrue. I have described how what much of you are saying about systemd's architecture is untrue or at least misrepresented. I have described limitations of your proposed approach, and problems it creates. Your posts however have been full of opinion, accusation, and descriptions of 'your way' but little (and many factual inaccuracies) to back up your opinion.
--- Quote ---I've described to you that I've observed that when installing updates to systemd or dbus, the update manager requests a system reboot, and if one declines, sometimes the desktop session (gnome or cinnamon on the machines I've looked at) crashes: first you see glitches, then it becomes unresponsive, and either just spins or crashes. Because of the dependencies of these system components, logging out and logging back in is not sufficient to avoid the effect; a reboot is needed.
To me, this indicates a clear relationship between the three components: the desktop environment (various services running as the user, connected using dbus), dbus itself, and systemd. In my experience, this is a serious step backwards in the system reliability, and something I would like to correct or avoid.
On Debian derivatives, kpatch can still be used to patch kernels, but why bother if you have to reboot your desktop/laptop every week or so anyway.
--- End quote ---
And you didn't read my response, where I described why this dependency exists, and how to address it, but you ignored that. You should not have to reboot after a systemd or dbus update, but you will have to restart many processes, as you would when updating any other system-level package like libc. If the package manager is prompting a reboot, it is a limitation of the package manager (or a choice by its maintainers to err on the side of caution), and has nothing to do with systemd. In most cases this requirement is based on dbus anyway (almost all of a typical desktop userland does not depend on systemd directly), and as we have already discussed, dbus != systemd and you will run into the exact same thing on a non-systemd system.
madires:
I think the big issue with systemd is that it's the opposite of the UNIX philosophy and users are afraid that it will take their freedom away. And it does that already to some extend.
Navigation
[0] Message Index
[*] Previous page
|
https://www.eevblog.com/forum/general-computing/devuan-4-0-released-as-debian-11-without-systemd/60/?wap2;PHPSESSID=07vkm5q7ml95j594idlvbfcsp1
|
CC-MAIN-2022-05
|
refinedweb
| 2,734
| 57
|
Let's consider something relatively simple. Let's say we're working on some fancy calculations. Our users explain until they're blue in the face. We take careful notes. We think we understand. To confirm, we ask for a simple spreadsheet with inputs and outputs.
We get something like the following. The latitudes and longitudes are inputs. The ranges and bearings are outputs. [The math can be seen at "Calculate distance, bearing and more between Latitude/Longitude points".]
Only it has a a few more rows with different examples. Equator Crossing. Prime Meridian Crossing. All the usual suspects.
TDD Means Making Test Cases
Step one, then, is to parse the spreadsheet full of examples and create some domain-specific examples. Since it's far, far easier to work with .CSV files, we'll presume that we can save the carefully-crafted spreadsheet as a simple .CSV with the columns shown above.
Step two will be to create working Python code from the domain-specific examples.
The creation of test cases is a matter of building some intermediate representation out of the spreadsheet. This is where plenty of parsing and obscure special-case data handling may be necessary.
from __future__ import division
import csv
from collections import namedtuple
import re
latlon_pat= re.compile("(\d+)\s+(\d+)\s+(\d+)([NSWE])")
def latlon( txt ):
match= latlon_pat.match( txt )
d, m, s, h = match.groups()
return float(d)+float(m)/60+float(s)/3600, h
angle_pat= re.compile("(\d+)\s+(\d+)\s+(\d+)")
def angle( txt ):
match= angle_pat.match( txt )
d, m, s = match.groups()
return float(d)+float(m)/60+float(s)/3600
range_pat= re.compile("(\d+)\s*(\D+)")
def range( txt ):
match= range_pat.match( txt )
d, units = match.groups()
return float(d), units
RangeBearing= namedtuple("RangeBearing","lat1,lon1,lat2,lon2,rng,brg")
def test_iter( filename="sample_data.csv" ):
with open(filename,"r") as source:
rdr= csv.DictReader( source )
for row in rdr:
print row
tc= RangeBearing(
latlon(row['Latitude 1']), latlon(row['Longitude 1']),
latlon(row['Latitude 2']), latlon(row['Longitude 2']),
range(row['range']),
angle(row['bearing'])
)
yield tc
for tc in test_iter():
print tc
This is long, but, it handles a lot of the formatting vagaries that users are prone to.
From Abstract to TestCase
Once we have a generator to build test cases as abstraction examples, generating code for Java or Python or anything else is just a little template-fu.
from string import Template
testcase= Template("""
class Test_${name}( unittest.TestCase ):
def setUp( self ):
self.p1= LatLon( lat=GlobeAngle(*$lat1), lon=GlobeAngle(*$lon1) )
self.p2= LatLon( lat=GlobeAngle(*$lat2), lon=GlobeAngle(*$lon2) )
def test_should_compute( self ):
d, brg = range_bearing( p1, p2, R=$units )
self.assertEquals( $dist, int(d) )
self.assertEquals( $brg, map(int,map(round,brg.deg)))
""")
for name, tc in enumerate( test_iter() ):
units= tc.rng[1].upper()
dist= tc.rng[0]
code= testcase.substitute( name=name, dist=dist, units=units, **tc._asdict() )
print code
This shows a simple template with values filled in. Often, we have to generate a hair more than this. A few imports, a "unittest.main()" is usually sufficient to transform a spreadsheet into unit tests that we can confidently use for test-driven development.
|
https://slott-softwarearchitect.blogspot.com/2011/02/
|
CC-MAIN-2021-39
|
refinedweb
| 530
| 53.88
|
We:
- Uninstall Netscape 8
- START->RUN
- Type: regedit
- Hit ENTER
- Navigate to the following:
- HKEY_LOCAL_MACHINESOFTWAREMicrosoftInternet ExplorerPluginsExtension
- Highlight and right-click the node titled “xml” and select delete.
- Restart Internet Explorer
I really don’t want to sound cynical, sarcastic or satirical, but that?
I really am looking forward to IE7, so I hope you guys can find a fix for IE6 and include it in IE7 as well.
And since you guys can read the hundreds of requests on this blog alone for full W3C standards support in IE7, I won’t request it again 😉 .
I didn’t think Netscape could get any worse. At the moment, can you say why they did this? I can’t think of any reason since the gecko xml parser should work just find for anything they need, and I don’t recall this issue with the betas. Maybe its a bug in some custom xslt parser?
The worse part is that this hurts them as well. The xml feed you posted doesn’t work in Netscape 8. Well, to clarify, it doesn’t if Netscape is using Trident.
Why the hell are Netscape writing registry entries under Internet Explorer’s section? This after releasing "the most secure browser ever" with known holes in?
Yes, it uses Trident underneath, but it’s a fully fledged app, not a plugin.
Shows once again that it was Netscape incompetence that led to IE’s dominance, not monopoly "abuse".
PS If there are any Netscape browser developers reading this, your UI is pathetic.
Cue endless conspiracy theories about MS’s "dirty tactics"
Honestly, the rubbish you have to put up with.. my heart goes out to you guys. Keep up the good work with IE7
I’ve got NS8 installed, and can view the supplied link just fine in IE… (SP2)
Does this problem breaks windows update ?
And if yes, what’s the error message displayed ?
TIA
@Doug Wright
Is that first release or the patched version? I have the former and it doesn’t work at all on XP SP2.
After reading your post, I went back and loaded the blog entry then the links. IE stayed the same, but Netscape generated a different output, an image icon. I wish it’d make up it’s mind.
Find the new netscape on
@snowknight
I’ve got 8.0 installed.
The feed page works just fine in IE, Firefox, NS8/Gecko and NS8/IE.
Shrug
This raises the question of why the registry has no security in the first place.
Ant: What do you mean by "no security"? You can ACL any part of the registry to restrict it as you wish. ACLs are apply to user accounts (and the apps running under them).
If you wanted to "secure" the registry to prevent Netscape from writing to the IE portion, you’d have to run IE from a different account (different "token") than Netscape — that way IE could access its portion and Netscape could access its portion. Is that what you mean?
Vincent I think that was quite valid question. Even MS says people shouldn’t modify MS’s registry settings and offer that option only for troubleshooting. Why should programs go change IE or other OS settings unless user specifically wanted such to happen?
I think this clearly points out a flaw in the system. In LH no doubt any program trying to change other programs or the OS registry settings will just find these changes disappear when the program is restarted.
That’s it! I’ve been stumped by this problem as my xml with xsl transformation stopped working (blank page).
Thank you!
And now we know why the Moz codebase struggled under AOL stupidity.
Randy eh 😉
This would be funny if it weren’t so ironic. OK, it’s funny. We’ve just confirmed an issue that has started to be reported on newsgroups and forums that after installing Netscape 8 the XML rendering capabilities of Internet Explorer no longer work. To paraphrase the old Microsoft-bashing line: "Netscape ain’t done…
First, it looks like Netscape 8 doesn’t handle XML either when using Trident. So it trashes it for both Netscape and IE.
Second, to Chloe and anyone else wanting to take potshots at old-school Netscape: This browser was not actually developed by the same company or people that developed Netscape 1-4 or even Netscape 6-7. AOL effectively dissolved that company two years ago (it exists in name only), and they outsourced development of NS8 to a company called Mercurial Communications.
The "heir" of Netscape, the company, is essentially the Mozilla Foundation, and the heirs of Netscape, the browser, are Mozilla and Firefox. You’ll note that neither of these disables features of IE.
Sorry, I can’t resist one little potshot at old-school Netscape: this takes me back to the days when Navigator was still my preferred browser and IE was not yet its equal – but if I was rash enough to uninstall an instance of Netscape it charmingly took half of Windows 95 with it (on the apparent assumption that "if Netscape doesn’t need something anymore, *nothing* needs it").
Those were the days.
Now that they’ve turned the brand into a portal and a low-cost ISP, and with all the Firefox/Mozilla variations out there I seriously can’t understand why AOL doesn’t just let the Netscape browser die? Why would anyone out there still be using it anyway?
To Kelson:
Regarding ‘new’ Netscape, well they’ve obviously learnt the lessons of why they once failed. Not. Their UI is inconsistent and ugly.
And the ‘old’ Netscape ethos continues to pervade the Mozilla Foundation today. Their software is buggy and bloated.
It’s obvious to the most casual observer that Firefox UI is orders of magnitude better than that of IE6, but that is (relatively) minor to correct. After which, there will be no compelling reason to use it.
Like other open standards extremists Mozilla are too insular. They should work on what end users want (UI) instead of what a whiny minority of web developers want..
Rest assured that the old Netscape idiocy is alive and well, both at Netscape and Mozilla, just with better marketing.
I’m really looking forward to IE7, which, from what I hear, should have better support for things like alpha-transparent PNG images, more CSS2 capabilities, etc., that I would have loved to be able to use over the last few years when something like 5% of the browsers out there supported them. I’m tired of leaving out nifty features because they "only" work in Mozilla, Opera and Safari. I’m tired of writing code based on the published specifications and finding that the world’s most popular browser does something strange with it, like requiring an empty paragraph at the end of the page in order to make a border visible. I’m sure it will take several years for everyone to migrate, but I would like to think that (a) IE 7 will improve matters and (b) enough people will upgrade that us "whiny web developers" can just build pages instead of hacking around zillions of browser incompatibilities.
Of course, I won’t be able to use it at work, since we’re standardized on Windows 2000.
As for "Netscape" learning why "they" failed before — Netscape 8 is made by all new people. AFAIK they’ve never built a web browser before. Ever. They’re not even *called* Netscape. AOL hired outside people and tacked the name on the browser. And I agree with you that they don’t seem to have done a good job.
Firefox being "buggy and bloated?" I disagree, but that’s a matter of opinion. I can only think of one FF bug that’s given me problems since it hit 1.0, but you may have run into others. And "bloat" is simply a synonym for "features I don’t use." One person’s bloat is another person’s make-or-break requirement.
Mozilla-specific CSS extensions: You’re kidding, right? The whole reason they begin with "moz-" is to discourage people from using them outside the browser UI or experimental sites. It deliberately *avoids* the classic "embrace and extend" technique, which involves taking a published standard, extending it, and getting people to *depend on* your extensions.
To Chloe:
"Instead of using Flash which is installed on 97% of computers they insist on implementing SVG."
Are you talking about natively supporting Flash? Why would any browser do this when there is a perfectly good (and as you say, well-deployed) proprietary plugin available?
If you’re not talking about Firefox supporting Flash natively, then what do you mean by "Instead of using Flash…they insist on implementing SVG"? How would Mozilla "use Flash" to improve the browser?
I guess I misunderstood your comment.
Regards,
Jeff Schiller
P.S. Sorry for continuing the side distraction of the relevant issue regarding Netscape 8’s recent bug.
It is great that you are providing a way for people to restore Internet Explorer to its full state of functionality in case they are inclined to do so, but considering that Internet Explorer chokes on XML prologs and application/xhtml+xml content, does it really matter if its XML support is completely broken rather than remaining partly broken and partly obsolete?
To Kelson:
Firefox is bloated because it eats memory like no tomorrow, and then refuses to release it. It actually has a reasonably sparse feature set, which is good, but with Deer Park it seems to be moving towards bloat like SVG. Even worse the bloat is ‘behind the scenes’ – there will be next to no UI improvements.
And Mozilla is perfectly capable of proprietary extensions. See their prefetch for another example.
To Jeff Schiller:
Whether things are implemented as a plugin or natively is pointless semantics when it is implemented on > 97% of installs. Instead of improving what works (ie Flash), SVG is a overengineered bloated hog. But what more can you expect when it’s designed by committee vote?
I really hope IE doesn’t implement SVG natively, because that will effectively kill SVG fad dead in the water. It’s time for MS to impose their authority..
Back on topic, I can’t see any possible reason whatsoever to use Netscape. It’s awful. The "website rating" security device is performed far far better with tools like Netcraft or Spoofstick toolbar. The only reason it has more press than Maxthon or Deepnet is because of its brand recognition.
"People want a browser which shows their pages."
And, as has been said time and time again, "militant" webmasters want to do their page ONCE, and have it display properly on a variety of platforms, be it IE, Mozilla, mobile devices, etc, and standards are the way to allow this.
You may set read-only for:
HKEY_LOCAL_MACHINESOFTWAREMicrosoftInternet ExplorerPluginsExtension regkey
@snowkinght
Unfortunately browsing an xml file of a reasonably large size in Gecko is cripplingly slow compared to IE.
Anyone know why Netscape did this? It doesn’t make much sense, anyone who has to uninstall Netscape 8 should give Firefox a try – it’s better anyway 😉
Chloe:
Link prefetching does not violate any standards:
Also the W3C states
"Refers to the next document in a linear sequence of documents. User agents may choose to preload the "next" document, to reduce the perceived load time."
Will IE7 have better RSS support? I suggest a setup like Safari RSS (Macintosh) to make RSS pages more useful
> Chloe : "Firefox is bloated because it eats memory like no tomorrow, and then refuses to release it."
This issue will be corrected in next releases.
> "I really hope IE doesn’t implement SVG natively"
I really hope IE7 implements SVG (like Opera 8, and future version of FF). We don’t need proprietary stuff like Flash. We need standards things built with XML : XHTML, SVG, MathML… We must be able to mix different languages in one page.
And stop thinking that SVG is a bloated technology : Opera implements SVG-lite which is not bloated…
> "It’s time for MS to impose their authority. "
Hey, we’re in 2005 : we need open-source, cross-plateform technologies. We don’t need another monopoly…
> "Realise this: no-one in the ‘real world’ outside militant webmasters cares about standards."
Wrong : Real web-developpers cares about standards.
Hmmm. I would like to know your job. Are you a web-developper ?
S
> And Mozilla are more than happy to ’embrace and extend’ – think of ‘moz-‘ in CSS.
The same could be said for IE, except it’s impossible to tell MS’s proprietary extensions apart from legitimate CSS since they don’t bother to put a prefix on their names, unlike Mozilla and Opera and KHTML and _every other browser using extensions to CSS_.
I don’t believe anyone has mentioned this, which strikes me as odd… but anyhow, XML was meant to be displayed with a style language, & thus should degrade to a jumble of strings, no tags displayed.
I know from experience that IE shows the XML in a tree, & so do Gecko browsers – so here’s my query:
Does IE render XML properly when it /is/ given a stylesheet? Or does it still treat it like pure data, not as a /markup/ language?
What I’d really like to see the IE team doing would be a regular progress report like this
It lists what changes have been made to the most recent development version of Firefox (Deer Park) and what bugs and regressions are still outstanding.
It’d be interesting1 to see what progress the IE team is making.
Of course as IE is not open source we’d not expect to see links to the Microsoft bug database and would understand if they didn’t want to mention any secret features but it’d be good to see the daily progress made on standards compliance, security and features you’ve already revealed (e.g. tabs)
Chloe: So nobody cares about standards except web developers? They just want something to display their web pages? How exactly would any browser do that without any standards? Every browser would use proprietary tags etc and nothing would in anything but a single browser. Standards are there for a reason, by following standards it’s far easier to create an accessible website because I know what supports particular parts of the standard and what doesn’t I can code appropriately to make sure code works in everything.
And for the XML bug, pfft, just another bug…it’s software what else should we expect 😉
To Aidan Walsh, prodebd:
Standards are ridiculously overengineered. Who seriously believes in the semantic web?
Even widespread standards don’t actually work – they always have leaks in their specs. No two implementations will be the same, and if developers are forced to run to the W3C every time they have a question no-one would get anything done.
Therefore there is no way to be sure of cross-browser compatibility without testing your pages in all browsers. The job of web developers is made harder by having to cater to multiple browsers.
To FlorentG:
This issue will be corrected in next releases?
And Longhorn will be ship on time. Where is your evidence?
Opera uses SVG-Tiny so it’s not bloat?
Irrespective of the complete lack of logic you demonstrate in making your point, Opera is the most bloated browser in existence. It appeals only to the savvy and will never escape its niche on desktops. SVG tries to reinvent the wheel and should learn from the failure of VML..
Fortunately I trust Microsoft to base their decisions firmly on economic principles rather than idealism.
Yes, I am a web developer, amongst other things.
You had better be careful because I have IE on Windows XP with SP 2 and the link works just fine for me in Avant browser or IE (which I admit to never using except for browsing the Windows update or Office update sites), Firefox 1.04, Netscape 7.2, or Netscape 8.01 using Display like Firefox or Display like Internet Explorer. You seem to have reported a problem that does not affect everyone using Netscape 8.
"Therefore there is no way to be sure of cross-browser compatibility without testing your pages in all browsers. The job of web developers is made harder by having to cater to multiple browsers."
Of course it’s made harder. Most of my time goes to catering for IE – if I could only design for Gecko browsers I’d be much quicker. But that’s life. So the point of a generic standard is that you can minimise the time taken to build cross browser compatible websites. The only alternative is to ubild for a single browser, which doesn’t appeal to me – besides, my company wouldn’t let me.
Seems to me reason enough to not touch ns8. <a href="">Firefox</a> is much much more friendly. Firefox is just more trust worthy then netscape and of course much much more secure then IE.
But Chloe, for once leave the economic reason aside.
As a Web developer, don’t you wish that you focus solely on creating a presentable user experience, rather than worrying and adding knick-knacks for each particular browser??
It was certainly this logic that lead us to standards in first place.
Their implementation and embracement by Microsoft will go a long way in making better web-pages.
All we ask is to give us the bare minimum tools (CSS2, XHTML) applicable the same way in all the browsers. This update is necessary in IE as Web-development is also evolving with time and progress of computing.
Embracing the standards and new techonologies will give flexibility in the hands of developers and a lay home-page creator equally.
What we are really complaining about is that IE is taking awfully long to embrace the new technologies thus actually impeding the development of WWW.
i am glad that this has happened to ie..i dont care if it was intentional or an accident.
"Realise this: no-one in the ‘real world’ outside militant webmasters cares about standards"
you do realise that these ‘militant webmasters’ care about standards for you all?, they care that their site works in all browsers on all platforms, they could (like some pathetic designers) just build their for internet explorer, but no. they spend about 5 hours fixing an error that should not even be an error, what browser is the error on always? internet explorer.
remember, standards are to there to give you the best internet experience possible, and that same experience to be availible on multiple browsers/platforms.
Fred Greg: Yes, if an XML document is styled with CSS or XSLT, Internet Explorer will display it styled.
Standards are a great starting point, but this war between the "new XML/XHTML standards" and the "old HTML way" is stupid. XHTML has just made webmasters learn a new set of hacks and workarounds for all of the buggy implementations of CSS/CSS2 in a dozen different browser versions. That’s standards for you. So instead of focusing time and effort on creating new content and design websites for users, I have to spend twice the amount of time learning new hacks and new work-arounds since my old knowledge and experience is replaced by shiny, brand-new standards. (Remember, HTML 3.0 was a perfectly good standard for it’s time and still renders beautifully in all modern browsers.)
The nice thing is that in the real world, most webmasters don’t code to the current standards because they know such standards will always be a moving target. The argument that the old ways will go away in newer browsers just hasn’t happened (heck, even the infamous blink tag still works in Mozilla!) and, you know what, it never will. Old standards will be supported as long as there is a significant base of "old" users (which is another good decade of MSIE 6.x).
So quit already with the standards war. Nobody is listening who cares.
And in other news, Coke tells users to not drink Pepsi.
Shocking!
I came up with a way of dealing with IE not rendering pages correctly. Just ignore it and suggest Firefox to people coming to my site.
Al instalar el nuevo Netscape 8 puede suceder (como ha sido mi caso con un Windows XP) que Internet Explorer deje de visualizar documentos XML —como los feeds RSS. En IEBlog cuentan la solución en dos pasos y el primero…
Appearently, there has come to light a small issue with Netscape 8 and the fact that is installs a wrapper…
Chloe wrote:
>.
See:
Quotation from that article, which discusses how Excel overcame Lotus 123’s huge advantage in installed base and network effects that came from that:
> The best way to eliminate people’s
> objections to switching to your product is
> to make it easy to switch back. Nobody
> wants to switch to a product that is going
> to eliminate their freedom in the future.
—
David W. Fenton
David Fenton Associates
Correct me if I’m wrong, but isn’t the Plugins branch within the registry the CORRECT place for applications to extend IE’s functionality? If I have an application that handles a particular document type, and I want to expose my new features through IE, wouldn’t I HAVE to specify that in the registry in this location?
Is it possible that Netscape decided that their browser had XML support that users might want to take advantage of, and (with or without the user’s consent), registered that capability with IE using its standard plugin/extension mechanism?
Now, I’m perfectly willing to go along with the suggestion that a Netscape bug caused IE to misbehave here, but it’s a whopper of an assumption to suggest that Netscape had no business doing this to begin with, or that it was remotely a malicious thing. It seems to me that Netscape was simply trying to register itself as an XML-handling application for IE, but it was buggy, so it failed to render anything.
Is there something else here that suggests Netscape was actually in the wrong here? I realize there are lots of "Microsoft is good, Netscape is bad" folks reading MSDN blogs, but let’s base our snide remarks on actual facts, yah?
"If you wanted to "secure" the registry to prevent Netscape from writing to the IE portion, you’d have to run IE from a different account (different "token") than Netscape — that way IE could access its portion and Netscape could access its portion."
Since the the key in question here is in the HKLM branch, that won’t make any difference. And it indeed raises the question why the key is in the HKLM branch, and why it is apparently writable for ordinary user accounts. And if you can put ACLs on registry keys, why does nobody, not even Microsoft, do that?
Some black eyes on MS part…relating to Netscape
Oh, and that security hole in netscape? A fix was released within a day. Not that it matters — Who would bother with netscape when firefox is avaliable? Hey Microsoft uses it:
…but refuses to admit that even though it’s obviously true.
Microsoft also recommend using firefox instead of IE!
> Opera is the most bloated browser in existence. It appeals only to the savvy and will never escape its niche on desktops.
Opera’s main market is mobile phones and handhelds, and the reality is it does quite well in that market.
Also, if Opera is the most bloated browser in existence as you seem to think it is, how do you explain the IE6 installation download (or its SP1 for that matter) being 9-73MB bigger? Yes that’s right, IE6 SP1 is 11MB at a bare minimum according to MS’s own information.
I’m no Opera fan myself, but maybe you should "Get the Facts" before making wild accusations.
David,
When you install an alternate browser, you don’t expect the "all your browser are belong to us" treatment. If I install NS8 alongside IE6, it’s because I want to test in both. It does me no good if NS8 sticks its fingers in IE6 and makes its rendering the rendering for both.
isnt the bottom line here, shouldnt have netscape made sure their browser worked in IE, afterall they using the core engine for rendering..
but the bugs dont stop there… after about 10 tabs ..new tabs start to become invisible ..i think netscape pushed it out the door and need to come up with a fix.. i have noticed a couple other bugs also..
and at first i was enjoying netscape after years of not using them ..because of its limitations
Regarding all the Friefox bashing:
Fine, there’s a memeory hole. So there’s stuff that needs to be worked out. But IE is at version 6.whatever; Firefox is at 1.0.4. Give it time. MS has been at it for like 10 years and they still can’t get a decent browser out to the world. Obviously IE7 will be better than 6, but I’m confident Firefox 2 will be better and less buggy than 1.0.
ok so i went over to netscape to see what they had to say and after a small debate, netscape admits its their fault and the bug exist..
"We apologize for the inconvenience that this bug has caused you. This certainly isn’t desired behavior and we didn’t even intentionally change that registry key. The development team is hard at work on a patch.
Thanks,
Netscape Product"
source:
Have you ever had one of those "moments" when you have literally dug so deep down into your mind to try and solve a problem that you literally have reached the point where there is simply nothing left to search…
Have you ever had one of those "moments" when you have literally dug so deep down into your mind to try and solve a problem that you literally have reached the point where there is simply nothing left to search…
Netscape 8の導入でIEに不具合 Netscapeの最新版をインストール…
I have been having so much trouble with IE lately. Pages load so slowly that they often time out and I have to refresh repeatedly to get them. At one point IE would not even access the net, although e-mail and program updates that didn’t use IE worked fine. I had to install Netscape to get internet access. (I had an old install package in my download directory.) I haven’t yet noticed blank pages in IE (which I am using at this moment) since installing Netscape, but if I do, I guess it will be IE that I remove.
I have lots of mal-ware programs installed and running (see my blog at ). I recently re-installed XP and SP 2, and everything is updated to the hilt, including IE.
Well after a Netscape finally released their v8.0 browser, they released an update to fix a security…
Well apparently Netscape makes some other modifications because I removed the registry entries noted above and locked their permissions so they wouldn’t be recreated. I then tried the page in Internet Explorer and it would not work. It only started working after I uninstalled Netscape 8.0.1 so there must be more to it then the registry entries listed above.
Notice it doesnt effect Firefox? Make the switch today.
Chloe – I wholeheartedly agree with you. I’ve been writing about the issues raised by militant web standards evangelism since last year:
"W3C uses CSS3 to bash IE":
"The tyranny of standards":
"hypocricy laid bare – the proprietary document object model":
"W3C is dead":
Note that I wrote these almost a year ago when Firefox was just kicking off, so they may seem a little out-of-date. I think the points are still valid
I note a few comments from Pro MS supporter about maintaining standards and I am aware that MS try to enforce their products with none standard functions as a standard (frontpage). It also reminds me of how MS said IE could not be seperated from windows and yet it was proved wrong. I don’t use Netscape and don’t have any intention to because I am use to using the benefits that firefox and mozilla provide. Complain as you will about these other browsers but the less we are dependant on one vendor the less likley we will have to pay for a new GUI and a few extra tidbits to show they did something for 12 months and in doing so make us pay a hefty price for an update that 99% of users will never use.
If you say well don’t upgrade if you don’t need it, is rediculous and narrow minded for when I need to access someone elses file that uses the newer version.
I wouldn’t care if IE made me a cup of coffee or answered my phone, the alternative is the preferred option. When the opportunity to play with Linux comes I will move as far as possible away from Microsoft as I can.
I am glad I am one of many who has the intention of making MS work for it’s money. Have you ever tried to close IE when MSN is open? It won’t let me. Why? Because it states an application that uses it is still open. Not only that but I don’t use IE and yet my startup list often shows I have done so and on several occassions. The more you support MS and its devious methods of snaring you the more insane it will get.
Q: How many programmers does it take to change a light bulb?
A: None. Its a hardware problem.
Q: How many MS programmers does it take to change a light bulb?
A: None. They change the ‘standard’ to darkness.
MS is in business to make money. Period. That is what a business is in business to do.
MS just happens to worked hard and long to place itself into the position of forcing everyone else to play catch up in a rigged game.
Could MS do better? Sure. They won’t untill there is a financial reason for them to do so.
Security, they just don’t get it. I should be able to control what processes access what resources. An app should be able to ‘own’ its own sub branch in the registry.
I won’t even start on the whole ActiveX issue, or overly powerfull scripting languages like VBA that support scripts embeded within documents.
I checked on my machine — Windows XP home edition;Service pack 2, Internet explorer 6.0.2900, Netscape Navigator Version 8; 0.9.6, FireFox Version 1.0.3.
I do not seem to have the problem listed here.
Dave can you kindly specify the configuration that is effected by this netscape issue.
regards
shantanu@myworld-myrules.com
@robin
That still doesn’t explain why Netscape would need to set one of its dlls as a plugin for IE.
@Everyone who says SVG isn’t bloated
If SVG 1.2 isn’t bloated, then why does it contain a "File Upload" section and a "Persistent Client-side Data storage" section? Does Scalable Vector Graphics really need them to be a proper *graphics* standard? It reminds me of the old Netscape/Mozilla mindset before Firefox got started.
Chris Beach and Chloe, you have my full agreement. It’s nice to see others out there that recognize Netscape for what it is – a sad, horribly mutated, utterly irrelevant product of uncoordinated development and misguided convictions – and that recognize Internet Explorer for what *it* is – a remarkable piece of software that sets advanced browsing standards for an entire world, continues to further open up a global network to the public, and is the clear leader in innovations that really matter.
Chris, your articles on the truth about web standards, and the misinformation and misperceptions regarding Microsoft and IE that are bandied about so frequently, are a breath of fresh air.
Netscape breaks IE’s XML Rendering
re my comment above:
It turns out I am using Netscape 6. I guess some of my download files are a bit out of date. But maybe that’s a good thing. At least I had something available that worked when I needed it. In any case I followed the links to Mozilla and downloaded the packages for Mozilla, Firefox, and Thunderbird for both Windows and Linux. They are not installed yet, but are available in case of trouble.
I have the problem of a blank ie when viewing xml
but i have nothing under the extension key is the xml sub key any where else?
Hey guys one of my pc at home has this similar problem of having a blank page when accessing some site particularly hotmail, yahoo mail, some microsoft page and windows update and some forum sites. but other secure site like banking w/c uses Java dont seem to have a problem… And here’s the catch! there are no other browser installed on that machine just plain old IE and the machine OS is WIN XP with SP 2 with all the latest hotfix! Any idea guys? I heard from others they have the same issue also! pls do email me at albert_ri@yahoo.com if you have some solutions cheers!
snowknight wrote :
"If SVG 1.2 isn’t bloated, then why does it contain a "File Upload" section and a "Persistent Client-side Data storage" section?"
This is because SVG is not only a graphic-description language, it defines also a complete set of API to create graphics-based Application.
Moreover, SVG 1.2 adds stuff that was requested by the community. So some people may have asked a file upload API…
And remember that it is just a Working Draft… So it may disappear in when it will be released as a recommandation.
Quote: and that recognize Internet Explorer for what *it* is – a remarkable piece of software that sets advanced browsing standards for an entire world, continues to further open up a global network to the public, and is the clear leader in innovations that really matter.
Sorry, could you explain to me what "innovations" IE had the last years and since when does Microsoft "set advanced browsing standards"?
Surely you must be kidding when you say "is the clear leader in innovations that really matter". Sorry, but IE6 hasn’t had ANY innovations in years. Just now, when other browser (who do have innovations) are becoming more popular, they start working on IE again (after years of doing nothing).
Sorry, I’m not a real anti-IE person, but these comments just are wrong.
And this is the reason why I use Fedora Core 3 or MacOS Tiger…
Where in the original post on this subject does it state that the registry key is rewritten /by Netscape/?
Avoiding the (needless) personal insults that are already being thrown around here, here’s my take on the matter:
Without standards, and a *good* base of standards at that, the WWW would not exist at all. Neither the original Netscape, or IE can claim to have done *anyone* any favours by implementing proprietry extensions and forcing their use, however it is the case that the standards procedure is slow, lethargic and prone to a "committee" attitude. We wouldn’t be where we are now without the original Netscape and the other early browsers adding extra functionality to the existing standards. It’s just a shame about the awful way most of these extenstions were implemented.
As for developing for IE, Netscape, Opera, etc. I can safely say that the single most frustrating point in web development is the hopelessly buggy layout (CSS) support in IE. I’m not saying that Mozilla, Firefox, etc also don’t have their CSS bugs, it’s just that IEs are many more and worse. I’m not even going to start on MS’s implementation of JavaScript, which is "interesting" to say least, except that it’s not the only implementation with "interesting" features, it’s just that some of it’s slackness critically effects lots of code (interchangeable bracket types, for instance).
The end result, is that we *MUST* have multiple browsers for the market to not remain stagnant, bloated and unstable / vulnerable. If there weren’t (finally) some decent competitiors to IE, you can bet that MS would not have decided to retro-fit IE7 into XP.
Oh, and onto the brief subject of NS8’s interface – I’ve hated it and always have (this includes all of the previous versions of Netscape too). Mozilla is a much better browser but I still hate where it’s taken the interface elements from Netscape.
Interesting bug, but well, after IE releases breaking applications, some applications were bound to break IE ^_^
1. Start/run/regedit
2. Move following key.
HKLMSOFTWAREMicrosoftInternet ExplorerPluginsExtension
3. delete sub key, .xml
4. Move following key.
HKLMSOFTWAREMicrosoftWindowsCurrentVersionApp Paths
5. delete sub key, Netscape.exe
Both Netscape and MSIE operates well.
I found another workaround that allows you to keep using Netscape 8 and Internet Explorer with full XML/XSLT rendering.
1. Close all instances of Internet Explorer and NS8.
2. Goto C:Program FilesNetscapeNetscape Browserplugins (or to whatever directory that you’ve installed NS8 to) and rename the npTrident.dll file to npTrident.dll.bku.
3. Remove the .xml node from the Registry as specified at the top of this thread.
4. NS8 can still be used and IE will now render XML/XSLT properly. However, all functions provided by the Trident plugin will no longer work. This breaks NS8’s own XML/XSLT rendering, among other things, but this can be overriden by using the Firefox engine in NS8 to render it instead.
It is working for me, and so far has broken nothing else that I use apart from XML (which is fixable as stated by using Firefox).
Hope that this helps. ^)^
Well this takes the biscuit, doesn’t it? I mean, let’s face it – Microsoft are constantly being accused of dirty tactics and all that kind of nonsense. Here’s a clear case of an application invading another’s turf. I say Microsoft should cull them!
(OK, not that extreme, but something must be done. Keep up the good work MS.)
Chloe: "Firefox is bloated because it eats memory like no tomorrow, and then refuses to release it."
What, unlike Internet Explorer???!?
Phil asked, "How do I unstall IE? and windoze? And use linux as my main os with firefox and openoffice?"
Simply download the Fedora Core 4 DVD image, burn to a DVD, insert into your DVD drive and reboot and follow the very simple on-screen instructions. That is all.
Hey I have a similar problem:
I Installed Netscape8, had problems and then unistall it
Later I reinstall SP1 for IE6 and MSXML4
Now I can’t see XML files without this heading
<?xml version="1.0" encoding="utf-8"?>
At least adding this line I can see the file…
Yours
Joe
I hope all you "standards" supporters reliaze that most of your precious web standards were adopted from already long existing features in IE and the former Netscape and then renamed and fudged by the W3C usually breaking something in the process. In other words, your precious "standards" are non-standard; the standard was chosen long ago by the comsumers.
FlorentG Said:"Real web-developpers cares about standards."
It would be nice if IE, NS, Opera, FF, etc., would ALL meet the _basic_ W3 standards.
I have yet to find any web site that is enhanced using Flash (all Macromedia), JAVA, or anyother "add-ons."
Developers need to remember that not ALL visitors to their web site have high-speed connections. In fact, most don’t.
HTML is for basic communications and display, all the other is superfluous. KISS!
The web is so bloated with _junk_, it’s lost its usefulness.
Microsoft’s Dave Massy, the senior program manager for IE, has warned Internet Explorer users that Netscape’s 8.0 browser can cause a conflict with Microsoft’s browser Internet Explorer. This may be another setback for the new "security" Netscape 8.0. The browser had immediate…
Definitely some strong opinions here. Of course, this is why we have five major browsers available!
For what it’s worth, the advantage of any version of Netscape over an installation of IE is the reversablility. Not only can I run multiple versions of Netscape on the same system, I can uninstall any of them. Registry cleanup obviously needs some work here, but it appears that not everyone is affected anyway. Microsoft seems incapable or unwilling to allow a return path from browser upgrades. It makes no sense to force users to reformat a hard drive just to get back to the previous state.
Both Netscape and IE have some useful features unavailable in the other offering. If I could get IE to render pages as fast as Netscape, perhaps I would have switched by now. I have tried every new version of IE when it came out and have always returned to Netscape. I can’t use tabs or get a page to stop loading in IE. I can’t get real JAVA (that means multi platform) to work. Settings are buried so deep and some aren’t available at all, or are undocumented. The PDF plug in rarely works as well as the one in Netscape (should I blame Adobe?) The Outlook/Exchange remote interface actually works better in Netscape! I am glad to see that some folks are able to use IE for something useful.
Maybe it will be the easiest way,
but is it really necessary to uninstall Netscape8 ?
I think there is another way…
Open your regedt32.exe,
And modify security settings to protect from rewriting the registry key.
…For one thing, HKEY_LOCAL_MACHINE is not be able to rewrite on "Users" group.
Isn’t it easier to forget about IE instead of:
1 – uninstalling netscape.
2 – waiting for the updated version
3 – reinstalling netscape
Hmmmm. Seems to me that this sound vaguely familiar, only with MS apps were breaking software from other vendors (and Microsoft turning a deaf ear). Does anyone recall the chant, "DOS isn’t done, ’till Lotus wont run."?
Thanks for the update. I’ve had a few people complain already. I’m glad theirs a solution.
> Chloe : "Firefox is bloated because it eats memory like no tomorrow, and then refuses to release it."
I’d suggest fixing your computer or upgrading it, because if Firefox eats more RAM on your computer than IE6, your computer is f$%*ed up. Period.
IE eats at least double the resources that Firefox does.
(HTP4 3.0, 1gig PC3200 RAM, XP Pro SP2 slipstream install, Firefox 1.4)
Hell even when Firefox was a .7 BETA it still ate less resources than IE6.
Fix your computer.
" Does anyone recall the chant, "DOS isn’t done, ’till Lotus wont run."? "
LOL, yep! 🙂
All the bickering about standards and such is ridiculous. I’ve been a web developer for going on 12 years now and frankly I wish for one thing only.
A Winner. True standards compliance will only come when people accept the fact that the largest market share *must* be the standard. Why? Because it’s ridiculous to design for 2% of the browsers, or 5% or whatever. Working between MSIE and Firefox reminds me of the days when it was working withing the AOL framework as well as normal IE and netscape. 0 compliance and absolutely no consideration that one of them had 90% of the market share.
Don’t get me wrong, I like the technological advances that have come out of the W3C as well as emerging advances with SVG and Ajax. But frankly the *frequent* XHTML specification changes and other spec changes seems a lot like a bunch of people with no commercial interest "pie in the sky"ing things.
Just my 2 cents
It’s not a bug, it’s a feature! 😉
Seriously, a third party app not working with Windows. I’m shocked. SHOCKED I say.
I guess I’ll just keep using linux for a few more years.
Can anyone verify that it is a plain jane default build of Netscape 8 breaking IE and not a plugin of Netscape?
[Sarcastic] The next thing Microsoft will be doing is asking people to uninstall Firefox since it is posing a considerable amount of problems to I.E.’s diminishing market share. [/Sarcastic]
[Sarcastic] The next thing Microsoft will be doing is asking people to uninstall Firefox since it is posing a considerable amount of problems to I.E.’s diminishing market share. [/Sarcastic]
Quote from Chloe:
"Yes, it uses Trident underneath, but it’s a fully fledged app, not a plugin."
All I have to say is check the registry at the location this article describes.. you will find:
"C:Program FilesNetscapeNetscape BrowserPLUGINSnpTrident.dll"
Not a plugin? uh-huh.
Long Live IE, Death to Netscape/Mozilla
-Rob
Or just set the permission of `HKEY_LOCAL_MACHINESOFTWAREMicrosoftInternet ExplorerPluginsExtension` to read-only so when NetScape tries to rw-write the registry entries, the operationg system will not allow that to happen.
Netscape should not constantly re-write and `grab` control of something. Same goes with IE and any other program. What’s happened here is a sign of bas coding and no consideration for the user’s wishes.
Hahaha. SO I install Netscape. Then IE doesn’t work properly? SO WHAT!!! THats why I install Netscape, so I don’t have to use your rubbish browser. Even better – UNINSTALL IE. And you can!!!
Wow, its amazing how to fix a problem Microsoft tells you to uninstall Netscape. That’s like like getting a new DVD player for your tv, and then one button on the remote control for the TV isn’t working, and the TV manufacturer calls for you to return your DVD player and use their model.
That’s one good marketing strategy, but of course microsoft is known for these. It’s amazing that Microsoft beats the competition, NOT by having the best technology, but simply by advertising and domination of the market.
But, I think that’s all going to change soon. More and more people will be using linux (if you want to switch download a FREE linux, I suggest mandrake, from). IN LINUX, YOU CANNOT GET VIRUSES OR SPYWARE! All the programs for Linux are free!
To install a program you simply type "urpmi netscape". And that’s it! No double clicking, no clicking next, the recommendedn install. You only type two words "urpmi netscape"
@Those that want Microsoft to win and lock you in tight:
I guess its a good business case for them when you look at the kinds of fines and redevelopment costs they suffer in Europe. ;p
@Those that prefer Flash over SVG:
I can write SVG in your Microsoft provided notepad. Can you write Flash in it?
@IE6 XML Engine
I still remember how MS implemented an incomplete, customized, non-standardized version of XSL back in the day that didn’t even cover half the spectrum of the XSLT specification. Since then I’ve avoided XML+XSLT natively in IE. Who cares. You guys jaded me for good in that one.
However…
@Netscape 8 adding the registry setting
I wonder why they did this? I’d really like to see an explanation. Having your app add registry values to other applications registry settings sounds like spyware/malware to me…
Problem solved….use *nix
I have NS 8 and the link here works, as well as another feed I tried. I don’t think this is an issue for everyone, a few people have commented here that theirs is working fine as well.
zero2dash wrote:
>I’d suggest fixing your computer or upgrading it, because if Firefox eats more RAM on your computer than IE6, your computer is f$%*ed up.
Do you suggest "buying a new refrigerator, because in the old one there is no room a newer bucket of sh*t"?
(I prefer using Opera.
It sucks, too, but in a different way. ^_^)
>@Those that prefer Flash over SVG:
>I can write SVG in your Microsoft provided notepad. Can you write Flash in it?
Indeed, all I have to do is write and compile, same way you write C in Vi. Flash MX is hardly required.
>IN LINUX, YOU CANNOT GET VIRUSES OR SPYWARE! All the programs for Linux are free!
ahahahahaahaha. You’ll have to tell me how the land of delusion is this time of year, it sounds like a nice vacation.
————-
It was either an error of judgement for NS to do this, or more likely an error of testing, since it doesn’t seem to effect everyone. Cool that you’re working together to fix it. =D
Hey everyone, how’s the kool-aid?
Chloe,
> It’s obvious to the most casual observer that Firefox UI is orders of magnitude better than that of IE6, but that is (relatively) minor to correct. After which, there will be no compelling reason to use it.
The fact that Internet Explorer doesn’t run on many platforms is pretty compelling. What would you suggest I do? Switch platforms? Load up an emulator every time I want to surf the web?
> Instead of using Flash which is installed on 97% of computers they insist on implementing SVG.
Flash already works in Firefox.
> How many pages do you know of that use VML, let alone SVG?
That’s like saying nobody wants flying cars because "how many people use flying cars?" Obviously very few people use VML and SVG because browser support is so scarce. If I knew a decent amount of people would be able to see SVG, I’d use it all the time.
> And Mozilla are more than happy to ’embrace and extend’ – think of ‘moz-‘ in CSS.
You forgot the third ‘e’. The "embrace & extend" phrase originated in a Microsoft employee describing a strategy to embrace, extend and EXTINGUISH. So far I don’t see Mozilla taking an "extinguish" strategy towards CSS. How many people do you see saying "CSS is much less useful because of Mozilla"? How many people do you see saying "CSS is much less useful because of Internet Explorer"?
Oh look, the very next comment illustrates the idea perfectly:
> I’m tired of leaving out nifty features because they "only" work in Mozilla, Opera and Safari.
See what I mean?
> Firefox is bloated because it eats memory like no tomorrow, and then refuses to release it.
Already fixed in the latest nightlies. As opposed to the well-documented Internet Explorer Javascript memory leaks which are getting on four years old without any fix in sight.
> no-one in the ‘real world’ outside militant webmasters cares about standards. They don’t care about corner cases like Acid2. People want a browser which shows their pages.
Do you even understand the concept of interoperability and how specifications help to get browsers and documents that just work?
> Standards are ridiculously overengineered. Who seriously believes in the semantic web?
Which standards? You seem to be lumping the common "web standards" in with the semantic web. Some of the *semantic web* standards may be overengineered, but the common "web standards" are not. By conflating the two, you seem to be trying to confuse the matter.
> The job of web developers is made harder by having to cater to multiple browsers.
What’s your solution? A one browser web I suppose. The only alternative is standardising the code each browser uses, and you seem to be dead-set against that.
> [Firefox memory leaks] will be corrected in next releases? And Longhorn will be ship on time. Where is your evidence?
Feel free to download and verify the changes yourself:
Dave Harris,
> The argument that the old ways will go away in newer browsers just hasn’t happened
This is untrue. Old ways have gone away frequently. For example, Netscape layers, table layouts, JSSSL, non-text/css CSS resources have all broken in newer browsers.
> Old standards will be supported as long as there is a significant base of "old" users
Great. So instead of running a validator to determine whether something is right, I have to take a survey to figure out how many people still use the feature.
Chris Beach,
> Note that I wrote these almost a year ago when Firefox was just kicking off, so they may seem a little out-of-date. I think the points are still valid
I know you think you are playing devil’s advocate, but there is a difference between playing devil’s advocate and simply trolling.
Playing devil’s advocate involves taking a controversial view in order to generate good-natured discussion.
Trolling, on the other hand, is deliberately ignoring facts and logic to generate bad-natured arguments..
FlorentG,
> This is because SVG is not only a graphic-description language, it defines also a complete set of API to create graphics-based Application.
This is what makes SVG bloated. Most of the time, all you really need is a vector graphics format.
SVG-Tiny, on the other hand, isn’t bloated and I would welcome support for it.
> But frankly the *frequent* XHTML specification changes and other spec changes seems a lot like a bunch of people with no commercial interest "pie in the sky"ing things.
Huh? What frequent XHTML specification changes?
First, XHTML 1.0 was published in 2000.
Then, later that year, it was updated to make minor clarifications to the language used – there were no changes to the XHTML language.
Then XHTML 1.1 was published in 2001. No changes have been made to this specification.
So by my count there has only ever been a single change to XHTML, the update from 1.0 to 1.1.
As for "pie in the sky", CSS 2.1 was aimed at making CSS 2 more easily implementable and specified previously proprietary properties and values.
To call a complete uninstall a "work around" is a real stretch.
If true this is only a problem if the user wants to go back to IE. If you want to go back to Firefox, its not a problem. And of course its not a problem if you’re happy with Netscape 8.
Remember when MS added an error to MS Windows that prevented it to run under DR DOS?
Netscape, Firefox, Opera, Arachne and many other PC-based browsers have no problem working together, yet IE does? Perhaps the problem isn’t Netscape. Oh, that’s right, Microsoft programs are perfect, don’t crash, and have no security holes. 9_9
MS has long violated the standards accepted and set by the World Wide Web Consortium (). If Microsoft would design their browser and other products to follow these standards, there wouldn’t be a problem. Other companies can do it and make money, so why can’t microsoft?
Once again I get to say Hooray for Firefox!
What crap. Leave it to Micro$oft to go and claim problems w/ a rival browser. Mozilla is highly superior to IE anyway, why anyone wants Netscape is beyond me. BUt it’s a more likely choice over that dragon IE.
There are some pretty amsuing accusations in the comments to the stories on ZDNET and news.com. A number…
So if IE is bloated and greedy and Netscape tries to take over, IE has a breakdown and complains.
getfirefox.com
problem solved
regarding standards…
back in the early 1980’s, a lack of interoperability was plaguing electronic music instrument manufacturers. they wanted a way for their devices to communicate though the instruments themselves were made up of differing types of proprietary hardware & software. The companies who made these instruments, large & small, got together & agreed to come up with a way to do this: a language, a device standard, a hardware standard. It was called the musical instrument digtal interface, or MIDI. it’s still being used today & it still works pretty well. every aspect of music technology has improved because of it.
i am not a web developer. i am a musician. those of you who want to lash out at me for this, & say i am out of my depth for leveling a criticism on a topic i don’t understand, that’s fine. however, i think this makes my example more pertinent to this discussion, not less. all of you morons defending the market share of Microsoft as the end-all-be-all of who should define standards need to go back in history & take a little look at what cooperation & an honest adherance to standards can do.
why does the world’s largest software manufacturer NEED help to stand in the way of technological progress? why do people defend them? i thought competition was good. Microsoft’s had a long day in the sun – why do their products seem to degrade rather than improve, or not appear when promised at all? is it perhaps because they have a corporate strategy that disavows progress? anyone who defends Microsoft for any reason is intellectually lazy slob. & for those of you who say "i can’t wait for MS to define the standards…" blah blah… are you stupid? they do! look where it’s gotten us.
I thought I could stay out of this, but it seems that I can’t.
The CSS 2 (and most of the 3) standards are not just fluff thought up to make browser programmers’ jobs hard. There are good reasons for the CSS properties that have been added, and just because the major browser doesn’t support them does not mean that everybody should sit still and never progress.
There are too many USEFUL layouts that you cannot do without many of the CSS properties that Internet Explorer does not support. How do you do position: fixed, for example? Sure, javascript, but you shouldn’t rely on Javascript for layout, and doing so to simulate fixed causes a lag in updating the element’s position when scrolling (and makes me dizzy). And it’s only going to get worse. Right now, there’s now way to implement multiple dynamic columns, but W3C is working on a spec, and Firefox will get a rough implementation soon. But so what? The major player will not get support for it for at least 5 more years.
And what about styling form controls? Right now, because IE doesn’t support all the CSS selectors, we cannot style the different types of INPUT elements without adding redundant classes and increasing the size of all pages with forms.
Not to mention the rendering bugs, but at least it looks like those will be fixed, and when they are I’ll be very grateful.
And why are standards not important, and yet both the MSN teams and ASP.NET teams have made attempts at meeting the XHTML standards? If everyone uses IE then why not code for IE, right?
I’d like to see some good progress on the standards front. I’ve said it before, the standards-compliant layout engine (not the quirks mode one) needs to get regular updates to fix rendering bugs (possibly via Windows Update). People coding against the standards-compliant rendering mode will understand if their hacks to get a browser to work break after an update. Worst case scenario a user can use an alternate stylesheet and still view the content of the page. We should not have to wait 3 or 4 years for a new version to fix rendering bugs.
Mind you, security should still be the #1 concern, but not the only concern.
Anyway, keep up the good work. I used to love Internet Explorer, and I’d like to see some good competition in the market again.
Jim: "Trolling, on the other hand, is deliberately ignoring facts and logic to generate bad-natured arguments."
Rather than admit you simply disagree with my point of view (which I have carefully explained), you accuse me of being a "troll". It’s clear who is the troll here.
Jim: ."
You can call it "testing the specification" or whatever you like. The fact is, Mozilla have implemented techniques before they have been finalised by the W3C. This is the same as what Microsoft have done with their filter classes. If you genuinely believe we should wait (years) for the W3C to finally release a standard, then you should admit that both Microsoft and Mozilla should have held back on their implementations.
TheMuuj: "And what about styling form controls? Right now, because IE doesn’t support all the CSS selectors, we cannot style the different types of INPUT elements without adding redundant classes and increasing the size of all pages with forms."
Err hold on a minute. I for one have never had any problems styling form controls in IE. Other supposedly W3C-compliant browsers (eg Safari) have posed more of a problem.
So Netscape 8 "breaks" IE. Intended or not, it’s about time MS got a taste of it’s own tricks.
What CSS selector do you use to style a Text box but not a Checkbox? Try putting a red border on INPUT and see how ugly your checkboxes look. If IE supported full CSS 2 selectors, you could apply a style to INPUT[type=’text’] and INPUT[type=’checkbox’].
And don’t get me started on the styles themselves. IE ignores most styles for SELECT elements (border, etc.), and try making your textboxes 100% width (and line up with SELECT elements and TEXTAREA elements), playing with your padding, or adding a background image to a textbox. The only control that is hard to style in other browsers for me is the file upload control, and I admit the standard could use some clarification there.
And I have no gripes about IE’s extra stuff. The filter property is great, because it lets you work around some holes, but I don’t think it needs to be in the standard. And until it is, I would have preferred IE to use -msie-filter instead to avoid poluting the future standard namespace.
But there’s nothing wrong with embrace and extend, as long as you don’t eliminate. But in this case, IE could do a little more embracing before they worry about extending any more.
"And until it is, I would have preferred IE to use -msie-filter instead to avoid poluting the future standard namespace"
I don’t understand why any of these prefixes are in any way helpful to the progress of standard adoption. If a company sets a standard, let it become defacto.
In my opinion we don’t need -moz-XXX or -msie-XXX. These only serve to pollute the markup within early adopter websites. What we need is for one company just to set a final bloody standard! Anyone else getting bored of waiting years for the W3C to finalise CSS3? Anyone completely disillusioned of the ‘standards by committee’ approach?
I say let the IE team come up with its own standards where necessary (as it has done before), and forget browser-specific namespaces. There’s no need to wait around for the W3C. There’s no need to fear ‘closed-door’ standards development. After all, we’re talking about published markup syntax here, not a rocket-science proprietary data format.
Web standards evangelists – rather than venting your angst against IE, how about directing your rage towards the W3C and give them the kick up the arse required to release a coherent, complete version of CSS3 that everyone can adopt.
ehe.. microsoft fanboys are cool 🙂
Two years ago it was proven that Megasloth was deliberately targeting Opera users, designing the MSN websites to be unusable and unreadable by Opera. If you changed a setting so that Opera identified itself as IE, the webpages worked fine.
This is just another in a long line of cowardly, anticompetitive tactics by Megasloth. Instead of making a better product than the competition, they denigrate others and resort to the FUD factor: fear, uncertainty, doubt.
Jeff Rose
Microsoft Windows:
32-bit extension and graphical shell to a
16-bit patch to an
8-bit operating system originally coded for a
4-bit microprocessor which was written by a
2-bit company that can’t stand
one bit of competition
As per the instructions, I uninstalled Netscape 8.0 browser
I am unable to locate the node title "xml" after I navigated to
"HKEY_LOCAL_MACHINESOFTWAREMicrosoftInternet ExplorerPluginsExtension"
Did I missed some thing or what?
What if the syntax IE chooses for filter isn’t optimal for all browsers, or behaves in a way that is counter-intuitive, and when it gets standardized one little thing gets changed and it suddenly breaks a lot of sites. If it had been -msie-filter, the sites that used the old syntax would continue to work even after it becomes standardized, and other browsers may even choose to implement IE’s behavior. When it becomes part of the standard, developers could slowly move from "-msie-filter" to "filter" and make sure it behaves correctly.
This is going to happen in Mozilla with -moz-border-radius, which is slightly different than the CSS3 border-radius. The -moz-border-radius property is use-at-your-own-risk but have fun making your site look cool now if you want.
What’s worse, two browsers come up with a property at nearly the same time, but use entirely different syntax? Is the W3C supposed to try to come up with a syntax that supports both? What if they are completely incompatable? Who gets precedent?
> Rather than admit you simply disagree with my point of view (which I have carefully explained), you accuse me of being a "troll". It’s clear who is the troll here.
It’s not that I disagree with your point of view, it’s that it’s based upon false and misleading points, and that you ignore relevent facts.
> The fact is, Mozilla have implemented techniques before they have been finalised by the W3C. This is the same as what Microsoft have done with their filter classes.
No, it is not. It is different in two very important ways.
Firstly, Microsoft’s filter classes are not part of any CSS draft. Mozilla’s -moz-opacity property follows the opacity property in the CSS 3 color specification.
There is a *major* difference between implementing something that is standard but not yet stable, and just implementing whatever you like.
It might have escaped your attention, but opacity in particular is finished. The CSS 3 color module is at Candidate Recommendation stage, which means the W3C *want* people to implement it.
Secondly, they follow the CSS rules for specifying vendor specific extensions. Microsoft do not, they pollute the CSS namespace by not prefixing their extensions.
I have explained this to you before, and you persist in sticking your head in the sand, and continuing to make the same baseless claim that what the two organisations are doing is exactly the same.
THAT is why you are a troll and not playing devil’s advocate.
> If you genuinely believe we should wait (years) for the W3C to finally release a standard
I do not, and no part of my argument rests on that. Straw men are another typical troll-like behaviour.
> I don’t understand why any of these prefixes are in any way helpful to the progress of standard adoption. If a company sets a standard, let it become defacto.
That’s exactly the problem. The W3C are effectively barred from creating a property called ‘filter’ that doesn’t work in exactly the same way as Microsoft dictates. What if the W3C comes up with a better implementation? Call it filter-even-better?
> Web standards evangelists – rather than venting your angst against IE, how about directing your rage towards the W3C and give them the kick up the arse required to release a coherent, complete version of CSS3 that everyone can adopt.
What’s the point? Internet Explorer hasn’t even come close to finishing 2.1 yet. Again, you criticise the W3C for being slow while ignoring the fact that Internet Explorer is a long way from catching up with the W3C.
Oh, and many of the CSS 3 specifications are ready for implementing, not that this hasn’t been pointed out before.
Jim: "Internet Explorer hasn’t even come close to finishing 2.1 yet. Again, you criticise the W3C for being slow while ignoring the fact that Internet Explorer is a long way from catching up with the W3C."
Firstly, IE7’s developers have come very close to finishing their implementation of CSS2, as you would know if you’d been reading this blog and others. As for 2.1, well that’s mainly bugfixes for the errors made by the W3C in CSS2.0.
As for CSS3, why on earth should IE’s development team speed into implementing a standard that’s not even been decided on yet, let alone guaranteed error-free. The problem is that the W3C don’t release standards anymore when it comes to CSS. No browser will ever be CSS3-compliant because there really is no such thing as CSS3. There’s just tidbits of spec, dribbling out gradually. I hope you don’t think that the IE team should wait patiently for these fragments to emerge, hurriedly coding in each new feature at the beck and call of the W3C?
"Firstly, Microsoft’s filter classes are not part of any CSS draft. Mozilla’s -moz-opacity property follows the opacity property in the CSS 3 color specification."
If "-moz-opacity" follows the CSS3 colour spec, then Mozilla should have called their behaviour ‘opacity’
I can’t stand the thought of there being deliberately browser-specific markup at any stage of development.
The W3C opacity property has no more merit than a similar filter class from Microsoft. Yet you would have MS hold back for several years in order to follow the W3C specification of few simple bits of syntax. That’s completely backward. I don’t care if the syntax of some property hasn’t been agreed by a giant burocratic think-tank. Just allow me to make an element transparent. I don’t care if you think MS is conspiring to make their standard the one and only. Maybe some developers like the idea of their being a single, quickly implemented standard, no matter whether it comes from an independent organisation or a corporation
I’m fed up with people putting the reins on MS and then justifying it with daft conspiracy theories and general distrust. Let the company innovate on the web. The <10%-share browsers can fall into line, where they belong.
"Instead of using Flash which is installed on 97% of computers they insist on implementing SVG.".
I left Netscape behind forever right about the time v.4 was released. v.8?!? The mind boggles, hope springs eternal, and WTF?
"
Your sarcasm is rather droll. Flash IS a great commercial product. It’s hardly likely that the open-source movement will be able to come up a web graphics IDE of the calibre of Macromedia’s effort.
I like the fact that SWF’s are self contained. I dread to think what the markup of pages would be like if Flash content could somehow be intertwined with HTML, CSS and JavaScript. I dread to think what the performance would be like, too!
I consider SVG to be an extension too far in the web-standards arena. There are reasons why such vector standards have not taken off in the many years they have existed.
It seems the only reason you guys want to foist off a text-based Flash competitor is because you either don’t trust Macromedia, or Adobe (yikes, a big scary corporation!) or because you’re a cheapskate who doesn’t want to pay for good software.
Thank you. Now I have found a reason to install Netscape. I’m still gonna USE Firefox tho.
"I’m fed up with people putting the reins on MS and then justifying it with daft conspiracy theories and general distrust. Let the company innovate on the web. The <10%-share browsers can fall into line, where they belong."
When was the last time that IE innovated anything? Version 6. When was the last time IE added anything that somebody else innovated? Version 6.
When did version 6 come out? Yeah. That’s everybody’s point.
It’s not that IE 6 sucks (except for a few nasty bugs which make me pull my hair out). It’s that…it’s old…and getting older every day.
Now look at the competition. They may not be truely innovating (that’s debatable), and borrow ideas from other places, but they’re moving in a direction that resembles forward.
And I don’t care about CSS3. I *care* about CSS2/2.1. There’s a pretty good spec, and *most* of the browsers support it fairly decently, but we (web developers) can’t use it because the #1 browser doesn’t support it.
And I still haven’t seen the IE team say there will be 100% CSS2 support. They mentioned bug fixes, and mentioned vaguely that work was being done.
But I haven’t seen any list of what will be supported, such as ">" and "+" selctors, attribute selectors, extra pseudo-classes, "position: fixed", min/max-height/width. What about the nasty "height" bug where a container grows to its contents regardless of size?
I need to know whether I will be able to treat IE7 as a good browser and give it complete stylesheets, or if I continue to treat it as a downlevel browser. It’s tempting to feed it no stylesheet like I would Netscape 4, but my clients wouldn’t like that.
And to heck with CSS3. That can wait for IE 7.1/7.5/8.0. To heck with SVG (although it makes it easy to write resizable pages).
I want CSS2. Period. And it looks like Windows XP users will get it. Well, good for Windows XP users.
I already have it, on Windows 98, 2000, XP, and any other OS I can think of.
If Dean Edwards can hack a lot of standards support into IE6, then Microsoft could have surely write a patch for IE6 to do it correctly.
IE *WAS* a great browser. I’ve used IE from version 3 through version 6. IE still has potential to be a great browser. But it’s been sitting too comfortably on its throne (well, it seems not that comfortably, or IE7 would be Longhorn-only, I wager).
"I’m fed up with people putting the reins on MS and then justifying it with daft conspiracy theories and general distrust. Let the company innovate on the web. The <10%-share browsers can fall into line, where they belong."
what a twit … arguing against an alleged stifling of innovation my ms while at the same time advocating stifling innovation by anyone but ms. take your brain out of the blender, it might heal …
"arguing against an alleged stifling of innovation my ms while at the same time advocating stifling innovation by anyone but ms""
So, what you’re saying is, one browser, IE supports "filter", so all the other browsers should move and support it as well. I’ll give you that…it might not be a bad idea to wait for a standard in every case. If each browser documented how this was implemented (even in weird cases), this wouldn’t be that big of a deal.
But let’s look at the other side. Lots of browsers support selectors like "ul#nav > li" (instead of just "ul#nav li", which can lead to nasty problems if you nest lists)…all Gecko browsers, KTHML browsers, Opera, etc.
Let’s pretend for a second that this wasn’t standardized, since a lot of people seem to think that standards are too slow so we shouldn’t have them at all. Let’s say one non-Microsoft browser came up with this idea (I’m actually not sure where it came from), and all other browsers, except for IE, thought it was a good idea.
Why is it okay for IE not to support this? Is IE the only browser allowed to innovate.
Like I said before, proprietary extensions are fine (it does drive innovation, and pushes the standardization process), but don’t forget about actually implementing the standards, either.
I’ve posted most of my text in a separate location in order to save space in the comments area of this blog entry —
What does this "Remember Me?" check box do?
-Mart.
Hey people, don’t use IE, don’t use Netscape. Just use Firefox. Or write your own browser. I can’t understand why people continues to use IE, that is such the worst application I ever tried. Microsoft(TM)(R) continues to give us bad software, and all people in the world seems pleased to use it. I can’t understand this.
Start revenging yourself 😉
– All names and facts in this post are purely casual –
> Firstly, IE7’s developers have come very close to finishing their implementation of CSS2, as you would know if you’d been reading this blog and others.
I have been reading this blog. The only things that I have seen confirmed wrt. CSS is elimination of the peekaboo and guillotine bugs.
I would *LOVE* it if you could point me to a statement made by a Microsoft employee that states they have come very close to finishing their implementation of CSS 2.
However I haven’t seen anything like that on this blog, and I suspect it’s just more untruths from you. Please, prove me wrong. I want to be wrong. Give me a link.
> As for CSS3, why on earth should IE’s development team speed into implementing a standard that’s not even been decided on yet
This is exactly what I mean when I say you are trolling. I’ve already pointed out that some CSS 3 specifications are ready to be implemented, and you ignore the facts and continue to spout misinformation.
Here’s just one example:
"This specification is being put forth as a W3C Candidate Recommendation by the CSS Working Group"
"All persons are encouraged to review and implement this specification"
"The CSS Working Group believes this document addresses all last call comments, and can be considered stable. It can still be updated by the Working Group, but only to clarify its meaning."
So go ahead, stick your fingers in your ears and keep chanting "the W3C are way too slow for Microsoft", when Microsoft even fails to implement specifications that the W3C published nine years ago. You only make yourself look even more ridiculous.
From Saint Louis Today: Microsoft Corp. is urging Windows users to uninstall the new Netscape 8 Web browser from their…
"I’ve already pointed out that some CSS 3 specifications are ready to be implemented, and you ignore the facts and continue to spout misinformation."
And I’ve already explained that there is no value in a specification that is disparate and drip-fed into adoption.
CSS2.1 is worthy of adoption because it is a benchmark standard – a reference that all implementors can adopt.
CSS3 is just a hotch-potch bundle of standards that have been endlessly discussed since 1999. It’s NOT a coherent, complete specification. My complaint is with browser implementors having to wait years for the various bits of CSS3 to emerge from the W3C. It’s a complete farce. Especially when various CSS3 properties are just duplicating behaviour that MS has already made defacto in their own implementation since the late 90’s. Think element-level alpha, HTC behaviour, ruby characters, element orientation (eg vertical text) etc.
And Jim, please stop with the troll accusations. You’re just making yourself look bad-natured.
IE suxs taht’s all…
The major problem with Netscape, is that Netscape communications can’t provide as good support as Mozilla does to Firefox etc.
Just to remember that IE does not follow standards and MS is allways trying to block all software industry growth to mantain leadership. So why you guys claiming about a little bug in Netscape? How about javascript problems and proprietary java initiatives regarding IE browser? I abandoned IE a year ago… And I am VERY happy.
Hail to Opera and Firefox!
Hail with Opera and FireFox…
Uhhhh….Hmmm? What’s that? Netscape something… Ohhh yeah…I remember Netscape…
It does something to IE? Oh. So what’s your point?
<<This page viewed with Mozilla 1.75>>
<<there.is.only.xul>>
I am not about to wade through that mess above so if this is mentioned sorry.
I was having no problem with xml pages, but I was not able to see a lot of ASP pages.
Followed the path to the registry key for the xml, found the xml key – point to something in the Netscape directory – and found an ASPX key – pointing the same place. Removed, and low and behold I can view pages that end in ASP again.."
I hear you buddy!
MS may have brought web browsing to the masses, but it looks like Firefox is bring web browsing to the imbecilic hordes.
Chris Beach wrote :
> "No, that’s not what I’m saying. My point is that waiting for standards to be discussed and agreed by the W3C is slowing down the adoption of innovative CSS techniques on the web by all browsers."
Hehehe… Microsoft did *not* innovate for the 4 past years… Nothing has changed… Lot’s of *innovative* CSS 2.1 thnigs are still not implemented… -> Internet Explorer *is* slowing down the adoption of standards that have been discussed 6 years ago…
> "Microsoft have traditionally led the way on innovation (or "proprietary extension", or whatever you want to call it). Let them continue. Stop the crazy web standards jihad"
Traditionnally… But speaking about the web, we haven’t seen any innovation since IE6…
> "CSS3 is just a hotch-potch bundle of standards that have been endlessly discussed since 1999."
Lots of CSS3 modules have reached the Candidate Recommandation. So user-agents developpers should implement what’s in those recommandation, thus allowing developpers to test it… And guess what, Gecko, Opera & KHTML are implementing those Candidate Recommandation. And once it has been widely tested and approved, it can reach the W3C Recommandation… But it can take a long time… Especially if the main browser does not care about it… Who’s slowing down the adoption of those standards again ? huh ?
> "It’s NOT a coherent, complete specification."
I don’t see why it is not coherent… And it is of course not complete, as it is not finished yet 😉
> "Especially when various CSS3 properties are just duplicating behaviour that MS has already made defacto in their own implementation since the late 90’s."
Remember that Microsoft is part of the W3C, so they make some propositions 😉
> "MS may have brought web browsing to the masses,"
Hmmmm… I would say that it is Netscape who brought web browsing to the masses… But Microsoft came, and crushed Netscape with their free browser…
I’ve frequently experienced Microsoft software incorrectly rewriting portions of the system in response to certain system changes – like default browser changes, MBR changes, or the installer service (which is the worst). In re-reading the blog entry, it does make a clear dance around which program is making the registry changes. 🙂 Since I doubt that Netscape 8 is a continuously running process like IE, I would certainly doubt that it has the necessary hooks to maintain the registry key in question. Of course, Netscape (the present) is AOL’s bastard baby… so I wouldn’t put it past it to be running in the background to spawn spyware for the next few years.
Also, why are people bashing about against Netscape as if it’s a huge competitor? You should be looking at Mozilla or Firefox as an alternative to IE; not Netscape.
I’m also very depressed about the announcement of XP+ only support for IE7. I expected it, but it’s still disheartening to hear about more forced upgrades for users who insist on continuing to use IE.
To people who mention that the XP upgrade path is "painless"; you’ve never done any sort of systems administration. A single errant _pixel_ will confuse the average user until his brain overloads. I still have to show MSCE certified technicians how to use the new start menu; or find control panel settings. It’s baffling. Then there’s the whole licensing scheme. I’ve already called India to renew my home subscription (yes, I like to call it a subscription. I have to repurchase it the next time I upgrade my machine – so says India). I don’t feel like doing that on a corporate level.
I want to thank Internet Explorer for allowing spyware and adware to be installed on millions of computers!
What kind of crap is this about Netscape writing in IE’s registry keys?! As if MS apps never done that! MS is known for these kind of "bugs" so stop whining! IE6 apparently doesn’t know how to render xml – everybody knows MS is not sticking to standards when they should, and now they know why…
IE is gone and lost, and IE7 will not help MS in recovering their loss of market share. I want to bet that it will take less than 1 week after release until the first bug in IE7 will be discovered!
"What kind of crap is this about Netscape writing in IE’s registry keys?! As if MS apps never done that!"
err.. what’s wrong with MS apps writing in MS registry keys? lol
If Netscape writes in IE registry keys – THAT’S more of a problem.
Chris, you still haven’t explained why you keep talking as if there aren’t finished, ready-to-implement CSS 3 specifications. Or do you concede that they exist now?
And I’d still like to know where you heard that Microsoft have almost finished complete CSS 2 support. Really. If they really said something like that, I would like to know about it.
Jim, as Chris Wilson points out:
"there is no CSS3 standard yet"
CSS3 will never be a standard until all the disparate parts, in their various stages of discussion/recommendation are pieced together and full tested in real implementation.
As for support for the current CSS standards:
"The first couple of things they’ve done are .. Address[ed] CSS consistency problems"
"the beta release is almost here"
> "there is no CSS3 standard yet"
So you have resorted to ignoring me when I point out that CSS 3 is a *group* of specifications then?
There is no DHTML standard either. But that doesn’t mean that browsers don’t support ECMA-262, the DOM and CSS, which are the specifications that comprise "DHTML".
Let’s start small. Can you agree that this specification exists?
Can you agree that it says:
"All persons are encouraged to review and implement this specification"
Can you agree that it says:
"The CSS Working Group believes this document addresses all last call comments, and can be considered stable. It can still be updated by the Working Group, but only to clarify its meaning."
If you can agree on all that, then I’ll ask my question again:
Chris, you still haven’t explained why you keep talking as if there aren’t finished, ready-to-implement CSS 3 specifications. Or do you concede that they exist now?
> "The first couple of things they’ve done are .. Address[ed] CSS consistency problems"
In what fantasy land is "addressed CSS consistency problems" evidence of a full CSS 2 implementation? You left out the all-important context; he said that in relation to fixing the Peekaboo and Guillotine bugs, with nary a mention of implementing any more of the CSS 2 specification.
Jim: "So you have resorted to ignoring me when I point out that CSS 3 is a *group* of specifications then?"
I’m not going to get drawn into your diatribe, Jim. Of course I know that a group of specifications make up CSS3. As I have explained, this is the root of the problem, since they are all at varying stage of design, and there’s very little concrete adoption on the Web to show for any of them.
The W3C started CSS3 in 1999. They’re still going now, SIX years later. I don’t care what parallels you’d like to draw with IE. The W3C are clearly INEFFECTIVE at creating a cohesive CSS3 standard that’s ready for adoption by all browsers. No browser can claim "I support CSS3" and this is unlikely to change before the end of the decade.
This is therefore a farce.
> The W3C are clearly INEFFECTIVE at creating a cohesive CSS3 standard that’s ready for adoption by all browsers.
You are *still* talking as if CSS 3 is one monolithic specification!
Why aren’t you complaining that the W3C haven’t finished the "Internet" standard? Is it because Internet technologies are best described in a number of different specifications? Then why do you insist on ignoring the fact that CSS 3 is a *group* of specifications?
The W3C saw a need to specify a colour module for stylesheets. They gathered input. They wrote a specification. They gathered feedback. They made revisions. After a while, they published a finished specification and are asking people to implement it. Some browser developers are already doing so.
Why do you feel the need to drag other presentational concepts into it, and say that because *other* CSS 3 specifications haven’t been finished, that the specifications that *are* finished don’t matter?
It’s like saying that it’s impossible to read any Stephen King novels because he hasn’t finished writing his latest one yet. Nonsense!
Do you have any more places where you think Microsoft have claimed they’ve almost finished their CSS 2 implementation, or are you conceding that point?
Jim: "Then why do you insist on ignoring the fact that CSS 3 is a *group* of specifications?"
Sigh.. this is the BASIS of my point, which I have already explained. I’m really, really bored of your inflammatory diatribe now.
I tried uninstalling NS8, still the problem persists. I do not have such a registry entry to remove. What am I supposed to do? I’m stuck with NS8. Right now I ended up using NS8 as my default browser as I’m a web developer and need the xml display to test webservices.
-raj
Chris Beach said :
"As I have explained, this is the root of the problem, since they are all at varying stage of design, and there’s very little concrete adoption on the Web to show for any of them."
You can’t have a concrete adoption :
– 80% of web-developpers don’t even know the word "CSS"
– the leading browser (IE) hasn’t a complete implementation of CSS 2 yet…
Imagine that IE7 is released, and that it implements some of the CSS3 candidate recommandation… IE is causing a lot of harm in the adoption of CSS3…
Another Problem? Used Netscape 8 to view statements on a Merrill Lynch site. Statements came up in a PDF window which hung. Ever since when I try to bring up the statement pages with IE, I get a blank page and the globe never stops spinning. Can use Back to go back to the previous page. The XML registery key does not exist. Uninstalled Netscape – problem remains. Used add remove programs to Repair IE – problem remains. Any similar problems or a fix?
Just install Firefox :
Microsoft has alerted users that Netscape’s latest browser appears to break the XML rendering capabilities in Microsoft Internet Explorer. Dave Massy, a senior programme manager for IE, warned users in a blog posting that after installing Netscape 8, IE will…
This isn’t about XML’s. I hope it is alright to post here.
Since I have installed the 8.0.1 Netscape fix, I have been experiencing two problems. One is when I first click on Netscape and the process freezes showing me that 99.9% of my CPU is being used. Using Task Manager, I end the program and click on it again. The second go around everything comes up alright.
The other problem is with the email applet. Right in the middle of writing an email the program will automatically minimize it to the Start Menu time and again.
If some else is experiencing these problems or knows of a fix, I would sure appreciate the help.
I think that Netscape is doing us all a favour in disabling xml in IE. IE is a miserable waste of code, and I commend Netscape for saving users from their own stupidity. In fact, I decided to leave Microsoft for good, because of the inferior quality of their products. It was because of MS getting complacent and sitting on their laurels with IE that I went to Mozilla, and, later on, left Windows for two Macs and converted my Windows box to Linux.
To quote several inane users:
"I think that Netscape is doing us all a favour in disabling xml in IE"
"Hail to Opera and Firefox!"
"I abandoned IE a year ago… And I am VERY happy."
"IE suxs taht’s all…"
Why do you guys waste your time writing about your ignorance and loathing of Microsoft / Internet Explorer and love for competing products?
This site is designed to be a constructive environment where the developers make a genuine effort to communicate with the public. Don’t waste this opportunity. If you plan to use future versions of IE, then HELP the developers make the product you want.
If you are resigned to using competing products then that’s fine – but don’t waste this site’s resources by spouting your feelings of abandonment, disillusionment or general angst here. It’s pathetic, and wastes everyone’s time
Chris, baby, why are you wasting your time defending technology that is on the way out. Buy a macintosh, perhaps that will make you a happier person, cause you seem wound up a little too tight. Chill out man.
"why are you wasting your time defending technology that is on the way out. Buy a macintosh, perhaps that will make you a happier person"
Bob, "baby," I’m spending two minutes of my time defending technology that’s on the way IN (IE7). I’m fed up of people abusing this and other MS blogs.
For your information, I am in fact an Apple user, but I still use PC’s from time to time (and Windows is a darn sight more stable than OS X)
Note to self — stop feeding the trolls..
Hey guy`s IE6 with SP2 on Windows XP Pro had a problem, but not width NS8. Since friday june/3 my IE6 don’t show the web pages with XML and i haven’t installed NS8 or other similar program. why ???
Chris, Chris, Chris, man, take up yoga, get out more, IE7, IE8, Safari, why get so twisted about it? It’s only a browser, if it’s got a problem, then the developers will fix it, you can’t save the IT world, just let it slide man.
Chloe:
You make me laugh. I haven’t even got through a quarter of these posts and I am already in stitches. I have just got to the part where you have stated that you are indeed a web developer. I have been reading your comments and I am amazed that you have stated this. Maybe you can point us to a few of your sites so we can see them?
Personally, I do not believe you are a web developer, or if you are I think you use FrontPage. Personally I think you work for Microsoft or have somekind of affiliation to them. You seem far too pro-Microsoft for my liking, far too willing to dismiss non-MS products for the most stupidest of reasons. Your ability to dismiss standards, especially web standards, is amazing. Your accusations that Opera is bloated is amazing – Opera bloated, IE not, absolutely hilarious. MS should impose their authority should they? Only webmasters want standards do they? (This one made me laugh the most – surely a web DEVELOPER knows the difference between a web developer and a webmaster [or website administrator to give it it’s proper name]).
I look forward to the rest of your comments as today I was feeling down but now I am having a right old laugh at your expense. In fact, I have sent the link to these comments to all my friends (mostly non-web developers who understand the need for somekind of web standards).
Standards are needed. I have recently finished one simple page, a form, laid out and formatted using simple CSS. This page works in Netscape, Opera, K-Meleon, Firefox etc, but it does not display properly in IE. Now why is that. I can fix it simply enough, but why should I? It works in all browsers except IE? To me that says IE is broken.
If you are a web developer as you claim to be, I think you should start looking at the web standards and start using them. Learn CSS. In fact, take a project and try to write some simple pages using standard HTML & CSS and then try them in ALL the browsers you can find. Once you have done this try the same pages in IE!
Also, as a side project, try searching the net on the subject of IE & CSS. It makes interesting reading.
To keep on topic, the new netscape uses the IE engine as well as the Gecko engine doesn’t it? Maybe this will explain some things!!
Chloe, don’t make the same mistake as I did – ignore these pathetic trolls, and keep your sound arguments coming. Nice to see that not everyone is an OSS/Mozilla zealot in this forum
Chris baby, I thought you were going to keep on-topic? But I can see that you really do need that yoga lesson. Turn of the Microsoft drugs and go outside, I’m sure it’s going to be a nice day today.
RE: Netscape and their tactics. What else do you expect from a pig, but a grunt. Netscape programmers ARE weenies and now they’ve spawned to a whole new generation. Perhaps that is why AOL stands for AnOther Loser. Programmatical overwrites of someone else’s registry key doesn’t happen by accident. Anyone who believes that must be easily fooled. Call me. Let’s talk about your new investments.
IBM started it with DOS 4.0. It’s a mindset. Do what you want to MSFT and when MSFT fights back or complains, sue them and cry foul.
Bob…
Yoga is not for everyone. Telling someone to change their lifestyle in a blog is pointless unless it’s a Dr. Phil site and the topic is "Yoga and you" a.k.a. sitting around in weird positions for those who are reality challenged and stress out when the clock ticks.
Jim…
You’re an idiot. Your argument loses weight when you focus on personal attacks. If CSS3 is a group of specifications then it should be called the CSS3 Group. If the "committee" has been working on it since 1999, then THEY’RE SLOOOOOOOOW, like you. They don’t get it, you don’t get it. We, get it.
To the Einstein in the muzak industry… you’re out of your element and have no idea what you’re talking about. Ya’, everyone in the muzak industry got together and created this Utopia, man, it was like, cool and everything. Take another hit and feed us again. Your comparison is not relevant and it’s BS besides. You could compare the music industry to Hitler and it would be a close call as to who has destroyed more lives. Perhaps you’re not aware of their lobby efforts to be able to hack into any computer, legally, if they FEEL you MIGHT BE storing illegal copies of muzak. Sounds like a bunch of choir boys to me. 78s, 45s, 33s, 8-track, cassettes, laser disks, CDs, DVDs.. when will it end? It won’t. Why not make billions on each new technology which is just slightly better than the other?
I read some posts that said, "It’s much easier to develop for FF." Aaaaaaaack spit! That’s just BS and you know it. I spend 400-500% more time on FF than IE.
One argument was: Why the confusing [] and () for indexing? And if IE only had one, the argument would be, how come IE only has one?
Well, why doesn’t Javascript use () instead of []. Oh wait, they do for some things. No confusion there. Javascript is also case-sensitive but won’t tell you it’s a case-sensitivity error, although that would be something very easy to implement. Rather, it’s object expected.
Why was Word Perfect so hard to use? They [WP] said, "If it’s hard to program, it’s got to be hard to use." I guess that didn’t work out very well. Another war MSFT won.
Someone tell me why MSFT must support all the crap that comes from the open-source community but they [open source] hardly ever support anything from MSFT? How many browsers support vbscript? How many web servers support ASP and client-side vbscript? How many support MS Access?
For the dink who had to include, "DOS isn’t done until Lotus won’t run." just shows how stupid 1-2-3 users were. Lotus was the company, 1-2-3 was the app and it sucked. Here’s an idea. Take me out of my app to use another part of my app so I can chart my values using really crappy text graphics. That one feature is what killed Lotus 1-2-3. In Excel, I highlight my cells, with my mouse, in screen mode 12, using a GUI interface and press F11. The chart appears. I didn’t even need the full version of Windows because MSFT offered a runtime version to Excel would run without the full version.
MSFT won most wars because they were the first, and the only at the time, that thought the interface should be "user friendly." They also thought it was a pretty good idea to assign devices/drivers to the OS, rather than to each app.
Apple said they stold the technology from them which both got from Xerox. Xerox had some brilliant technology but was too stupid to know what to do with it.
Mr. Fedora Core 3 and 4. I’m running it. It sucks the big one. The Mozilla browser hangs more than Johnny Wad.
Mandrake? Ya’, Linux for weenies (see Netscape programmers).
I’m tired of hearing, Linux runs on my old 386 with 64k of memory, and washes my moped and cooks my pizza and chills my Diet Pepsi. The reason your Linux runs on your 386 is because you’re poor. That’s all you have and it runs pretty damn bad on it too.
The browser war is not over, it never will be. There will always be those that think everything should be given to them. We classify these people as free-loaders (see Liberals and other people’s money).
What I would like to see in IE7 is:
a version that does not integrate with the OS. Give me IE and IE Integrated (a.k.a. Windows Explorer) but call it IE Integrated. Also, MS Word does not have to be able to surf the net.
Hopefully OE will also be upgraded because I’m about ready to shoot it.
You can put in tabbed browsing but I would prefer tiled and cascaded browsing. I’d like to see all my pages at once.
Allow me to let my desktop background be my browser (IE Integrated). While you’re at it, give me more options than just large icons view on my desktop. I would prefer to have a list or detail view, like in Windows Explorer.
When I set the doctype to strict, IE should only support standards, nothing propritary. This would give me something no other browser can offer, full compliance for standards ONLY! There does not exist one on the planet today.
From the tiled view, let me click and drag a window off onto the desktop to get a new window and offer it as a copy or a move. I would also like to double click a header, as I can to get a full window but when in tiled view, my browser would open to another window.
Let me put my menus, toolbars anywhere I want on my browser and even off my browser.
Give me a way to identify, clear enough for n00bs, that I am in secure mode (SSL). The tiny icon in the status bar is not very useful if the status bar is off.
For those of you who think standards is so great, let’s compare it to another standard that doesn’t work very well. It’s called the U.N. Crappy org running just as bad with the same attitude towards the leader of the pack.
I’m not completely happy with IE but then there’s nothing else out there that would make me completely happy.
Roland: "Someone tell me why MSFT must support all the crap that comes from the open-source community but they [open source] hardly ever support anything from MSFT? How many browsers support vbscript?"
Roland is damned right!
OSS advocates are under the illusion that open-source IS the world of software, and therefore they have the right to press their open standards on every bit of commercial software. They fail to understand that in most cases, the adoption, documentation, testing and support of proprietary software is INFINITELY superior to their own hobbyist efforts, and that some open standards (eg CSS3) are becoming ridiculously bloated and impractical to adopt.
The cabal of minority browsers are using the web standards jihad as part of their monstrous grass-roots marketing campaign to gain market share for their fledgeling browsers. What the advocates fail to realise is that users (i.e. the people browsing the web) don’t give two hoots about the latest CSS trivia, or browsing with mouse-gestures, or daft browser "skins".
Yes, of course IE should have it’s bugs patched, and support PNG, but come on you standards advocates – you’re making an almighty mountain out of a molehile here.
"You’re an idiot. Your argument loses weight when you focus on personal attacks."
Priceless. 🙂
Something for the blame-Netscape crowd to explain:
WinXPSP1, install N8, no problem.
Add SP2, no more XML rendering.
Conspiracy? I don’t know, but maybe blame should be re-assessed.
Brianiac: Priceless 🙂
Perhaps you’re not familiar with the definition of "personal attack."
Brianiac: Something for the blame-Netscape crowd to explain:
WinXPSP1, install N8, no problem.
Add SP2, no more XML rendering.
Conspiracy? I don’t know, but maybe blame should be re-assessed.
So, what you’re saying is MSFT is to blame for Netscape rewriting IE’s registry key?
You’re probably right as nobody is willing to accept blame for anything these days. That old lady put herself in the position to have her purse snatched. That store owner was just looking to get robbed. That woman was just asking to be raped by dressing sexy. MSFT shouldn’t allow Netscape to overwrite IE’s registry keys. MSFT is to blame. it all makes sense when you put it that way.
Chris Beach said :
"Chloe, don’t make the same mistake as I did – ignore these pathetic trolls"
LOL
This one made me laugh for fifteen minutes… Come on… Who’s the real pathetic troll here ?
"You see a mote in another’s eye but cannot see a beam in your own" 😉
Microsoft goon squad is getting organized, FALL BACK, FALL BACK".
Nice tip!!fixed my problem with above soln. thx!
Got Netscape 8? Got Internet Explorer 6? Then you’ve got broken XML in Internet Explorer. Until now. Netscape’s issued an updated version that fixes the problem, according to BetaNews. Get Netscape 8.02 here….
While I will agree that IE as some cool features, it also has some serious security holes.
For the owner of this blog to suggest uninstalling Netscape shows a lack of technical insight. Quite frankly it’s irresponsible, as well as laughable. It smells of typical Gates angst, complete with whiny MS cheerleaders.
There’s a whole industry based on spyware and virus removal thanks to Microsoft. Perhaps these MS employee bloggers should spend less time giving ridiculous advice, and spend more time fixing the Boeing 747-size security holes.
BTW, I just installed SuSE Linux for my mother. She loves it!
Signed,
A Linux and Windows user.
Heh – Looks like a lot of really upset people here. Really upset. Some of the comments are most amusing.
I don’t know who’s to blame here, MS, Mozilla, or AOL. What I do know is that almost everyone who has posted here looks like a religous zealot.
What it comes down to in simple terms is:
1) IE has problems.
2) Netscape has problems.
And the vast majority of posters here would leave an alien from Mars who read the posts determined not to use either product,
I am a webmaster and care deeply about standards – and I by far a hardcore webmaster – I am just sick of making workarounds for IE when everything else works in any other browser because I make my pages standards compliant with rigerous testing –
I finally gave up and just tell people to go download firefox – its free and they will be browser with a standards compliant browser and also more secure.
I am sick of the attitude that it is other people’s problem to be compatible with microsoft – it is about time microsoft start being compatible with free software – or we will just stop buying you crap and get the FREE stuff – just like any other product we buy.
It is just common sense.
"…when officials were amending the XML problem, they came across faulty documentation on Internet Explorer, which is the likely reason behind of the problem…"
I think all this talk about letting Microsoft define the standards is pretty funny.
Microsoft likes to patent things, it’s one of their revenue plans. So then we lose the ability to have "free" browsers (Ie isn’t free, you pay for it with Windows) because Microsoft requires that you license their patents and if their current such licenses are any indication they will preclude use in open source browsers like Mozilla/Firefox/Konqueror and possibly even Safari on the Apple platform due to it’s KHTML core.
I’m a web developer, and when I write a site in current valid XHTML/CSS it works in Firefox, Netscape, Mozilla, Safari, Konqueror etc. It requires CSS fixes to work properly in Internet Explorer though. The IE developers have already agreed to fix some of these bugs so why are we all argueing about it? I just want to be able to write a page and have it look and function the same in all modern browsers, and possibly the next generation of browsing devices like Nokia’s new web tablet and smartphones/pda’s.
You might like to go back to bloated table layouts and the like but I’d like to go forwards if it’s ok with you.
The IE guys are trying to fix the bugs, so lets let then get on with it and stop the pointless arguing.
Also, keep in mind that if Xerox had patented the GUI, would OSX and XP exist now? If the guys that invented TCP/IP had been unable to reach a standard argreement would the Internet exist now?
Anyone that thinks standards are not important needs their head read. In case you haven’t heard Microsoft don’t own the Internet, they don’t even own most of it. If they did then they could set the standards however they liked but the fact is that they don’t.
As a web developer it annoys me no end to hear all the zealots here going on about how the standards don’t matter and Microsoft should just go nuts making stuff up. It annoyes me cos I’m worried the MS developers might listen and make the situation worse then it is. When it comes to that stage, I will write a basic txt only version of a web site and set the server up to deliver it to IE users. Microsoft doesn’t own the billions of pages out there either, if they did we’d not be having this discussion. And if enough of those users served IE a basic text page instead of the full experiance then I’d imagine Firefox’s market share would sky rocket over night.
I actually feel somewhat sorry for the IE developers, they are probably very good programmers, and could write a very good browser, but most likely have to tow the company line when it comes to interoperability, patentability and all that other jazz. I imagine that it will take Microsoft being found guilty of anti-competitive behaviour in Asia and possibly china before they start realising that having 88% of the browser market stitched up doesn’t mean they own the Internet. Well, we have had two guilty verdicts for anti-competitive behaviour, US and EU, and microsoft is spending billions trying to settle lawsuits like Sun and Novell, and yet for every one they settle, two more pop up. Eventually even Bill and Steve must reach the conclusion that they can’t all be wrong and that perhaps they should look at their own SOP with regards to interoperability.
Personally I’d like to see IBM open source OS2 and make it a valid Win32/64 platform for client machines, then they have Linux on the server and OS2 on the client. I don’t want Windows or Microsoft to go away, I just want them to start playing nice with others with regards to interoperability.
A recent case of MS not playing nicely is the SenderID framework, they based it on an open standard, SPF and tacked on their own stuff, after patenting it and licencing it in a manner that makes it unusuable to the Internets most predominant Mail servers. (Sendmail/Postfix/Qmail)
If they hadn’t done that, if they had said, "well Spam is a bigger issue then our need to be incompatible, so lets make this an open stardard" then we’d all be getting less spam now. And what if SPF had been patented? SenderID would then having noting to sit on top of.
Like I said, Microsoft is all gung ho for patenting ideas as a means to generate revenue and lock out competitors, even when their own patented technology runs on top of a standard that somebody else came up with and gave away in order to reduce the spam problem.
So sure, tout the benefits of a Microsoft Internet if you like, but while your loading your IE coded pages to a Unix/Linux server running Apache (who after all have about 70% of the worlds web server software market) that if Apache took the same aproach as Microsoft, all pages served from apache would add an adendum to the bottom of every page telling them to get Firefox.
I’m raving now, thanks very much. Standards… we need them. I’m sick of the IE CSS box model hacks and the fact that I must use proprietry jpg’s/gifs because microsoft didn’t see the need to support the free versions properly.
Oh, and with regards to the moz- additions, their name makes it obvious what they are, mozilla specific code. I’d like to see all of MS’s such code be labelled msie- because then I’d know not to use it on any site that has users on other browsers or platforms, just like I don’t use moz- features on sites where I know users are IE.
Good luck with IE7 guys. Pleaes listen more to your develper nature rather then your MS project manager when coding for it.
rgds
Franki
Chloe,
Unbelievable!
"It’s obvious to the most casual observer that Firefox UI is orders of magnitude better than that of IE6, but that is (relatively) minor to correct. After which, there will be no compelling reason to use it. "
You don’t actually know what’s in the works for browsers in the future – I expect you don’t claim to be a medium?
A browser of Firefox calibre would have been reached much sooner were it not for IE being preloaded on unsuspecting users computers, and then being left to stagnate.
Netscape was almost completely destroyed by this strategy (well done Microsoft) – except that it was considered illegal.
"PS If there are any Netscape browser developers reading this, your UI is pathetic."
IEs UI is abhorrent.
."
VML and SVG do not prevent flash from working – where did you get that idea?
Oh and the CSS "extension"? Nice try, but Gecko is used for laying out the entire UI, not just the web pages. How else would you propose styling the UI elements?
"It’s time for MS to impose their authority. "
MS doesn’t have any authority on web technology, only an illegally obtained (but shrinking) monopoly.
."
This is totally bogus. Most web designers aim at IE, Netscape, Safari and Opera. Many include others, like Konqueror. Just because you’d rather not bother doesn’t mean you’re in the majority.
Plus you’re angry at the wrong party. IE is the REASON that web pages need tweaking. It’s relatively simple to create web pages with HTML/CSS and have it work on compliant browsers without tweaking.
Only IE is the fly in the ointment.
Plus standards are important to other user agents. For blind people, for example. Web pages that adhere to the standards work well for those readers, but pages designed for IE are horrible. So thanks again MS.
"Even widespread standards don’t actually work – they always have leaks in their specs. No two implementations will be the same, and if developers are forced to run to the W3C every time they have a question no-one would get anything done."
Many specs in many industries prove you wrong.
Take Java. JVMs by Sun, IBM and Blackdown. Many others. All work.
Compliance is tested.
The only major vendor to release a non-compliant JVM? MS. hmmmm….
"Fortunately I trust Microsoft to base their decisions firmly on economic principles rather than idealism."
Nice, but MS doesn’t base their decisions on YOUR or MY welfare or economic advantage: only their own, and that of their shareholders – of course.
The fact is the IE wouldn’t be a player if it had had to compete on merit alone. (And the two "hads" is intended and correct)
YAWN!
Netscape 8.0.2 solves this problem. Couldn’t tell if it was posted through all the ranting.
> It’s obvious to the most casual observer that Firefox
> UI is orders of magnitude better than that of IE6, but
> that is (relatively) minor to correct. After which,
> there will be no compelling reason to use it.
I agree – after Firefox becomes another two orders of magnitude better than IE there really will be no reason at all to use IE.
ML
He said the new version will be built on the work they did in SP2, and other things. Gates mentioned they will go further to defend IE users from phishing and other deceptive
|
https://blogs.msdn.microsoft.com/ie/2005/05/25/netscape-8-and-internet-explorers-xml-rendering/
|
CC-MAIN-2017-09
|
refinedweb
| 20,230
| 72.16
|
A Unity ID allows you to buy and/or subscribe to Unity products and services, shop in the Asset Store and participate
in the Unity community.
Hello.
Any plans for make InputSystemUIInputModule extensible ?
for example:
public class MyCustomModuleTest : InputSystemUIInputModule
{...
@cassandraL, That's is cool. You are welcome :)
Hello @cassandraL
I mean adding packages to a subcategories (like hierarchy window).
For example, transfer all 2D packages to the 2D category...
Hello.
Can you planning the packages groups for a better organizations Package Manager packages ?
[IMG]
Dear developers.
Working with large scenes and assing fields in scripts are so hard and unbearably.
Can you add Editor scene pipette like...
Same issue. I reinstalled hub and it not help.
Unity HUB 2.0.4 not showing Unity 2019.1.11
BUMP
I have Same Problem. Any comments from devs?
Unity 2019.1.1.f1
EditorTools.activeToolChanging and EditorTools.activeToolChanged are missing
But this code works for me
// CustomEditor tool...
What about "update" button for installed Unity versions?
Currently for install new version of Unity we need to manually remove old and install new...
Hello. I use older Spine plugin, Unity 5.4b21, Unity Cloud Build and have some errors while building game for iPhone and android
Log text:...
Hi. I play you game and see some bugs in console after loading first level.
I fixed the problem. Wrong provision file and P12 .
Thx for reply. Log to long and i cut.
Hi. Please help me.
I can not build of my application.I keep getting an error when a build of iOS.
Unity 5.2 with vuforia 5.0.5. Repo -...
[IMG]
Hello everyone!
We are the young independent game development studio. We invite you to play in our first and very fascinating game called...
+1
I have this problem too
|
https://forum.unity.com/search/111938324/
|
CC-MAIN-2019-43
|
refinedweb
| 298
| 63.05
|
persian_fonts 1.0.3
persian_fonts: ^1.0.3 copied to clipboard
persian_fonts #
A Flutter package for using free persian fonts.
The
persian_fonts package for Flutter allows you to easily use any free persian fonts in your app.
Getting Started #
Currently,
PersianFonts supports 4 types of fonts: Vazir, Samim, Shabnam and Sahel. yours isn't hrere? add it!
First, add the
persian_fonts package to your pubsec dependencies.
To import
PersianFonts:
import 'package:persian_fonts/persian_fonts.dart';
To use
PersianFonts as the default TextStyle:
Text( 'These are persian fonts.', style: PersianFonts.Samim, ),
To use
PersianFonts with a customized TextStyle:
Text( 'These are persian fonts.', style: PersianFonts.Samim.copyWith( ... ), ),
You can also use
PersianFonts to make or modify an entire text theme to use one of the supported fonts:
MaterialApp( theme: ThemeData( textTheme: PersianFonts.vazirTextTheme, ), );
|
https://pub.dev/packages/persian_fonts
|
CC-MAIN-2021-25
|
refinedweb
| 131
| 50.94
|
No events, no activities in the field. How can your sales team still win new business?22. April 2020
Email Service Provider – Little movement in a fragmented market18. August 2020
Executing complex projects in Salesforce Marketing Cloud with SSJS
From design pattern to test-driven development
Modern web development requires a good code structure and should involve a test-driven development process. The tests to be written should ideally achieve test coverage of 100 per cent – only this ensures that the software will continue to run when modifications are made to the code in functions (changes to requests, refactoring, etc.). Common programming languages, in conjunction with appropriate frameworks, make the work of developers significantly easier and also provide corresponding test frameworks. At Publicare, we use test frameworks like this in Laravel (PHP, PHPUnit), vue.js, APEX (Salesforce) and golang.
For example, if someone wants to initiate deployment processes in Salesforce Sales Cloud using APEX code, they can’t avoid writing tests. If a minimum test coverage prescribed by Salesforce is not met, or the tests fail, the deployment will come to a screeching halt.
But it’s different in Salesforce Marketing Cloud. The programming languages there, AMPScript and SSJS, and the available platform libraries do not support test-driven development. There are also no requirements to write tests, either within CloudPages or automation scripts. The code required within the platform could theoretically be considered as not being very complex. But, practically speaking, development in Salesforce Marketing Cloud has a professional minimum standard in terms of approach and quality. There are multiple reasons for this:
- Errors in processes lead to potential data losses, for example in newsletter registrations, unsubscribing from mailing lists or transfers to third-party systems.
- Badly structured code presents problems in keeping track of changes to customer requests, which means it has to be completely redeveloped.
- Performance bottlenecks are difficult to detect in a messy “spaghetti code”.
- Maintaining this kind of code is complex and costly.
To avoid all of this, or to minimize the risk as much as possible, we also use test-driven development in Salesforce Marketing Cloud. But what can we actually do within the platform and, above all, how can we do justice to our own standards of professionalism with SSJS – a language that is based on the ECMA3 specifications published in December 1999 and that is therefore a relic from the last millennium? As a digital marketing agency, this question has been keeping us busy ever since our first project in Salesforce Marketing Cloud. Time and time again, we’ve adapted our own design patterns in this area and implemented them in a platform-specific way. The following key elements have supported us in implementing test-driven development.
DRY – Don’t Repeat Yourself
We structure code in the Marketing Cloud in an object-oriented way, but without ongoing inheritance. In this instance, objects are a cluster of methods and aim to make the paradigms or approaches more comprehensible when reading the code. To give an example: we often use a “controller” object (objects created by us begin with a “_” in the code, to avoid any naming conflicts later in the process). The controller possesses functions for processing requests (reading parameters, mapping parameters against a data extension, etc.). Because we use this object more often in CloudPages, which we employ in projects, we do not reimplement the object in each CloudPage. However, if there were a bug or a change needed for some other reason, we would have to manually update each CloudPage, which requires both time and patience.
Instead, we implement the reusable code in code snippets and ensure it is imported in CloudPages. This means we only have to make changes to the code in one place. The imports are similar to their equivalent in golang:
import (
“fmt”
“github.com/badoux/checkmail”
“github.com/devfacet/gocmd”
)
or the equivalent in PHP
use AppAbstractsDataExtensionDescriptionJob;
use AppBusinessUnit;
use AppData Extension;
use AppMarketingCloudReadDataExtensionReader;
This is also the first step in testing the code. Were we to work exclusively via copy and paste, we’d be unable to eliminate errors and would have no idea what a professional code-based test scenario needs to look like.
Make It Configurable
It’s assumed that you have to write a method for filtering contact data out of a data extension. In the context of SOAP, in order to do this, it’s necessary to explicitly specify the columns being accessed. This is no problem given that the method isn’t difficult to implement. The ID, EmailAddress, FirstName and LastName columns are entered as arrays in the request, as is the CustomerKey of the data extension. But in the next step, the written code is transferred to an additional business unit of the customer, which would also like to access the functionalities. However, in this second business unit, the columns to be called up are ID, EmailAddress and City, and the CustomerKey of the data extension is of course different. From this point on, you would have a method with two different paths across the various business units, although the intention of the method is always the same – from a code perspective, they are two parallel tracks. “n” further business units may also be added down the line.
From a maintenance perspective, this approach is clumsy; it’s better to work with variables. Here, both the CustomerKey of the data extension and the columns being queried become configuration variables in the code snippet; so, the path of the method remains the same. When deploying to other BUs, only one configuration variable must be modified per BU; the rest can be adopted as is.
These configuration variables are a critical component for testing database operations within the scope of test-driven development in Salesforce Marketing Cloud.
Test-Driven-Development
The execution of the first two patterns, “DRY – Don’t Repeat Yourself” and “Make It Configurable”, also allow us to adapt test-driven development as effectively as possible. Because we don’t have a terminal, we instead need to opt for implementation within CloudPages and express our test cases visually – if it’s green, it’s good
With the first pattern, “DRY – Don’t Repeat Yourself”, we’re able to integrate the code base already used by the other CloudPages in the test suite CloudPage. If something in the code base changes, the tests must continue to run successfully – or the changes will be defective too. By the way: to be able to execute changes like these without disrupting live operations, we save each version of the code base elements. A new version must first be validated by the test suite before it can be integrated by the controllers.
Because we share the URL of the test suite CloudPage and the tests can be initiated by any project participant at any time, it would make no sense to run data extension-based tests against the live database. But unfortunately, Salesforce Marketing Cloud does not understand the concept of live database versus test database. These kinds of distinctions simply don’t exist. This is where the “Make It Configurable” pattern helps. Before we request methods in the test suite for tests, we ensure that the configuration variables of the data extensions used are overwritten – so instead of potentially live data extensions, we use a model of the actual data extensions for testing purposes during development. This is also an extremely useful way to debug processes without disrupting live operations.
Everything else is then “normal” development work: writing methods, and developing and executing tests for them. From our perspective, this form of development is extremely reassuring: the better we write the tests, the more certain we can be that our software fulfils its purpose. However, if we test complex processes manually (which took a long time before the tools in Salesforce Marketing Cloud were created), it’s not only stressful (because it often requires many mouse clicks), it’s also extremely time-consuming – because with every change, the test must be restarted from the beginning to look for potential crossover effects.
But what should we do about special logic in individual business units?
One potential weak point, when modelling cross-business unit methods, are the exceptions from the rule. To enable us to model cross-business unit methods despite special logic, we’ve chosen to implement event objects. An event can occur in a method. It consists of an event name and an event data object, with both transferred from the method to the fire method of the event. From a method perspective, nothing more is needed. For example:
_Event.fire(“Contact.subscribed”, {Contact: Contact})
If the process is concluded in business unit A, but there is a request in business unit B to send a welcome email to the contact, shared use of the method code remains possible. In business unit B, code is added – a “listener” – which stands in an additional code snippet. A listener is a function that responds to to an event with a specific name. Each event can have a limitless number of listeners. In the code snippet, the listener and its callback function must be registered with the corresponding event:
var listenerFunction = function(eventData) {
var Contact = eventData.Contact,
//… logic here
}
_Event.addListener(“Contact.subscribed”, listenerFunction)
A welcome email will then be triggered in this listener and dispatched to the address of the contact.
This principle might seem straightforward, but it also provides plenty of leeway for modelling code across different business units because you work out the similarities and then process the specific characteristics for each event.
Outlook
In addition to the patterns described here, we have developed a range of other working methods that influence the approach we use to implement individual extensions in Salesforce Marketing Cloud. We strive throughout for a professional, modern and, above all, reliable implementation.
A well-structured code is the basis for every effective process. Projects in Salesforce Marketing Cloud will also be able to accommodate any recurring change requests from clients if they are clearly coded – which significantly simplifies maintenance and optimization of these processes.
If you would like to know more about this topic or are looking for professional services in this area, we’d be happy to advise you.
|
https://publicare.de/en/blog/executing-complex-projects-in-salesforce-marketing-cloud-with-ssjs/
|
CC-MAIN-2021-31
|
refinedweb
| 1,712
| 50.67
|
I previously posted a 1080p dynamic streaming demo. In case you’d like to customize this for your own demo or website, here is the source code (Flash CS4 required). Enjoy!
Monthly Archives: July 2009
New RTMPe content protection white paper
A).
Flash Builder 4 Tutorial 2: RESTful Services
Many things have changed in Flex 4 and with the new Flash Builder 4 Beta, you can already start trying these out. This little tutorial will walk you through a simple FB4 HTTP Service example to explain the differences. If you want to do this, download the Flash Builder 4 Beta.
First – there are multiple new namespaces in Flash Builder 4. These appear to be confusing at first but you should not be scared by them.
Fx is for the Flash Catalyst packages and contains some new drawing primitives and more. Some of the old namespace qualified elements are now qualified including Script..
Another major change is that many non-visual components of an application must be bound by the element. You might notice if you are trying to declare an HTTP service, the will not auto-complete unless bound by the declarations tag. If you want to manually build this project, you can add an HTTPService like this:
A third thing you will see is that the layouts are no longer contained in the header. Instead, they are declared inside a
container as shown below:. onto the middle of your application. If you manually add it in Code view, just start typing the angle bracket and “datagrid” and let Flash Builder complete this for you.
9. Highlight the DataGrid, then right-click (Control Click on Mac) the DataGrid object and select Bind To Data from the men
u.
Free Flex Builder 3 for Unemployed Developers
Even
New Fireworks CS4-Flash Catalyst Integration
If.
AIR contest for developers or students living in Romania
We […]
LiveCycle DS 3 beta integrates with Flash Builder 4
The beta version of Adobe LiveCycle Data Services 3 delivers many new features and improvements. One particularly exciting feature is a new technology, code named Fiber, which enables Flex developers to use a model-driven development approach for faster and easier data-driven application development. With Fiber, data management is implicitly supported and does not require developers to create custom assemblers or employ complicated LiveCycle Data Services specific configurations. And as part of Flash Builder 4 beta, Flex developers can easily create a fiber Model to simplify development and enhance productivity of data-driven Flex applications.
For an overview of the features included in the next release, view the Getting Started videos or read Anil Channappa’s What’s New in LiveCycle Data Services 3..
Join me in San Jose Aug 19th and explore Adobe LiveCycle and the Flash Platform
If_2<<
Integrating […]
|
https://blogs.adobe.com/digitalmedia/2009/07/
|
CC-MAIN-2018-17
|
refinedweb
| 464
| 52.29
|
Details
Description
Currently if I have a table that contains clob/blob column, import/export operations on that table
throghs unsupported feature exception.
set schema iep;
set schema iep;
create table ntype(a int , ct CLOB(1024));
create table ntype1(bt BLOB(1024) , a int);
call SYSCS_UTIL.SYSCS_EXPORT_TABLE ('iep', 'ntype' , 'extinout/ntype.dat' ,
null, null, null) ;
ERROR XIE0B: Column 'CT' in the table is of type CLOB, it is not supported by th
e import/export feature.
Issue Links
- is blocked by
DERBY-2864 LOB import unexpectedly succeeds on corrupt data
- Open
- is related to
DERBY-2859 Misleading error message if you supply too many arguments to SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE
- Open
DERBY-2860 Documentation problems for IMPORT/EXPORT LOBs feature
- Closed
- relates to
DERBY-2527 Add documentation for import/export of LOBS and other binary data types.
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
Some thoughts on implementing import/export for large objects.
related discussion on the derby-dev list:
Import uses VTI to import data into a table from a file. Just found out
that derby does not support CLOB/BLOB data types with VTI. Any one remember
why these types are not supported ?
Currently all the columns in the import file are treated as VARCHAR type and
cast them to the appropriate column type of the table, when the insert
statement is generated. For example to import into a table T4(
create table t4( a int , b char(100)) );
INSERT INTO "T4"("A", "B") --DERBY-PROPERTIES insertMode=bulkInsert
SELECT cast(COLUMN1 AS INTEGER) , COLUMN2 from new org.apache.derby.impl.load
d.Import('c:/suresht/databases/emp.dat',null,null,null, 2 ) AS importvti ;
Clob types column can casted from VARCHAR type, performance may be bad but it will work.
Problem with blob data type is, it can be casted from any other type.
I am kind of stuck on how to extract the binary data from an import file and insert
into the table using the VTI, without VTI support for CLOB/BLOB types.
types.
Any ideas/suggestions ?
Thanks
-suresh
For reading from a VTI I'm not sure why CLOB and BLOB are not supported. SQLBlob seems to contain the correct code in its setValueFromResultSet(). It might be a hangover from the time the codebase supported JDK 1.1 and java.sql.Blobs were not available. It might be simply the work was never done. What error do you get?
For setting BLOB/CLOB into a VTI it might be tricker, since it requires the SQL layer to be able to manufacture a java.sql.Blob object, and since they are JDBC objects the language doesn't handle them. Though it's a simiar problem to BLOBs in triggers/functions and I think at least for triggers it works, so I think there is a mechanism for creating a java.sql.Blob from a BLOB column.
and having written that, I thought BLOBs were used in triggers and triggers used VTIs ...
Thanks for the input Dan. When I specify the column type for import VTI as Types.BLOB , I got the following error :
"The external virtual table interface does not support BLOB or CLOB columns. ''{0}
'' column ''{1}
''. "
This error is coming from impl/sql/compile/FromVti.java
if( columnType == Types.BLOB || columnType == Types.CLOB)
throw StandardException.newException(SQLState.LANG_VTI_BLOB_CLOB_UNSUPPORTED,
getVTIName(), rsmd.getColumnName( i));
I will check out triggers with BLOBS.
DERBY -378 (partial)
This patch adds some code required to support import/export of table with
clob, blob(large objects) data types. Clob/Blobs data can be exported to
an external file that different from the main export file. Location of the
lob data in the external file will be written to the main export file.
When writing the lob data to an external file, no conversion is done for the
binary data , clob data will be written using the user specified code set.
1)This patch implements following two new procedure to support
exporting LOBS to an external file name:
SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_IN_EXTFILE(..)
SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_IN_EXTFILE(..)
2)This patch implements following two new procedure that allow
import of large object data stored in a external file.
(for example exported previously using the above export procedures).
SYSCS_UTIL.SYSCS_IMPORT_DATA_LOBS_IN_EXTFILE(...)
SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_IN_EXTFILE(..)
3) import/export of table with clob,blob types will also work
with single input/output file, using the exiting import/export
procedures. In this can binary data is converted into hex format before
exporting and the data hex is converted to binary on import.
Clob data is exported similar to other char types.
Tests: derbyall/junitall test suites passed on Windows XP/JDK142, except
for the known failures.
Each blob/clob goes into its own separate external file? Or all the blobs/clobs go into a single external file?
> Each blob/clob goes into its own separate external file? Or all the blobs/clobs go into a single external file?
> [ Show » ] Bryan Pendleton [24/Feb/07 05:15 PM]
All the blobs/clobs go into a single external file.
I haven't actually reviewed the code at all, but I was just wondering about the names for the new procedures. When I first looked at them use of the "IN_EXTFILE" sounded a tad awkward to me (esp. for export). I instinctively thought "...TO_EXTFILE" would be better for export and "FROM_EXTFILE" would be better for import. But then I realized that such names could potentially cause confusion (ex. If I'm importing lobs from EXTFILE does that mean there is other, non-lob data in EXTFILE that I'm not importing?) So those probably aren't much better.
The only other thing that comes to mind is "USING_EXTFILE", but again, I don't know if that's really any better. Perhaps "IN_EXTFILE" is in fact best because it's generic and it's short, in which case please feel free to leave the procedure names as they are. I just thought I'd mention that on first reading the names seemed slightly odd, in case you or anyone else can come up with other suggestions.
NOTE: I do not think this little comment should block commit of the patch. This is a pretty minor thing and could easily be changed as part of a follow-up patch when (and if) a different set of names is chosen.
Committed derby_378.diff to trunk on revision 512109. If there are any review comments related to this patch , I will address them in the future patches for this issue.
DERBY -378 (partial)
This patch adds code required to support import/export of a table with
CHAR FOR BIT DATA, VARCHAR FOR BIT DATA, LONG VARCHAR FOR BIT DATA
data types. Data of this type of columns is exported to the main export
file as hex strings. On import data is also expected to be in hex strings
in the main export file for these type of columns. This patch also
disallows use of hex decimal characters (0-9 , a-f , A-F) as
delimiters for import/export procedures.
Maximum data length of these types is only 32700 ( 254 bytes for CHAR FOR
BIT DATA , 32,672 for VARCHAR FOR BIT DATA and 32700 LONG VARCHAR FOR BIT DATA). Because max length allowed is less than 32k, I think providing import/Export
using an external file for these types may not add much value. No external
file support will be provided for these types. It can be added later,
if some one thinks it is required.
Tests:
Added a new junit test to test the import/export of these binary types.
It would be great if someone can review this patch.
Looks good, couple of minor questions:
1) I see use of StringUtil.fromHexString() in the patch, but no use of StringUtil.toHexString() in the patch. How does the exporting work?
2) If the input to StringUtil.fromHexString() is malformed by its length not being a multiple of two then null will be silently inserted. Should import throw an exception here?
These could be addressed after the patch is committed.
Thanks for taking time to review , Dan.
> 1) I see use of StringUtil.fromHexString() in the patch, but no use of StringUtil.toHexString() in the patch. How does the exporting work?
Export calls Resultset.getString() method for these types also. getString() method
return the data in hex format, by calling StringUtil.toHexString().
> 2) If the input to StringUtil.fromHexString() is malformed by its length not being a multiple of two then null will be silently inserted. Should import throw an exception here?
Good Catch. inserting nulls on malformed hex strings is bad. I will add a
a check for the return value from StringUtil.fromHexString() , and throw an
exception if it is null.
Committed derby378_2.diff to trunk on revision 515708..
DERBY -378 (partial)
This patch checks for invalid hex strings in the import file
while performing import into a table with CHAR FOR BIT DATA,
VARCHAR FOR BIT DATA, LONG VARCHAR FOR BIT DATA data types.
Import will throw an exception if it detects any invalid hex
strings during import.
Tests:
Added a new junit test case to ImportExportBinaryDataTest.java
to test for the invalid hex strings in the import file.
DERBY-378 (partial)
This patch adds code to handles NULL (SQL NULL) data while
performing import/export of table with column types blob, clob.
Checks for invalid hex strings in the import file while performing
import into a table with Blob column. Import will throw an exception
if it detects any invalid hex strings in the import file for blob column.
Tests:
1) Added a new junit test ImportExportLobTest.java to
tests import/export of clobs and blob data.
2) Wrapped BufferInputStream/BufferedReader around the streams
used in BaseJDBCTestCase.java:assertEquals() methods to compare
clobs/blobs. Without buffering these assert method were really slow.
DERBY-378 (partial)
This patch adds some code required to support import/exoprt of lob data.
1) Addded code to read clob data using getCharacterStream()
instead of getString() while importing clob data from an extern file.
(Note: Clobs are read using getString() until DERBY-2465 is fixed).
2) Made some code changes to make each lob column has it it's own file handle to
the lob file to read the data, otherwise streams can get corrupted when
there are more than one clob/blob type column in the table.
A comment on Army's comment on names. I don't have strong feelings, I also thought using TO for export and FROM for import was more natural. I do think you should check with laura and see if these names are going to cause documentation issues because they are too long, I don't remember her ever saying what the problem length was.
Thanks for the feedback Army & Mike. I agree with both of you ,
LOBS_FROM_EXTFILE/LOBS_TO_EXTFILE sounds better than
"LOBS_IN_EXTFILE". Unless someone else has a better
suggestions. New procedure names will be :
SYSCS_UTIL.SYSCS_EXPORT_TABLE_LOBS_TO_EXTFILE(..)
SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE(..)
2)This patch implements following two new procedure that allow
import of large object data stored in a external file.
(for example exported previously using the above export procedures).
SYSCS_UTIL.SYSCS_IMPORT_DATA_LOBS_FROM_EXTFILE(...)
SYSCS_UTIL.SYSCS_IMPORT_TABLE_LOBS_FROM_EXTFILE(..)
–
One another other thing I was debating myself was whether
to use "EXTFILE" or "SEPFILE". Sticking with "EXTFILE",
"SEPFILE" does not seem any better.
These procedure names are fine with me. The names are clear (Export To and Import From),
and they stay under 50 characters including underscores and the period (just barely
More than 50 can cause real problems in the PDF output. The name can get truncated.
I'm assuming the EXTFILE refers to External File, as opposed to a separate file?
I think EXTFILE is better too.
Thanks for the feedback Laura. Incase of export "EXTFILE" is used
to indicate lob data is not stored in the main export file along with
other table data, but in a different file specified by the user. And incase of
import it indicates lobs data is in a different file, and the reference to
it is stored in the import file specified by the user.
Suresh is there a spec for me to look at for this issue?
I'd like to understand the documentation hits.
Thanks for your interest to document this issue Laura. Intially proposed spec is attached to this jira (iexlobs.txt) , but it is out of date. I will update the spec and post it in a day or two.
updated the spec and added some notes for dcoumnentation.
I agree with Suresh. There needs to be a way to import and export data from clobs/blobs.
|
https://issues.apache.org/jira/browse/DERBY-378
|
CC-MAIN-2017-09
|
refinedweb
| 2,097
| 66.13
|
13. What is the result of attempting to compile and run the following public class? public class ErrorTester throws Throwable{ public static void main(String args[]) { System.out.println("Hello World");} } a) The class will not compile. b) The class will compile but not run c) The class will compile and run but with no output d) The class will compile and run with the expected output Option a) is correct. The problem with this code is the fact that the throws clause is on the class, not the main method. Only methods can declare that they throw an exception, not a class. As a result, this method does not compile. This is a pretty blatant coding error, but sometimes, when you really get deep into the SCJP questions, an obvious coding error can be difficult to spot, so be careful!
Originally posted by Jelle Klap: The source code for question 4 is messed up:
10. What is the result of attempting to compile and run the following class with the input of 123?
|
http://www.coderanch.com/t/269568/java-programmer-SCJP/certification/Runtime-Compile-Time-SCJP-Mock
|
CC-MAIN-2014-42
|
refinedweb
| 174
| 71.14
|
Asked by:
Unable to Connect Remote Configuration Manager Console
I am having an issue that is similiar in nature to others where the Admin Console for 2012 is unable to connect to the database with the following displayed from the console.
Here is the catch: I have approx 50 users all which have their own desktops using the admin console to connect. Almost all users are able to connect. (Leads me to believe the site servers are ok) Specifically so far two users can not connect, I have logged on as myself and verified that I too can not connect from those machines either, but can from other machines. I then had the users logon to other machines and voila they were able to logon. This really now points to s specific issue with these desktops.
I checked the SMSAdminUI.log files on both machines and I found they were reporting two different things:
User1 Log:
[1, PID:2368][01/23/2013 10:35:46] :Insufficient privilege to connect, error: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'\r\nSystem.UnauthorizedAccessException\r\nAccess is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))\r\n at System.Management.ThreadDispatch.Start()
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementObjectSearcher.Initialize()
at System.Management.ManagementObjectSearcher.Get()
at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlConnectionManager.Connect(String configMgrServerPath)
at Microsoft.ConfigurationManagement.AdminConsole.SmsSiteConnectionNode.GetConnectionManagerInstance(String connectionManagerInstance)\r\n
User2 Log:
[1, PID:5148][01/24/2013 12:18:53] :The performance counter '# images' was not found
[4, PID:5148][01/24/2013 12:18:53] :The performance counter '# result objects in memory' was not found
[4, PID:5148][01/24/2013 12:18:53] :The performance counter '# exceptions' was not found
[4, PID:5148][01/24/2013 12:18:54] :The performance counter '# exceptions' was not found
[4, PID:5148][01/24/2013 12:18:54] :The performance counter '# result objects in memory' was not found
[4, PID:5148][01/24/2013 12:18:54] :The performance counter '# exceptions' was not found
[5, PID:5148][01/24/2013 12:18:57] :The performance counter '# images' was not found
[1, PID:5148][01/24/2013 12:18:58] :The performance counter '# images' was not found
Checked the event viewer nothing unusual..........
I have reviewed the steps to correct which are below and all of them check out! I am at a total loss of what to look for or at next......Any help would be appreciated.
Validate the errors in the AdminUI.log that is stored <Path where SCCM is installed>\Microsoft Configuration Manager\AdminConsole\AdminUILog Check the event viewer for any specific errors. Perform the below steps for generic issues:
1.Ensure DCOM is active
a. Expand Component services > Computers > Right click My Computer and go to
"Properties".
b.Make sure that "Enable Distributed COM on this computer" is selected.
2.Validate the DCOM Permission
a.From the Start menu, click Run and type Dcomcnfg.exe.
b.In Component Services, click Console root, expand Component Services, expand Computers, and then click My Computer. On the Action menu, click Properties.
c.In the My Computer Properties dialog box, on the COM Security tab, in the Launch and Activation Permissions section, click Edit Limits.
d.In the Launch Permissions dialog box, click Add.
e.In the Select User, Computers, or Groups dialog box, in the Enter the object names to select (examples): box, type SMS Admins and click OK.
f.In the Permissions for SMS Admins section, select the check box to allow Remote Activation.
g.Click OK twice, and then close Computer Management
3.Verify WMI Permission
a.
On the SMS Provider computer, click Start, click Run, type wmimgmt.msc, and then click OK.
b.
Right-click WMI Control, and then click Properties.
c.
On the Security tab, expand Root, and then click SMS.
d.
Click Security in the results pane to see the permissions.
e.
Click Advanced, click SMS Admins, and then click View-edit.
f.
If the SMS Admins group does not have Enable Account and Remote Enable permissions, grant the permissions.
g.
Repeat this procedure for any groups used in addition to SMS Admins
4.Check whether the user has the necessary privileges to the SMS provider on the site server
5.Check whether the user has the necessary security rights to the database?
6.Verify namespace connectivity
a.
On the computer where the SMS Provider is installed, click Start, click Run, and then type wbemtest.
b.
Click Connect, type , and then click Login.
c.
Click Enum Classes, click Recursive, and then click OK.
d.
In the Query Result list, double-click SMS_ProviderLocation.
e.
Click Instances, and then double-click the line that contains the target site code. For example, SMS_ProviderLocation.SiteCode="ABC."
f.
In the Properties section, locate the NamespacePath line. You might have to double-click this line to see the whole line.
g.
Copy the NamespacePath value to the clipboard. For example, copy the following value:
h.
7.To verify server connectivity
a.
Close all WBEMtest windows from the preceding procedure.
b.
Click Connect, paste the NamespacePath that you copied in the preceding procedure, and then click Login.
c.
Click Enum Classes, click Recursive, and then click OK.
d.
In the Query Result list, double-click SMS_Site.
8.Verify the SMS Provider details
a.Open sms\bin\i386\smsprov.mof and validate the following text in the mof file
b.instance of SMS_ProviderLocation
c.{
d.SiteCode = "ABC"; -- here ABC refers to 3 digit side code
e.Machine = "CAS Server name";
f.NamespacePath = "";
g.ProviderForLocalSite = TRUE;
h.;
9.Rebuild the namespaces:
a.
Recompiling the mofs located in the sms\bin\i386 directory will rebuild the namespace.
b.
This has to be done on the site server itself. Open a command prompt and go to the sms\bin\i386 directory. Once there, enter the following commands:
1.mofcomp smsprov.mof
2.mofcomp smsstub.mof
3.mofcomp pollprov.mof
4.mofcomp netdisc.mof
5.mofcomp cpprov.mof
6.mofcomp cmprov.mof
Question
All replies
Yes, I know this is an old post, but I’m trying to clean them up. Did you solve this problem, if so what was the solution?
This sound like a firewall issue. I would start by disabling the firewall and seeing if you can connect. If this works then you know where the problem is,
Garth Jones | My blogs: Enhansoft and Old Blog site | Twitter: @GarthMJ
- Proposed as answer by Garth JonesMVP, Moderator Saturday, April 18, 2015 2:06 PM
|
https://social.technet.microsoft.com/Forums/en-US/7e0576dd-e588-403f-8af9-698f730d6813/unable-to-connect-remote-configuration-manager-console?forum=configmanagergeneral
|
CC-MAIN-2015-22
|
refinedweb
| 1,080
| 59.3
|
Unable to create a contour_plot of a system of inequalities
asked 2016-07-16 14:30:45 -0500
This post is a wiki. Anyone with karma >750 is welcome to improve it.
I am trying to plot a system of inequalities, dependent on a matrix H. Here is my function I am planning to contour_plot:
def reg(x, y): f1 = H[0,0] * H[0,0] * x + H[1,0] * H[1,0] * y f2 = H[0,0] * H[0,1] * x + H[1,0] * H[1,1] * y f3 = H[0,1] * H[0,1] * x + H[1,1] * H[1,1] * y if f1 < 0 or f2 < 0 or f3 < 0: return 0 else: return 1
I then have H be
> H > [2.220446049250313e-16 -0.9999999999999998] > [ -0.9999999999999998 2.220446049250313e-16]
However
contour_plot(reg, (x,-Integer(5),Integer(5)), (y,-Integer(5),Integer(5)))
yields an error. It says
zero-size array to reduction operation minimum which has no identity
The strange part is that when
> H > [-1 0] > [ 0 1]
the same contour_plot yields exactly what I want without any errors
Help would be much appreciated, I have just picked up SAGE this week and have much to learn
Thanks for reporting !
|
https://ask.sagemath.org/question/34111/unable-to-create-a-contour_plot-of-a-system-of-inequalities/?sort=latest
|
CC-MAIN-2019-22
|
refinedweb
| 206
| 61.19
|
Can designing a good key is that “we should be able to retrieve the value object back from the map without failure“, otherwise no matter how fancy data structure you build, it will be of no use. To decide that we have created a good key, we MUST know that “how HashMap works?”. I will leave, how hashmap works, part on you to read from linked post, but in summary it works on principle of Hashing.
Learn how HashMap works in java
Key’s hash code is used primarily in conjunction to its
equals() method, for putting a key in map and then getting it back from map. So, our only focus point is these two methods. So if hash code of key object changes after we have put a key value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak.
On runtime, JVM computes hash code for each object and provide it on demand. When we modify an object’s state, JVM set a flag that object is modified and hash code must be AGAIN computed. So, next time you call object’s
hashCode() method, JVM recalculate the hash code for that object.
2. Make HashMap key object immutable
For above basic reasoning, key objects are suggested to be IMMUTABLE. Immutability allows you to get same hash code every time, for a key object. So it actually solves most of the problems in one go. Also, this class must honor the hashCode() and equals() methods contract.
This is the main reason why immutable classes like
String,
Integer or other wrapper classes are a good key object candidate. and it is the answer to question why string is popular hashmap key in java?
How to make a class immutable. But, you must make sure you are honoring the contract with equals() also.
3. HashMap custom key object example
An example is always better for demonstration, right? Then lets have one.
In this example, I have created an
Account class with only two fields for simplicity. I have overridden the hashcode and equals method such that it uses only account number to verify the uniqueness of Account object. All other possible attributes of
Account class can be changed on runtime.
package com.howtodoinjava.demo.map;; } }
Will this cause any undesired behavior???
NO, it will not. The reason is that
Account class’s implementation honor the contract that “Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.” i.e.
- Whenever a.equals(b) is true, then a.hashCode() must be same as b.hashCode().
- Whenever a.equals(b) is false, then a.hashCode() may/may not be same as b.hashCode().
4. Test the HashMap custom key object
Lets test our
Account class for above analysis.
package com.howtodoinjava.demo.map; import java.util.HashMap; public class TestMutableKey { public static void main(String[] args) { //Create a HashMap with mutable key HashMap<Account, String> map = new HashMap<Account, String>(); //Create key 1 Account a1 = new Account(1); a1.setHolderName("A_ONE"); //Create key 2 Account a2 = new Account(2); a2.setHolderName("A_TWO"); //Put mutable key and value in map map.put(a1, a1.getHolderName()); map.put(a2, a2.getHolderName()); //Change the keys state so hash map should be calculated again a1.setHolderName("Defaulter"); a2.setHolderName("Bankrupt"); //Success !! We are able to get back the values System.out.println(map.get(a1)); //Prints A_ONE System.out.println(map.get(a2)); //Prints A_TWO //Try with newly created key with same account number Account a3 = new Account(1); a3.setHolderName("A_THREE"); //Success !! We are still able to get back the value for account number 1 System.out.println(map.get(a3)); //Prints A_ONE } }
Program Output.
A_ONE A_TWO A_ONE
This is my understanding on designing custom key object for HashMap. If you disagree or feel otherwise, please drop me a comment.
Happy Learning !!
References:
how to do hashmap value object (is my approach correct ), I have written this code, how to get the city details,
My csv file contains these data,
city,city_ascii,lat,lng,country,iso2,iso3,admin_name,capital,population,id
Malishevë,Malisheve,42.4822,20.7458,Kosovo,XK,XKS,Malishevë,admin,,1901597212
Prizren,Prizren,42.2139,20.7397,Kosovo,XK,XKS,Prizren,admin,,1901360309
Zubin Potok,Zubin Potok,42.9144,20.6897,Kosovo,XK,XKS,Zubin Potok,admin,,1901608808
Kamenicë,Kamenice,42.5781,21.5803,Kosovo,XK,XKS,Kamenicë,admin,,1901851592
Viti,Viti,42.3214,21.3583,Kosovo,XK,XKS,Viti,admin,,1901328795
Shtërpcë,Shterpce,42.2394,21.0272,Kosovo,XK,XKS,Shtërpcë,admin,,1901828239
________________________
___________________________
pretty deep and difficult to understand in one go.
but great article, thanks for the information.
Save my day! Thanks Lokesh!
How do you access values of a hashmap in a class from a different class in Java? please help!
Awesome..felling that I m learning hashmap now..
Hi Lokesh,
One more point to add to the answer is not using the transient variables in hashCode()
If the object is serailized, it would get default value for transient variable instead of instance value , making it impossible to locate
Hi Lokesh,
could you plz explain me below doubts ?
if HashMap key is a String object/user defined class obj then how the hashcode generates ?
HashMap hm= new HashMap();
hm.put(21, 121);
normally hashcode calulates : key %capacity = 21%4= 1 // suppose my Initial capacity is 4 and it will tore @ index position 1
same way want to know how it calculates for a String and userdefined class as a key ..
Interview questions:
what is the output
System.out.println(employeeObjectMap.size());
System.out.println(employeeObjectMap.get(employee3));
MapSize :1 as every time it generates same hashcode so same bucket is use for out opeation.
As equals always returns false it wont be able to get the object from map.
MapSize will be number of put operations you do as every time it generates same hashcode so same bucket is use for out opeation but since equals method returns false every time it stores in different entry of map.
As equals always returns false it wont be able to get the object from map.
please ignore my first answer
is equals methods compare each key on the same bucket and if keys are equal then replace the values to the recent keys value?
please explain how equal method works in hashmap?
In Hash map equals method works on keys. Generally Hash code is may same or may not same for two different keys. if hash code is same and and the index is same but keys are different In this case hash map create a linked list and stores the values at the next node of present key value pair
This article is very informative.. Thank you very much..
above hashcode method :
final int prime = 31;
int result = 1;
result = prime * result + accountNumber;
return result;
is same as :
return 31 * accountNumber;
Any reason why you wrote those 4 lines?
No. You are right that it could be one line code also. But if you have multiple fields in hashCode() calculation then It will be easy to change them method as below :
To avoid any unforced error as reassigning value to accountNumber, It’s better if we make the field “accountNumber” final.
To avoid any unforced error as reassigning accountNumber a new value,It would be better if you make “accountNumber” final
i think it is important that neither equals nor hashcode should change when changing the state of object. In your example, if I have hashcode on the basis of account number and equals on the basis of account number and holder name, then neither property can be changed if you a reliable key is required for map.
Absolutely true. Agree “that neither equals nor hashcode should change when changing the state of object.”
can you please elaborate?.. Dint get it..
If hashcode and equals will change after inserting the ‘key’ object in map, you will not get same ‘value’ object from map.. and even you may loose the value object all together thus causing memory leak.
I had run your sample programme but it will not correctly run
Any particular problem you see?
Very good one.Thanks Lokesh
Nice post.
In #33, you are setting for value for a1 but I guess you might be interested in setting value for a3.
Assume that, I have included holdername in equals method and I put the a3 in the same map. Then the above code will return “A_THREE” because after matching the hashcode, it will use the equals to identify the correct key. Please correct me if I am not
Typo corrected. Yes, you are right.
Hi.. I included holdername in equals method and then put a3 in the same map . I got null as output for a3 as key.
If i include holdername in hash code as well then i get null for all the three keys. Can you please mention as to how will I get “A_THREE “as value for a3 as key.
apologies… i made a mistake. yes u are right.
Never mind.
Hi Lokesh, Can u help me in understanding the output following program. Why the output is different in the below two cases?
Just to help others reading this: Output of above program is –
World
Hello
In your first part of program, you created an instance of
Testand set it’s value to “Hello”. After inserting this instance in map, you used the same reference to change the value to “World”. So value got changed.
In second part of program, you created instance of
StringBufferand set value to “Hello”. BUT, now you created another instance of
StringBufferand assigned the reference to variable
sb. Please note that after changing the reference,
sbdoes not point to first
StringBufferinstance, rather it points to second instance. So any operation you does using
sbnow, does not affect the instance inside map. So when you fetch it from map, it’s unchanged.
If you really want to change the value, then do not assign the reference of new
StringBufferto
sb, rather simply use
sb.append()method.
Now output will be:
World
HelloWorld
Hey well explained, but I am not clear about immutability. Since you told at the start how to create immutable class. I dont see it you above example. Am I missing anything here ?
Please read the linked post:
Is the last println line correct in TestMutableKey??
we have not added a3 obj into map, so how can we retrieve it?
Hi Ajay,
As far I I understand, both a1 and a3 would produce same hascode and also equals method wouldl return true since both account numbers are same. That are the only two things HashMap will check before returning a value object from the map.
What if I would like both values in the account class to be immutable? Like the account number and the holder name would have to be equal for the objects to be equal? How does this change the hashcode and equals methods?
Nice Article
1.) when a hashcode value is calculated , this value happens to be some memory address on the heap. What is the guarantee OR how hashMap ensures that the hashcode that will be calculated will be a free mem area(the same mem area is not being used by some other program)
2.) Although internally objects will be stored in a transient Entry[]. Is it that this array which is a datastructure with contiguous mem locations will already claim its space on the heap, once declared and then the bucket allocation happens from within this transient array.
Kindly help on the above 2 questions
1) NO, hashcode is not same as memory address. Rather it’s kind of representation of memory address. For default hashCode() method, JVM derives the value from the value of the reference to the object. So, first object is created in memory and then hashcode is calculated.
2) Yes you are right.
Can i do the same hascode implementation with String, as u did with integer value(Acc no)? If so how?what should be the code inside hashcode?
You can use StringVar.hashCode() in your hashCode implementation.
Very good post. It clearly explains
Most important thing to know about HashMap is it’s data structures and algorithms used to write this class. As name of class(HashMap) is indicating that its works on hashing mechanism. This class basically uses two data structures, one is Array and other is Linked-List. HashMap internally create Array of Entry type objects. Entry is an inner class used by HashMap to stores Key and Value type’s objects. To place an Entry object in array, we need an index at which that object can store in array. This index is generated by hash code of key object provide by user. Hash code of key object can get by hashCode() method of key object. After knowing index, Entry object can place in array. These array indexes are known as bucket. Now if you want to retrieve any object from HashMap, you need to provide key for that. This is key object gives hash code, this hash code generates an index and now at this index you have your object.
If you want to read more about HashMap [Click Here]
Can u explain more why it becomes null if we don’t override hashcode and equals
In this case, Account a3 = new Account(1); creates an object whose hashcode will be different from a1. We have not put a3 in map, so it’s not available to matched with a1.
If we override hashcode and equals then a3 is matched with a1 due to same account number, and a1 is returned.
Hi, I have not implemented hashcode() and equals() methods and the output is:
A_ONE
A_TWO
null
I have changed the accountNumber field to String, still get the same output
A_ONE
A_TWO
null
String being immutable, should the output be different?
No, both account objects are separate.
Nice article .I really enjoyed all your articles.I have one request, could you please explain ThreadLocal .I tried understanding but not able to implement it practically. It will be very helpful.
I will write a post soon. By the time, you would like to read a practical example of Thread local:
This is only acceptable if you are okay with the mutable parts of the class being unimportant for seeing if two instances of the class are “equal”. Many people might be thrown off by the idea of them changing something and seeing that it is still considered equal to something that it was equal to before. This is not neccessarily a bad thing, but you should probably state in the documentation that certain parts aren’t factored into its equality.
Fair enough.
I get the same value even if I don’t override hashcode or equals? WHY
If you do not override the hashcode and equals function, output will be:
A_ONE
A_TWO
null
Which is different from above program.
Hi Lokesh,
if in this case as we are not overriding the hashcode and equal method,and we are changing object state i.e.(mutable key) then how its is fetching the values A_ONE
A_TWO ?
That’s before modifying the keys. After modifying, it’s null.
here account a1 always returns same hashcode even after setting the name.
Is that mean its not necessary that hashcode will change incase we are changing state of mutable class (Provided we are not override the method)
YOU ROCK MAN!
Very clearly explain.
Best article i ever read on this topic…..
Nice article man, keep up the good work !!!
Hi Lokesh,
Can you can explain hashmap get(), with example , i tried so many time times but i have some little bit confusion,
Have you gone through how hashmap works?
|
https://howtodoinjava.com/java/collections/hashmap/design-good-key-for-hashmap/
|
CC-MAIN-2020-05
|
refinedweb
| 2,656
| 73.17
|
> On Tuesday 26 May 2009 07:52:36 pm Paul Kendall wrote: >>. >> > Latest patch included, I also also changed the parser to that when it returns > packets it sets the codec_id to CODEC_ID_AAC, which means that the AAC codec > is used. Please help me to understand: latm_find_frame_end is called with a AVPacket read from a Stream. What is if the size of the Packet is smaller than a frame? +static int latm_find_frame_end(AVCodecParserContext *s1, const uint8_t *buf, + int buf_size) +{ + LATMParseContext *s = s1->priv_data; + ParseContext *pc = &s->pc; + int pic_found, i; + uint32_t state; + + pic_found = pc->frame_start_found; + state = pc->state; + + for (i = 0; !pic_found && i < buf_size; i++) { + state = (state<<8) | buf[i]; + if ((state & LATM_MASK) == LATM_HEADER) { + pic_found = 1; + s->count = i - 2; + break; + } + } + + if (pic_found) { + /* EOF considered as end of frame */ + if (buf_size == 0) + return 0; + if ((state & LATM_SIZE_MASK) + s->count + 3 <= buf_size) { if the Packet is smaller (buf_size is the size of the Packet) then "(state & LATM_SIZE_MASK) + s->count + 3 <= buf_size" can not be true? + pc->frame_start_found = 0; + pc->state = -1; + return (state & LATM_SIZE_MASK) + s->count + 3; thanks Peter
|
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-May/076107.html
|
CC-MAIN-2015-06
|
refinedweb
| 178
| 56.29
|
. You then start
the thread and call
Go, so two separate threads
are running
Go in parallel. However, there’s
a problem: both threads share a common resource—the console. If
you run
ThreadTest, you get output something like
this:
abcdabcdefghijklmnopqrsefghjiklmnopqrstuvwxyztuvwxyz
Thread synchronization comprises techniques for ensuring that multiple threads coordinate their access to shared resources.
C# provides the
lock
statement to ensure that only one thread
at a time can access a block of code. Consider the following example:
using System; using System.Threading; class LockTest { static void Main( ) { LockTest lt = new LockTest ( ); Thread t = new Thread(new ThreadStart(lt.Go)); t.Start( ); lt.Go( ); } void Go( ) { lock(this) for ( char c='a'; c<='z'; c++) Console.Write(c); } }
Running
LockTest produces the following output:
abcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyz
The
lock statement acquires ...
No credit card required
|
https://www.oreilly.com/library/view/c-essentials/0596000790/ch03s08.html
|
CC-MAIN-2019-30
|
refinedweb
| 135
| 57.67
|
This is a
playground to test code. It runs a full
Node.js environment and already has all of
npm’s 400,000 packages pre-installed, including
jss-default-unit with all
npm packages installed. Try it out:
require()any package directly from npm
awaitany promise instead of using callbacks (example)
This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.
Provide plain numeric values in your JSS style definitions, and the plugin will insert the apposite units. Defaults to
px for sizes,
ms for durations, and
% for transform origins, and these can be customized easily (see Usage Example).
Make sure you read how to use plugins in general.
import jss from 'jss' import defaultUnit from 'jss-default-unit' // Optionally you can customize default units. const options = { 'line-height': 'rem', 'font-size': 'rem' } jss.use(defaultUnit(options))
const styles = { container: { 'line-height': 3, 'font-size': 1.7, 'height': 200, 'z-index': 1 } }
Compiles to:
.container-sdf345 { line-height: 3rem; font-size: 1.7rem; height: 200px; z-index: 1; }
File a bug against cssinjs/jss prefixed with [jss-default-unit].
npm i npm run test
MIT
|
https://npm.runkit.com/jss-default-unit
|
CC-MAIN-2020-24
|
refinedweb
| 192
| 59.4
|
Q_DECLARE_TYPEINFO and namespaces - how does it work?
I've used Q_DECLARE_TYPEINFO before on classes that I didn't put into any specific namespace, and never had any problems.
Now I have a class that should be in a specific namespace, something like this:
@#include <QTypeInfo>
namespace MYNAMESPACE
{
class MyClass
{
public:
MyClass();
int data;
};
} // namespace MYNAMESPACE@
How do I declare the typeinfo of this class?
If I put the Q_DECLARE_TYPEINFO inside the namespace brackets, I get the error "error: specialization of 'template<class T> class QTypeInfo' in different namespace"
If I put the Q_DECLARE_TYPEINFO after the namespace brackets (now declaring the typeinfo for MYNAMESPACE::MyClass), I get the error "error: expected unqualified-id before 'namespace'" in my corresponding cpp file, which looks like this:
@#include "myclass.h"
namespace MYNAMESPACE
{
MyClass::MyClass()
{
}
} // namespace MYNAMESPACE
@
How is this done correctly?
I've already check these two cases with MSVS2010 and they works fine.
Do your forget a semicolon sign before @#include <QTypeInfo>@?
I'm testing on Creator with MinGW.
#include <QTypeInfo> is the first line. Why should there be a semicolon before?
Ok, tested it on VS2010 as well.
Case 1 (inside namespace bracket) actually works on VS2010.
Case 2: I did forget the semicolon after the Q_DECLARE_TYPEINFO. This case now works on both compilers. Thanks!
|
https://forum.qt.io/topic/20558/q_declare_typeinfo-and-namespaces-how-does-it-work
|
CC-MAIN-2017-34
|
refinedweb
| 213
| 56.66
|
- Article Catalog
- How to set up and run first part of the series that demonstrates how to set up Jupyter Notebook environment with Docker to consume and display financial data from Refinitiv Data Platform without need to install the steps above. The article covers Jupyter with the Python programming language. If you are using R, please see the second article. Scipy-Notebook Image
You can run the following command to pull a jupyter/scipy-notebook image (tag 70178b8e48d7) and starts a container running a Jupyter Notebook server in your machine.
docker run -p 8888:8888 --name notebook -v <your working directory>:/home/jovyan/work -e JUPYTER_ENABLE_LAB=yes --env-file .env -it jupyter/scipy
Requesting ESG Data from RDP APIs
The jupyter/scipy-notebook image is suitable for building a notebook or dashboard with the Refinitiv Data Platform APIs (RDP APIs) content. You can request data from RDP APIs with the HTTP library, perform data analysis and then plot a graph with built-in Python libraries.
What is Refinitiv Data Platform (RDP) APIs?
The Refinitiv Data Platform (RDP) APIs provide various Refinitiv data and content for developers via an.
The example notebook of this scenario is the rdp_apis_notebook.ipynb example notebook file on the GitHub repository /python/notebook folder. To run this rdp_apis_notebook.ipynb example notebook, you just create a .env file in /python/ folder with the RDP credentials and endpoints information, and then run jupyter/scipy-notebook image to start a Jupyter server with the following command in /python/ folder.
docker run -p 8888:8888 --name notebook -v <project /python/notebook/ directory>:/home/jovyan/work -e JUPYTER_ENABLE_LAB=yes --env-file .env -it jupyter/scipy-notebook:70178b8e48d7
The above command started a container name notebook and mounted /python/notebook/ folder to container's /home/jovyan/work directory. Once you have opened the notebook server URL in a web browser, the rdp_apis_notebook.ipynb example notebook will be available in the work directory of the Jupyter. The rdp_apis_notebook.ipynb example notebook uses the built-in libraries in the image to authenticate with the RDP Auth Service and request Environmental Social and Governance (ESG) data from RDP ESG Service to plot a graph. You can run through each step of the notebook. All activities you have done with the file will be saved for a later run too.
Please see the full detail regarding how to run this example notebook on the How to run the Jupyter Docker Scipy-Notebook section.
The rdp_apis_notebook.ipynb notebook workflow is identical to the example notebook on my How to separate your credentials, secrets, and configurations from your source code with environment variables article. It sends the HTTP request message to the RDP APIs Auth service to get the RDP APIs access token. Once it receives an access token, it requests ESG (Environmental, Social, and Governance) data from the RDP APIs ESG service.
How to change Container User
The Jupyter Docker Stacks images are a Linux container that runs the Jupyter server for you. The default notebook user (nb_user) of the Jupyter server is always jovyan and the home directory is always home/jovyan. However, you can change a notebook user to someone else based on your preference via the following container's options.
docker run -e CHOWN_HOME=yes --user root -e NB_USER=<User> <project /python/notebook/ directory>:/<User>/jovyan/work
Example with wasinw user.
docker run -p 8888:8888 --name notebook -e CHOWN_HOME=yes --user root -e NB_USER=wasinw -v C:\drive_d\Project\Code\notebook_docker\python\notebook:/home/wasinw/work -e JUPYTER_ENABLE_LAB=yes --env-file .env jupyter/scipy-notebook:70178b8e48d7
Now the notebook user is wasinw and the working directory is /home/wasinw/work folder.
Please note that this example project uses jovyan as a default notebook user.
How to use other Python Libraries
If you are using the libraries that do not come with the jupyter/scipy-notebook Docker image such as the Plotly Python library, you can install them directly via the notebook shell with both pip and conda/mamba tools.
Example with pip:
import sys
!$sys.executable -m pip install plotly
Example with conda:
import sys
!conda install --yes --prefix {sys.prefix}.
The Jupyter Docker Stacks let developers create their Dockerfile with an instruction to install the Python dependencies via mamba, pip, and conda package management tools. Please see more detail on the Using mamba install or pip install in a Child Docker image page.
Example with Refinitiv Data via Refinitiv Data Platform Library and Plotly
Let's demonstrate with the Refinitiv Data Platform Library for Python (RDP Library for Python) and Plotly libraries.
Introduction to Refinitiv Data Platform (RDP) Libraries
Refinitiv provides a wide range of contents and data which require multiple technologies, delivery mechanisms, data formats, and multiple APIs to access each content. The RDP Libraries are a suite of ease-of-use interfaces providing unified access to streaming and non-streaming data services offered within the Refinitiv Data Platform (RDP). The Libraries simplified how to access data to various delivery modes such as Request-Response, Streaming, Bulk File, and Queues via a single library.
For more deep detail regarding the RDP Libraries, please refer to the following articles and tutorials:
- Developer Article: Discover our Refinitiv Data Platform Library part 1.
- Developer Article: Discover our Refinitiv Data Platform Library part 2.
- Refinitiv Data Platform Libraries Document: An Introduction page.
Disclaimer
As this example project has been tested on alpha versions 1.0.0.a10 of the Python library, the method signatures, data formats, etc are subject to change.
Firstly create a requirements.txt file in a /python/ folder with the following content:
plotly==5.2.2
refinitiv-dataplatform==1.0.0a10
Next, create a Dockerfile file in a /python/ folder with the following content:
# Start from a core stack version
FROM jupyter/scipy-notebook:70178b8e48d7
LABEL maintainer="Your name and email address"
# Install from requirements.txt file
COPY --chown=${NB_UID}:${NB_GID} requirements.txt /tmp/
RUN pip install --quiet --no-cache-dir --requirement /tmp/requirements.txt && \
fix-permissions "${CONDA_DIR}" && \
fix-permissions "/home/${NB_USER}"
ENV JUPYTER_ENABLE_LAB=yes
Please noticed that a Dockerfile set ENV JUPYTER_ENABLE_LAB=yes environment variable, so all containers that are generated from this image will run the JupyterLab application by default.
And then build a Docker image name jupyter_rdp_plotly with the following command:
docker build . -t jupyter_rdp_plotly
Once the Docker image is built successfully, you can the following command to starts a container running a Jupyter Notebook server with all Python libraries that are defined in a requirements.txt file and jupyter/scipy-notebook in your machine.
docker run -p 8888:8888 --name notebook -v <project /python/notebook/ directory>:/home/jovyan/work --env-file .env -it jupyter_rdp_plotly
Please noticed that all credentials have been passed to the Jupyter server's environment variables via Docker run -env-file .env option, so the notebook can access those configurations via os.getenv() method. Developers do not need to keep credentials information in the notebook source code.
Then you can start to create notebook applications that consume content from Refinitiv with the RDP Library API, and then plot data with the Plotly library. Please see more detail in the rdp_library_plotly_notebook.ipynb example notebook file on the GitHub repository /python/notebook folder. Please see the full detail regarding how to run this example notebook on the How to build and run the Jupyter Docker Scipy-Notebook customize's image with RDP Library for Python and Plotly section.
The rdp_library_plotly_notebook.ipynb workflow starts by initializing the RDP session.
Then the notebook requests the historical data from the RDP platform using RDP Libraries Function Layer, and plots that historical data to be a multi-lines graph with the Plotly express object.
Caution: You should add .env (and .env.example), Jupyter checkpoints, cache, config, etc. files to the .dockerignore file to avoid adding them to a public Docker Hub repository.
What if I use Eikon Data API?
If you are using the Eikon Data API (aka DAPI), the Jupyter Docker Stacks are not for in the same machine that running the Eikon Data API, and the Refinitiv Workspace/Eikon application does not support Docker.
However, you can access the CodeBook, the cloud-hosted Jupyter Notebook development environment for Python scripting from the application. The CodeBook is natively available in Refinitiv Workspace and Eikon as an app (no installation required!!), providing access to Refinitiv APIs and other popular Python libraries that are already pre-installed on the cloud. The list of pre-installed libraries is available in the Codebook's Libraries&Extensions.md file.
Please see more detail regarding the CodeBook app in this Use Eikon Data API or RDP Library in Python in CodeBook on Web Browser Getting Start with Refinitiv Data Platform article Scipy-Notebook
Firstly, open the project folder in the command prompt and go to the python Scipy-Notebook image and run its container.
docker run -p 8888:8888 --name notebook -v <project /python/notebook/ directory>:/home/jovyan/work -e JUPYTER_ENABLE_LAB=yes --env-file .env -it jupyter/scipy-notebook:70178b8e48d7
The Jupyter Docker Scipy-Notebook will run the Jupyter server and print the server URL in a console, click on that URL to open the JupyterLab application in the web browser.
Finally, open the work folder and open rdp_apis_notebook.ipynb example notebook file, then run through each notebook cell.
How to build and run the Jupyter Docker Scipy-Notebook customized image with RDP Library for Python and Plotly
Firstly, open the project folder in the command prompt and go to the python subfolder. Then create a file name .env in that folder with the following content. You can skip this step if you already did it in the Scipy-Notebook run section above.
# RDP Core Credentials
RDP_USER=<Your RDP User>
RDP_PASSWORD=<Your RDP Password>
RDP_APP_KEY=<Your RDP App Key>
docker build . -t jupyter_rdp_plotly
Once Docker build the image success, run the following command to start a container
docker run -p 8888:8888 --name notebook -v <project /python/notebook/ directory>:/home/jovyan/work --env-file .env -it jupyter_rdp_plotly
The jupyter_rdp_plotly container will run the Jupyter server and print the server URL in a console, click on that URL to open the JupyterLab application in the web browser.
Open the work folder and open rdp_library already contain.
- Discover our Refinitiv Data Platform Library (part 1).
- Discover our Refinitiv Data Platform Library (part 2).
- Plotly Official page.
- Plotly Python page.
- Plotly Express page
- Plotly Graph Objects page
- Jupyter Docker Stacks page
- Jupyter Docker Stack on DockerHub website.
- How to set up and run R Data Science Development Environment with Jupyter on Docker
For any questions related to Refinitiv Data Platform or Refinitiv Data Platform Libraries, please use the following forums on the Developers Community Q&A page.
GitHub
Related Articles
- How to separate your credentials, secrets, and configurations from your source code with environment variables
|
https://developers.uat.refinitiv.com/en/article-catalog/article/how-to-set-up-and-run-data-science-development-environment-with-
|
CC-MAIN-2022-27
|
refinedweb
| 1,796
| 54.12
|
- Products
- Solutions
- API & Docs
Sending text messages during a phone call is a useful way to give users content for offline reference, or even confirm an sms subscription.
In this demonstration, we are going to describe how to build an application that can initiate an SMS message from a phone call.
If you haven't already, take a look through the Twilio SMS Quickstart which explains in further detail all the functionality available in Twilio's SMS API.
This demo is written in Python for Google App Engine. This code can be adapted for other Python web frameworks such as Django.
This demo utilizes TwiML, with a focus on the
<SMS> verb.
A Caller will dial into a Twilio number and be prompted to confirm their subscription. Once they confirm their sms subscription, a confirmation SMS message will be sent back to them.
If you have further questions about Twilio SMS be sure to check out the faq.
When a call is answered by Twilio, Twilio fetches the '/' page which is configured to query the GatherPage object.
application = webapp.WSGIApplication([ \ ('/', GatherPage), ('/confirm',. Prompts the user to confirm their SMS subscription. Say is wrapped in a Gather verb to collect a digit from the caller. The Gather will post the results to /confirm """ def get(self): self.post() def post(self): templatevalues = { 'postprefix': BASE_URL, } xml_response(self, 'gather.xml', templatevalues)
Here is the template used to render the initial TwiML greeting. Twilio then prompts the caller to confirm their subscription by pressing 1.
<?xml version="1.0" encoding="UTF-8"?> <Response> <Gather method="POST" numDigits="5" action="confirm"> <Say>Please confirm your SMS subscriptiong by pressing 1.</Say> </Gather> </Response>
When the caller confirms their subscription, Twilio performs an HTTP POST with the results back to the 'action' handler. The 'action' handler is '' in the current application.
If the caller pressed 1, the phone number is added to the list of subscribed callers.
def post(self): tplvars = {} confirm = self.request.get('Digits') if not confirm: self._error("We could not confirm your subscription.", BASE_URL) return # strip off extra digits and keys from the Digits we got back confirm = confirm.replace('#', '').replace('*', '')[:1] if confirm != "1": self._error("We could not confirm your subscription.", BASE_URL) return subscriber = Subscriber() subscriber.number = self.request.get('Caller') subscriber.put() xml_response(self, 'confirm.xml', tplvars)
The final response is generated and sends back a confirmation sms.
You can see that an
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Thank you for subscribing, you should receive a confirmation message in a moment.</Say> <Sms> Thank you for subscribing. This message confirms your subscription to. This is an example SMS response from twilio.com. </Sms> <Say>Goodbye</Say> <Hangup/> </Response>
Twilio sends an SMS with the text specified to the caller.
And that's it! The rest of the code is input validation and error handling.
For an overview of all the Twilio SMS API features, take a read through the SMS Quickstart
|
http://www.twilio.com/docs/howto/send-sms-in-call
|
CC-MAIN-2015-11
|
refinedweb
| 496
| 59.7
|
Continuing the line of my submissions for the idiot question of the decade award, my next (and I truly believe, best yet) attempt goes as follows...
I have (been told I have) a requirement for a module that, when inherited from, will...
The first is/was fairly trivial - via judicious use of a parameterised import routine initialising a package scoped hash and an AUTOLOAD routine using said package variable to categorise uncaught method calls.
The latter requirement wasn't/isn't set out in stone, so shouldn't be a problem either way, as for the middle requirement, well that is, as thay say, another matter entirely...
My initial reaction was to pre-judge a set of likely constructor names and parse the inheriting package for any sub(s) by one of these names. I hacked together a .t script containing a number of package declarations, which when run, passed all tests - at this point, I didn't/couldn't suss WTF was going on.
Shortly thereafter, my co-process gifted me a copy of Perl Hacks, and whilst reading #47, I guessed that B::Deparse (about which I knew nothing) may be put to use in my particular problem.
Soooo, without any further thought at all (as will become/is already obvious), my initial reaction was to attempt to rewrite import to utilise said module against all subs/methods in the inheriting class.
The module was re-visited, along with its test harness and I was (admittedly, not entirely unexpectedly) disappointed to observe that some of the tests failed.
Eventually, it dawned on me that the successful tests all involved packages declared in-line in the .t script, or put another way, the tests that failed involved the use/require of a separate package file...
Anyone seen the root cause of the problem yet (which is more than I had;-) ?
Yep, that's right, at the time a package->import is called by the compiler, only the BEGIN block/sub exists in the inheriting class when it [the inheriting class] is implemented as a disparate package file - the compiler is busy determining dependencies and preloading the symbol table ready to begin the ascent of compiling the package itself.
.oO(Surely I should've seen that ages ago - DOH!!!)
My current thinking (or what passes for it in my world) is that I probably need to beg/borrow/steal, or possibly write, a module that acts as an inheritable compile pragma to any sub-class - unless you know better...:-)
So come on, you are cordially invited to make the most of this opportunity to support my candidacy for the above award...
TIA & rgds to all ,
Exit, stage left, a goon show fan that wishes he'd chosen the more apposite PM user name of Eccles...as in 'Mad Dan'
I'm not sure I follow what you're trying to do, but my reading reminds me of BEGIN, UNITCHECK, CHECK, INIT, and END blocks, which I also don't fully understand.
If you want to ensure that there are no other constructors before you, I don't think you'll have much luck. Any code any where can bless into your class and cross its digits in hopes that nothing goes wrong.
I could imagine perhaps a new() method that notes its results (with weak references, of course) in a lexical hash. Then other methods in the class can check up on the objects they're called on in this table of "allowed" objects and throw a tantrum if a transgression is detected. There would be a performance penalty, of course. Also, you can't stop someone from "subclassing" via delegation. Such an object could even override UNIVERSAL::isa so as to pretend to be your object.
So what are you really trying to gain here? What is the rationale behind these requirements? What do you want to protect yourself against?
Thanx for your insight - looks like UNITCHECK or, probably, CHECK would be the way to go.
Way to go kyle :-))
Update
Thinking about it, using the CHECK block would be best as it's also run when using perl -c .... Something like the following would possibly suffice (based on code supplied elsewhere in the thread 702588)...
CHECK {
my $dp = B::Deparse->new();
while (my ($pkg, $hash) = each %INTERFACES) {
while (my ($var, $glob) = each %{"${pkg}::"}) {
next unless defined &$glob;
croak "Constructor detected: ${pkg}::$var" if
$dp->coderef2text(\&{"${pkg}::$var"}) =~ /\bbless\b/;
}
}
}
[download]
Further Update
Corrected typo (missing trailing slash) in RE
Some of that sounds a bit off. Taking just the first-
Fully support abstract methods in as much as a call to a non-overridden abstract (by design) method causes the code to croak or otherwise blow up
...
The first is/was fairly trivial - via judicious use of a parameterised import routine initialising a package scoped hash and an AUTOLOAD routine using said package variable to categorise uncaught method calls.
Methods (object oriented code) should have no use for import, and AUTOLOAD is not for doing abstract parent methods. For those, you just write/stub the method with the croak/die/confess in it. That way any successful call has to have come from a subclass. Maybe you're doing something different but the way it sounds, it sounds like you're going about coding up your specs entirely wrong. :(
... sounds like my description wasn't the best in the world.
import is used solely for the (pure abstract) inheritor to define the interface it expects its inheritors to implement.
AUTOLOAD is used solely to catch unimplemented methods, mutators etc. and provide a categorised croak.
In outline, the implementation was along the following lines (I'm afraid I havn't got the actual code to hand at the moment - it's on a memory stick @ work & I'm working from home at the time of writing - doncha just hate it when that happens)...
package AbstractBase;
use strict;
use warnings;
use Carp qw/confess/;
use Storable qw/dclone/;
my %DEF_INTERFACE = (
methods => [],
mutators => [],
);
use vars qw/%INTERFACES/;
sub import {
my ($self, $caller) = (shift, caller);
%INTERFACES{$caller} = dclone { (%DEF_INTERFACE), @_ };
}
sub AUTOLOAD {
my $self = shift;
(my $method = $AUTOLOAD) =~ s/(.*::)//;
my $interface = $INTERFACES{$1};
croak "Abstract method not instantiated: $method" if
grep /^$method$/, @{$interface->{methods}};
croak "Mutator method not instantiated: $method" if
grep /^$method$/, @{$interface->{mutators}};
croak "Undefined interface component: $method";
}
[download]
That being said, IMO, you don't tend to learn much if you havn't been thro' the pain.
The "abstract" ness you are looking for can be done mostly by using Moose::Role, you can find links to a number of talks/slides that discuss roles in more detail here. And if you have further questions feel free to join the mailing list (moose@perl.org) and/or IRC (#moose@irc.perl.org).
Hell yes!
Definitely not
I guess so
I guess not
Results (41 votes),
past polls
|
http://www.perlmonks.org/index.pl?node_id=702435
|
CC-MAIN-2014-52
|
refinedweb
| 1,148
| 58.11
|
Redesigning the Loyc tree code07 May 2013
This post was imported from blogspot.The original (and current) design for the classes that represent Loyc trees has some problematic properties:
- You can't tell if a node is mutable or immutable without a runtime check.
- Green nodes are hard to work with because they use relative positioning.
- Red nodes (the Node class) are hard to work with because they have parents.
- The "f" part of "f(x)" is not (in general) an independent node--although it could be.
However, the original design does not benefit from type safety. You cannot say "this method requires a mutable tree" or "this method requires an immutable tree". It's non-obvious when a method takes or returns a "Node", what exactly that means.
I created an optionally-persistent hash-set recently that overcomes this problem by having two separate data types for mutable and immutable sets: Set<T> (immutable) and MSet<T> (mutable); both of these are wrappers around a helper data type InternalSet<T> which contains the algorithms, and the user can convert a set from mutable to immutable (or vice versa) in O(1) time, so I've been considering doing something comparable for Loyc nodes.
Parenting is another problem. My current implementation is inspired by Roslyn and has two kinds of nodes, green and red, the meaning of which is explained by Eric Lippert on his blog. The green nodes are cachable, so that for example the subtree for "Console.WriteLine" can be re-used to save memory if it appears in multiple places in a source file; they also use relative positioning to help support incremental parsing if I ever get around to implementing that. These factors allow Loyc trees to be very lightweight, but the latter fact makes it very hard to manipulate green trees without losing all information about positioning (or worse, causing some calculated positions to be incorrect). Therefore, end-users are generally supposed to use red nodes instead of green ones, leaving green nodes mainly as carefully-constructed products of the parser.
However, each red node has a parent, and this turns out to be very inconvenient when transforming syntax trees. Each node can only have a single parent, and if you insert a Node that has a parent as a child of another Node, you get an InvalidOperationException. The compiler cannot help detect the problem, and correcting the problem requires that you first "detach" the Node from its parent. To make matters worse, detaching is an O(N) operation (in general) because the array of Nodes in the parent has to be shifted left (after the spot where the detached Node used to be); plus, if the Node's parent is frozen, detaching causes a ReadOnlyException. Now, you don't actually have to detach; you can clone the node instead, but cloning all over the place could also hurt performance.
The way I have defined Loyc trees also makes me slightly uncomfortable. Recall that a node essentially has three parts:
- The attribute list (may be empty)
- The head (one of: a Symbol, a literal Value, or a Head node)
- The argument list (optional, and if present, may be empty)
A couple of things make me uncomfortable about #2, the head portion. First of all, a call such as "f(x)" normally consists of two nodes: the call "f(x)" is one Node, and the symbol "x" is another Node. "f" is not a Node but merely a Symbol. The advantage of this representation is that it saves memory, since a separate Node does not have to be allocated for "f", we only need memory for the Symbol "f", and this memory is shared every time "f" appears in any source file. But I can certainly imagine that you might want to do something with "just the head part" of a node, ignoring the argument list and the attributes; for example you might want to print "just the head part" as a string, and there is no convenient way to do this right now.
A second problem is that there is a weird oddity in the code right now, because the Head part can be a Node rather than a Symbol, and my code currently treats the Node "f" as equivalent to the Symbol "f". This makes me uncomfortable because Loyc trees are not fully round-trippable like they are supposed to be; if you take the tree "f(x)" where "f" is a Node, print it as text and re-parse it, the output is "f(x)" where "f" is a Symbol--a slightly different tree that prints out the same way.
An alternative way to interpret this case is that if a Node serves as a Head and has no attributes or arguments, it should be interpreted as being in parenthesis. In that case, when "f" is a Node serving as a Head, it must have parenthesis around it: "(f)(x)". The reason I did not take this route is because allowing "f" to be a Node (without parenthesis) allows it to have its own positioning information. So in the case of code like "2 + 3" (which is "#+(2, 3)" as a Loyc tree in prefix notation), if "#+" is a separate node then it can have its own positioning information, indicating that the "+" sign is two characters to the right of its parent node "2 + 3". On the other hand, this positioning information is perhaps not needed for all method calls, which seems to be an argument in favor of allowing simple Symbols to be heads; and we cannot simply remove the "Symbol" part of a Node, for how would we represent a Node that is just a Symbol?
All of the above issues are "design smells", but I am not yet confident about how to eliminate the stink.
Here are my thoughts so far. First of all, I am convinced that immutable nodes are more convenient to work with and should be the default choice. Mutable nodes--assuming that I keep support for mutable nodes at all--should have their own data type, but I'm not sure if it should be a completely separate data type or a derived class. Certainly, it's good if code that analyzes immutable nodes can work with mutable nodes "for free", although some code will want to know "for sure" that no other code will modify a tree. The common interface between immutable and mutable nodes could be placed in an INodeReader interface, which allows mutable and immutable nodes to be completely separate, but code that operates on INodeReader instead of a base class would be slower, and implementing INodeReader is a burden on me because the interface needs its own special argument and attribute lists (it must return lists of INodeReader instead of the actual node type).
I have an idea that I think would allow nodes to be cached and relocated, without the inconvenience that currently makes green nodes problematic. If this idea works, the green nodes will become the preferred form in which to manipulate syntax trees, while red nodes would only exist as a way to track parents.
Dealing with parenting has been annoying and I want the problem to go away. I'm thinking about getting rid of parents--and red nodes--completely, at least temporarily while I finish off LLLPG, the parser generator. Perhaps the parentable nodes (red nodes) could be added later as a special kind of node, derived from the same base class as the green nodes; the red nodes may be simple wrappers, consisting of a reference to a green node plus a reference to a parent. All the methods would simply be forwarded to the green node.
Changing the subject now, I need to find a new way to look at Loyc nodes. Clearly, all Loyc nodes can have attributes and position/width/style information, so it's natural to have a common base class with common data. Apart from this common information, nodes represent the following forms:
- Just an identifier: simple_symbol
- Call an identifier: simple_symbol()
- Just a literal: "literal"
- Call a literal: "literal"() (weird, but syntactically legal)
- Call a complex head: Console.WriteLine(), Foo(x)(y), Foo<x>(y)
- Node in parenthesis: (x + 1). I'd like to represent parens explicitly in order to more faithfully represent the input, even though Loyc trees are not designed to support everything the way Roslyn and NRefactory can; for example, there's no obvious way to support round-tripping of syntax errors.
data NodeData = Symbol | Literal object | InParens Node | Call Node List<Node>In this representation, 'Node' is position information, plus attributes, plus a NodeData. A "Call" consists of the thing being called, plus a list of arguments. Or we could use the LISP representation of a call:
data LispNode = Symbol | Literal object | InParens Node | Call List<Node>In the LISP style, the thing being called is the first item in the List (and in LISP, the List is a linked list rather than an array.) The LISP style definitely has advantages, but I'm not sure I'm comfortable mixing the call target with the call's arguments like this.
So what should I do in C#? I can certainly map the ADT to C# with something like:
public class Node { /* position information and attributes go here */ } public class SymbolNode : Node { public Symbol Name { get; } ... } public class LiteralNode : Node { public object Value { get; } ... } public class ParensNode : Node { public Node Child { get; } ... } public class CallNode : Node { public Node Head { get; } public IListThe issues with this mapping are:
Args { get; } ... }
- C# doesn't have features for deconstructing nodes easily; there's no 'match' statement
- Lots of run-time conversions are required: you'd be downcasting constantly, harming performance. You could use visitors though, avoiding some casts (I expect casting to have a significant penalty because the classes above would not be sealed--in fact they'd probably be abstract, to allow support for red nodes, repositioning to account for editing in an IDE, etc.--and casting is rumored to cost more when the target type does not exactly match the actual type). I've never been a fan of the visitor pattern by the way, but it's grown on me recently as I finally grok it. The visitor pattern is brittle with respect to changes in the class hierarchy, but that's not really a problem for Loyc trees, because fundamentally new kinds of nodes should never be needed.
- When you add red nodes and other wrapper classes, the total number of classes could be quite high.
- A simple call such as "f()" will require two nodes, whereas the current implementation only needs a single node. It occurs to me, however, that the child node "f" could be implemented as a temporary object, constructed on-demand and immediately discarded (calling the Name property rather than Target would avoid constructing the temporary object).
- Currently, a mutable node can be converted in-place between any of the possible node types, e.g. you can simply write node.IsCall = true to add an empty argument list. That kind of thing is not possible when we use these separate classes.
|
http://loyc.net/2013/redesigning-loyc-tree-code.html
|
CC-MAIN-2019-26
|
refinedweb
| 1,868
| 54.15
|
Convert Decimal fraction to binary in Java
In this section, we are going to learn how to convert a decimal fraction into binary in Java. So, we can divide this problem into two parts i.e one for integral and other for decimal part.
1. To calculate a binary number of an Integral Part:
The logic behind this is to divide the number by two and store its remainder.
- We will implement a while loop that will work till the time number becomes zero.
- Divide a number by two and store the remainder in a variable called rem.
- Update a number to a number divided by two i.e, n=n/2.
- Insert the remainder at the first index of String.
2. To calculate a binary number of a Fractional Part:
The logic behind this is to multiply the number i.e fractional part by two and store its integral part. In this, we have taken an integer called k which denotes precision up-to k digits. If we have not taken this then in most of the cases the loop will run infinitely.
- We will implement a while loop that will work till the time k becomes zero.
- Then, multiply a number by two and store its integral part in a variable called integralPart.
- Update fractional number by extracting a fractional part of number*2.
- Lastly, reduce the value of k by one.
Java program to convert Decimal fraction to Binary
package CodeSpeedy; import java.util.Scanner; public class decimalToBinary { public static void main(String[] args) { // TODO Auto-generated method stub double num,fractionalPart= 0,number; int rem=0,integralPart,k; StringBuilder s=new StringBuilder(); Scanner scn=new Scanner(System.in); System.out.println("Enter the number"); num=scn.nextDouble(); //112.564 System.out.println("Enter number upto which precision is required"); k=scn.nextInt(); //5 System.out.print("Output is "); int n=(int) num; fractionalPart=num-n; while(n!=0) { rem=n%2; n=n/2; s.insert(0,rem); } System.out.print(s+"."); s=new StringBuilder(); while(k!=0) { integralPart=(int) (fractionalPart*2); s.append(integralPart); number=fractionalPart*2; fractionalPart=number-integralPart; k--; } System.out.println(s); //1110000.10010 } }
Output:
Enter the number 112.564 Enter number upto which precision is required 5 Output is 1110000.10010
The catch in this problem is that rather of taking a String, we have used StringBuilder. StringBuilder helps to modify the string from any end which means we can insert an element at any Index which is not supported by normal String. So by using this, we don’t have to implement a function to reverse a String.
Also read: How to convert a HashMap to TreeMap in Java
Can you convert the fractional part to binary without using string builder or array
|
https://www.codespeedy.com/convert-decimal-fraction-to-binary-in-java/
|
CC-MAIN-2022-27
|
refinedweb
| 463
| 50.43
|
"The generation of random numbers is too important to be left to chance." – Robert R. Coveyou
An alternate random number generator built around four principles:
Statistical Quality. If you use any seed less than 53,668 and generate one bool, it will be
True – if you're
using core's
Random module. More sophisticated statistical tests spot patterns in the "random" numbers almost
immediately. Would you want to trust the accuracy of your fuzz
tests to such a flawed algorithm? This library
produces far less predictable and biased output, especially if you use thousands of random numbers. See
test/dieharder for more details.
Useful features. This library exports
constant and
andMap, which are conspicuously absent from core, along
with other helpful functions for composing generators. Particularly interesting is
independentSeed, which allows for
lazy lists and isolated components to generate as much randomness as they need, when they need it.
Performance. This library will generate floats about 3.5 times faster than core, and ints do not regress. These figures stand to improve pending some optimizations to the compiler. You can see the full benchmark results.
Compatibility. This library is a drop-in replacement for core's Random module. Specifically, you
can replace
import Random with
import Random.Pcg as Random and everything will continue to work. (The one exception is third party
libraries like elm-random-extra.)
This is an implementation of PCG by M. E. O'Neil. The generator is not cryptographically secure.
Please report bugs, feature requests, and other issues on GitHub.
andMapflipped.
andThenflipped.
initialSeed2, since there are now only 32 bits of state.
Random.Pcg.Interop.fissionhas been changed to a (core) generator of (PCG) seeds.
generateto match core 4.x API. Implemented by Richard Feldman.
generaterenamed
stepto match core 4.x API.
Random.Pcgfrom
Random.PCG.
splithas been removed; use
independentSeed.
minIntand
maxIntvalues changed to match core.
|
https://package.frelm.org/repo/689/5.0.2
|
CC-MAIN-2018-51
|
refinedweb
| 311
| 51.95
|
Partnering with a managed service provider (MSP) vendor
Managed service provider (MSP) partnerships are rarely as fruitful as both sides would like. When choosing an MSP vendor, ask these questions to determine if your partnership will be a good one.
The majority of channel partnerships are not as productive as both sides would like, yet we treat each letdown as if it were some new phenomenon. The decision-making criteria to determine who to choose as a partner has changed little over the years. From the vendor's perspective, the driving force is incremental revenue and reach. For the managed service provider (MSP), it's the product offerings that best fit customer requirements and whether enough money can be made selling, implementing and supporting them.
Tim Hannibal of VaultLogix, a Mass.-based MSP, explained that besides the obvious profitability factor, the vendor must be flexible to work with. In a market like today's, where conditions are continually changing, having a flexible partner that you can easily communicate with is critical. Tim said VaultLogix's MSP software vendor has demonstrated its ability to do just that. Both parties have to recognize that the world is fluid and dynamic today, and without the ability to communicate candidly and honestly, even then longest relationships will be put to the test. In addition, channel partners rely heavily on their vendors' abilities to constantly explore upcoming market needs and new opportunities.
Philosophically, it makes sense to ask yourself the following questions during the qualification phase when you are considering implementing an MSP offering.
- Does the vendor provide unique functionality? By providing this functionality, the customer (end user) derives value, which can be justifiable and does not require me (the VAR) to compete solely on price.
- Is the vendor's product offering geared to the MSP market, or was it bolted together to fill a perceived need? One that is bolted together may require you to become your own little software company in order to provide the managed service offering (i.e.: middleware may be needed). Getting the facts, obtaining concrete examples and asking the tough questions can save you a lot of time and money up front.
- Is the vendor's software licensing model "MSP friendly", or do you need to outlay large sums up front? Since you will be charging your customers as they grow, it is beneficial for you to buy the same way. Vendors that grew up in the MSP market understand this model and will charge accordingly.
- Does the vendor understand the MSP space? What education can they provide that enables you to invest in an MSP initiative profitably from the beginning?
- Does the vendor have a direct-sales force? If so, do the field reps have a channel neutral (or channel favoring) compensation plan? This means that the vendor representative gets paid as if they sold it themselves, which in turn creates the right field behavior.
- Do the MSP vendors' solutions tie into other MSP products like Level Platforms, ConnectWise, AutoTask, Kaseya, N-Able, Silverback, etc.? By working with a vendor that performs this service for you, the requirements you have to provide for internal expertise and expenses can be minimized.
- How easy is it to work with the vendor? Speak with other VARs outside of your territory that have worked with the vendor and find out the real scoop. The vendor may sound good on the surface but you should drill down just to be certain. If you don't pose a competitive threat, other partners will most likely be happy to share the good, bad and ugly truth.
In review, to increase the probability of a successful business relationship, look for the following qualities in your MSP vendor.
- Simplicity in delivery and being as non-invasive as possible (agentless or appliance based) will dictate how much training and investment you'll need to make up front, and how fast you can go to market.
- VAR's ability to brand the software to leverage existing brands' equity
- Flexible terms (pay as you go or creative licensing), aligned with incentives.
- A proven solution in the field. Is your customer the vendor's beta site? If so, you need to be compensated for the risk and for being their QA lab.
- Quick start package from solution to billing available now. If not, how much work do you need to do before you can really start selling?
- Advanced security. This will be a concern for any customer who is sending data to someone else.
- World class customer service. Ideally the vendor's support is a virtual extension of your own. If not, you need resolution efficiently and easily until your own staff can get up to speed.
- Tools to increase selling efficiency. Learn from the vendors' experiences.
- They are easy to do business with. It's a red flag if they are difficult to deal with before you bring them customers.
Perfection is hard to find anywhere you look, however there are vendors that are at the top of the list each time you prioritize criteria. These are the folks you want to do business with; starting a new initiative is challenging enough.
One of the key focus areas for you during your due diligence should be the tools the MSP OEM provides for you to be successful. The first explanation should occur before you sign on the dotted line. If an MSP OEM does not sit down with you to calculate an internal rate of return (IRR) for your business and set expectations in both directions, I would question every assumption they throw at you. A good IRR tool should be in the MSP OEM's bag. You should be able to examine the breakeven and the profit areas of the business. Companies that were built to provide MSP services should be able to quantify all aspects of the IRR before you commit a dime. A good OEM knows that your success is shared by them, so not giving you all the realistic assumptions up front does no one any good over the long haul..
Start the conversation
|
https://searchitchannel.techtarget.com/feature/Partnering-with-a-managed-service-provider-MSP-vendor
|
CC-MAIN-2020-05
|
refinedweb
| 1,018
| 62.78
|
Details
- Type:
Bug
- Status: Resolved
- Priority:
Critical
- Resolution: Fixed
- Affects Version/s: None
-
-
- Labels:None
- Environment:Maven 2, JUnit, JUnitPerf, JRat, custom testbench:
Description
The following test template (see
VELOCITY-24):
- local macro, not global
#macro(letter $char)
This is the letter $char
")
—
Works quickly and correctly with Velocity 1.5 with several concurrent threads. However, 1.6-dev is a LOT slower (even 20x).
The major performance bottlenecks seem to be:
RuntimeMacro.render (60% of time)
VelocimacroFactory.getVelocimacro (20% of time)
With several threads this test also causes Velocity to throw error(s):
org.apache.velocity.exception.MacroOverflowException: Exceed maximum 20 macro calls. Call Stack:letter->letter->letter->letter->letter
at org.apache.velocity.runtime.VelocimacroFactory.startMacroRendering(VelocimacroFactory.java:179)
at org.apache.velocity.runtime.RuntimeInstance.startMacroRendering(RuntimeInstance.java:1693)
at org.apache.velocity.runtime.directive.VelocimacroProxy.render(VelocimacroProxy.java:200)
at org.apache.velocity.runtime.directive.RuntimeMacro.render(RuntimeMacro.java:230)
at org.apache.velocity.runtime.parser.node.ASTDirective.render(ASTDirective.java:178)
at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:323)
at org.apache.velocity.Template.merge(Template.java:324)
at org.apache.velocity.Template.merge(Template.java:232)
at org.apache.velocity.test.load.Velocity24Test.testRendering(Velocity24Test.java:51)
This is related to
VELOCITY-297 but the fix doesn't seem work with the new modified macro implementation.
Activity
- All
- Work Log
- History
- Activity
- Transitions
Also I think that it would be nice if one could switch that recursive call tracking off in the configuration file since it's quite expensive to do (there are some tough synchronized blocks).
I'll make it so setting a value of <=0 turns it off, but even so, the synchronization all has to go for this to work properly. The macro call stack cannot work as it's supposed to if it is shared across threads. So, i'm moving it into the InternalHousekeepingContext interface (impl is in InternalContextBase). This way, so long as no one shares a context directly (wrapped is fine) across threads (which is a Very Bad Idea to begin with), this will work as it is supposed.
Really, i'm a bit surprised this macro call depth guard got committed in the first place. It's got lots of problems and the testcase is atrociously broken. Fix will be checked in momentarily. If anyone out there is implementing InternalContextAdapter in their own apps (perhaps for a custom directive? but even that's unlikely), this will break their code. Sorry, the fix is absolutely necessary, and i don't believe there's any other way to do it.
Ok, that should do it. I haven't installed and run your testbench though, Jarkko. If you wouldn't mind testing this, i'd be much obliged.
Sorry, forgot for a second that performance issues were listed for this issue too. Re-opening to look at those.
You're talking about Velocity-297, right? Mea culpa as the committer who reviewed the patch.
I think it's fine to change InternalContextAdapter – we've done this before and I don't consider it part of our public API.
Yeah, it was for
VELOCITY-297. But really, you may have committed it, but we're all supposed to be reviewing commits. We all missed it. Nice work Nathan! I ran tests with 250 simultaneous threads using the test but I didn't get the incorrect macrooverflow exception anymore. I also tested that infinite recursion correctly causes the exception. So your fixes seem to work well.
The performance is still rotten though (with 350 threads, 50 loops: 1.5: 1,3 seconds, 1.6-dev: 46 seconds)
Ok, i've got your testbench running for me now. Thanks! It's nice to be able to test improvements. I only wish it could tell me what is happening within those slow methods that is taking so long. I can assume it is thread blocking, but it would be nice to know for sure. I suppose if i can reduce the synchronization and get big performance gains, than that will tell me.
So, it seems that synchronization is not the main problem. It seems like there is a lot of work being re-done. When the template is parsed, each use of a macro in that template creates an instance of RuntimeMacro and a VelocimacroProxy. That's fine and to be expected. What surprised me is that when you render the template (even when cached), each render of that template creates its own VelocimacroProxy instance and a VMProxyArg instance. In other words, it appears that every time a macro is rendered, it's content is re-parsed into an AST. That seems pretty overkill.
I don't really have any more time to investigate, but there's got to be a better way to do this. But, if we can't find a way, then i'd want to revert the changes that caused this. Given the choice between this constant re-parsing and not being able to include macros via #parse calls, i would prefer the latter. Inconvenience is better than terrible performance. Hopefully, it won't come to that, and we'll just find a way to avoid all this repetition.
Nathan is right. I have analyzed the code a lot and there is massive amount of rework done. Every time a macro is used, a new VelocimacroProxy is created and the macro is reparsed from string to AST. Then each macro argument is reparsed from string to AST. For each macro argument a new VMProxyArg is created. In addition, a new VMContext is created every time a macro is called (2 HashMaps). This means a lot of memory allocation which is slow and lots of garbage.
Also when the macro is parsed the first time (Macro directive) the already parsed AST is turned back into a String and stored.
I mercilessly refactored the code and I managed to create an implementation which passes all current tests and a) uses shared AST for all macros, b) uses shared VelocitymacroProxy c) uses call by reference for macro arguments (instead of call by value). With these modifications the performance is very close to 1.5 with the template in this issue but not quite there yet.
I'll see if I can tweak the refactored design a bit more but it's already several times faster than current one.
I look forward to seeing your patch, Jarkko! I'm a little wary about point c) in your list, but i'll wait until i see what you've done.
First things first:
1. This is not a real production quality patch. It contains some ideas and major design changes that I tried when trying to make Velocity 1.6 new macro implementation perform better. I have done some functional, performance and load testing but not nearly enough.
2. Although tests pass, I have most probably broken some functionality especially regarding error messages and namespaces.
3. I have tested these changes with several hundred concurrent threads which does not mean that they are free from race conditions, locking issues etc. nasty stuff.
4. Even after this patch Velocity 1.6 svn head is around 10-20% slower than 1.5. I didn't investigate 1.5 code that much but I suspect that Velocity 1.5 fully preconstructs templates by duplicating macro AST and precalculates values for constant macro arguments. This patch however uses shared macro ASTs which should reduce memory usage but introduces a bunch of new problems.
5. There are public interface changes (yep, bad).
Main ideas of this patch:
1. When a macro is parsed and thrown into Macro.processAndRegister, it is not transformed and stored as String but as AST.
2. VelocimacroManager does not create new VelocimacroProxy for each request but creates one per macro / namespace. Thus threads share the macro AST.
3. VMContext and VMProxyArg have been replaced with ProxyVMContext. This allows us to skip parsing of macro arguments when macro is invoked and it reduces memory allocation overhead.
4. "Render literal if null for references" is tricky to implement with shared macro AST. Velocity 1.5 implements this by preprocessing the AST tree with visitor.VMReferenceMungeVisitor. As far as I understand, this is not possible with shared macro AST. Therefore there's a rather ugly hack which puts macro argument references to the macro rendering context. ASTReference can then construct the literal format of arguments on-demand.
Other notes:
1. ExtendedProperties class is synchronized and very slow overall (it even says so in the JavaDocs). There are quite many runtime calls to this class throughout the Velocity code.
2. I haven't really investigated yet if this version even uses less memory than 1.5. If the memory usage isn't significantly lower, I don't see much point in using 1.6 if one doesn't need the new macro functionality.
3. I probably made some catastrophic design mistakes but it takes time to understand velocity functionality and design. Please forgive me.
Hi,
Jarkko-- thanks so much for your great work, I'm looking forward to seeing this in production.
I just wanted to throw in a reminder the the macro functionality in v1.6 is a tremendous leap forward from 1.5, at least for some of us. (responding to: "If the memory usage isn't significantly lower, I don't see much point in using 1.6."). The new feature is that macros defined in a file included with #parse are now available to the parent page. This means that you can make libraries of macros for various parts of your app (separate from the global macro library). Secondly, macros can be added programmatically via a call to RuntimeInstance.addVelocimacro().
I mention this mainly to ensure we don't scope this new functionality out with the performance improvements.
Perhaps this is not the proper place to discuss such matters (and I must admit that I'm largely ignorant to the inner workings of Velocity), but is there a reason that a macro is /ever/ re-parsed from text into an AST? Why aren't macros parsed once during the parsing of the containing template and stored along with the main template's AST in memory?
Simple answer. It's because #parse is executed at runtime. Since macros can be loaded in a parsed file, the specific macro might change each time the page is rendered.
OK. I tweaked my patch a bit and removed some bottlenecks. JRat revealed that a lot of time is spent in ASTReference.render because of the value = EventHandlerUtil.referenceInsert(rsvc, context, literal(), value); call. I also managed to make VelocimacroProxy.render totally unsynchronized and made some other little tweaks here and there.
Tests still pass but I hope this doesn't break things too much.
The good news is that with some of my test templates and the test in this issue the patched 1.6-dev is now in some cases even 20% faster than Velocity 1.5.
Some cleanup and Javadoc fixes. Also fixes a log problem which occurs when multiple concurrent threads parse and try to add the same macro simultaneously. This caused unnecessary spam in the log.
I confirmed with Eclipse Memory Analyzer (which is a great tool BTW!) that Velocity 1.6-dev with this patch uses significantly less memory (because macro AST is shared). I made a template with dozens of macro calls to a macro which has huge amounts of text. Velocity 1.5 ended up with 80 MB heap, patched 1.6-dev with 4,5 MB heap.
Latest attachment includes final tweaks to improve performance. I'll start waiting for feedback on these changes. With these changes 1.6-dev is 10-20% faster than 1.5 with the tests I ran (on single core laptop).
Interestingly the creation of the macro context in VelocimacroProxy.render method costs a lot of time because of the memory allocation. There's no easy way to avoid this though.
Removed some tweaks that didn't accomplish anything. This is now about as fast as I can make it.
Is there a test case for including macros in a separate file that is included using the template merge? I'm doing template.merge(context, writer, templates); where templates contains a path to the file containing my macros.
I'm testing this patch (velocity-1.6-dev-macro-performance-IDEAS-v2.2.patch) and I'm getting a null pointer only when I update the file.
The error occurs in the ResourceMangerImpl.refreshResource(). The macros file is coming back a resource type of 0 instead of 1 or 2. Therefore, it is throwing a null pointer exception when attempts to create a new resource.
Patch version 2.5 fixes a bug found by Erron Austin. Thanks for testing! The reason was that Template and ContentResource didn't initialize type by setType in their constructor. There was also another bug in refreshResource (call to newResource.setModificationCheckInterval was missing).
I created a JUnit testcase but it's not completely automatic yet (you have to manually modify template files while the test is running) so I won't include it here yet.
I've verified that my bug has been fixed. I've also verified that my application is working much better than before.
Not knowing the inner workings of Velocity, I can't comment on the way the code was written. But I can say that the results are very good.
Thanks!
Some small additional improvements in patch 2.6. This patch detects if ConcurrentHashMap is available and uses it in resourcecache (if the cache is configured to be unbounded). Also changed some StringBuffer -> StrBuilder in render time segments.
Some minor speed improvements might still be possible in VelocimacroManager and VelocimacroFactory (investigate the use of Hashtables and synchronized blocks).
Somewhere I thought I read someone was against requiring JDK 1.5. Is this not the case?
The new patch does not require JDK 1.5. It uses dynamic classloading to check if the code is running under JRE 1.5+, if it is, it uses ConcurrentHashMap, if it is not, it uses synchronized HashMap. See ResourceCacheImpl.
I can confirm we have a requirement for minimum compile-time JDK 1.4 and run-time JDK 1.3. Clever use of reflection to dynamically choose.
Jarkko,
You might be able to make this ConcurrentHashMap code perform faster if you were to check for it at class initialization, and then associated a map-factory class that used the chosen strategy thereafter. I'm not sure if the complexity is worth the (marginal) performance savings, though.
Maybe something like this:
private static final MapFactory _threadSafeMapFactory;
static
{
try
catch (Exception e){ _threadSafeMapFactory = new SynchronizedMapFactory(); }
}
/* these go in their own files, so the ClassLoader won't choke on a missing ConcurrentHashMap */
public interface MapFactory
public class ConcurrentMapFactory
{
public Map createMap()
}
public class SynchronizedMapFactory
{
public Map createMap()
}
Inspired by Christopher's comment I created a MapFactory which can create Java 5 concurrent maps if they are available. I implemented it in slightly different way though to avoid compile time dependency.
Since there are several maps in VelocimacroFactory and VelocimacroManager, I modified those to get their maps from the MapFactory.
Running on JDK 1.6.0_07 server mode (single core) Velocity 1.6-dev with this patch (2.7) was up to 25% faster than 1.5 and I believe the difference grows larger when there are more CPUs or concurrent threads.
I'll leave the older 2.6 patch in place since these changes are a bit radical.
I'll stop this optimizing madness and wait for Nathan's input.
Thanks for re3moving that dependency – I had forgotten that we had a JDK 1.4 requirement for compiling. I thought we were up to 1.5 these days.
You are swallowing an exception in your MapFactory class and allowing the pre-JDK 1.5 code to kick-in instead. Your in-text comment says "this should never happen". If that's the case, then you should throw some type of error. If someone finds that this error is being thrown, they'll know to come to us and we'll fix it. Otherwise, we may not be getting the speed improvement provided by ConcurrentMap.
Good call on the difference between Hashtable and a synchronized HashMap: I had forgotten that they had slightly different semantics.
If you choose to implement my "throw an error" strategy above, I woulod recommend taking out the addition null check for your "map" reference afterward – because it should always be null.
Ok, i've committed everything from your latest patch, with just a bit of cleanup here and there. All the tests pass, performance looks quite improved to me. This is awesome, Jarkko! Thanks!
Before i resolve this, does anyone know of any code that could/would/should/does/did/might reference the VMProxyArg, VMContext, or VMReferenceMungeVisitor classes? It seems unlikely to me, so i'm tempted to just remove them, rather than merely deprecate them. Also, the Runtime class has been deprecated for some time now. I'm ready to yank that out too. Thoughts anyone?
Oh, i forgot to mention that it appeared your patch was not built against the trunk's head, as recent changes to VelocimacroManager were reverted. For simplicity, i went ahead and let them be reverted. I'll redo those soon, but not tonight. Dinner calls.
If there's no code in the project that references those classes I'm okay with removing them. They seem pretty internal to me.
Ok, marking this resolved. Jarkko, feel free to re-open if i missed something or messed up something. I think i got it all though. Performance looks much better in my testing too.
Now, with all these changes, it's probably time for a beta release to encourage people to start kicking the tires and make sure we didn't change something important...
As i said in
VELOCITY-606, the bug found above looks like VelocimacroFactory.startMacroRendering is mis-designed to limit macro concurrency when it is trying to limit macro call depth. I don't think there's anyway to fix the startMacroRendering(...) method. The macro call stack probably has to be stored in the VMContext/InternalHousekeepingContext, just like the template stack. I'll see if i can make that work right before i worry about performance.
|
https://issues.apache.org/jira/browse/VELOCITY-607?attachmentOrder=asc
|
CC-MAIN-2016-07
|
refinedweb
| 3,076
| 59.09
|
I converted a solution from VS2005 to VS2010. The original solution used dotNet 2.0 and ESRI ArcGIS so when VS2010 wanted to switch to dotNet 4.0 I declined. ESRI ArcGIS 10 hasn't been cirtified for dotNet 4.0 yet.
I then selected each project properties and changed dotNet to 3.5, cleaned up any broken references and tried to rebuild the whole solution.
The rebuild gave me a message like the following:
The referenced project ‘..\..\..\TechnicalArchitecture\Shared\TheCityofCalgary.Architecture.DataEntityModel\TheCityofCalgary.Architecture.DataEntityModel.csproj’ does not exist.
and the following error message:
This
is odd since the referenced project's location has not changed and it is 3 directories up and over from the project that is using the reference. So I changed the relative reference to a fixed reference by changing ..\..\.. with
C:\Projects\(ArcGIS) Server Services\Main V10\Solution. The project will know build. However, this will cause issues when I try to send the solution off to our build server since it won't have this physical location.
The type or namespace name 'DataEntityModel' does not exist in the namespace 'TheCityofCalgary.Architecture' (are you missing an assembly reference?)
I
have also tryied recreating the project. This works as well. However, when I rename the project back to the old name and modify the directory back to the old name the project gives the same error about a broken reference.
Any
suggestions on what I'm doing wrong? All help is appreciated.
P.S.
I hope I've posted to the correct forum.
You need to calculate relative paths not between project/solution files, but between sln, csproj files physical locations.
Maybe while upgrade the relative paths of the projects FILES changed? That must be the main reason, if absolute paths work fine.
|
https://social.msdn.microsoft.com/Forums/en-US/417f5bdc-57f9-476c-95c0-e7a715259e88/broken-reference-issues-relative-address-isnt-working?forum=csharplanguage
|
CC-MAIN-2020-16
|
refinedweb
| 298
| 60.31
|
\input texinfo @c -*-texinfo-*-
@setfilename ../../info/cl
@settitle Common Lisp Extensions
@include emacsver.texi
@copying
This file documents the GNU Emacs Common Lisp emulation package.
.''
@end quotation
@end copying
@dircategory Emacs lisp libraries
@direntry
* CL: (cl). Partial Common Lisp support for Emacs Lisp.
@end direntry
@finalout
@titlepage
@sp 6
@center @titlefont{Common Lisp Extensions}
@sp 4
@center For GNU Emacs Lisp
@sp 1
@center as distributed with Emacs @value{EMACSVER}
@sp 5
@center Dave Gillespie
@center daveg@@synaptics.com
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage
@contents
@ifnottex
@node Top
@top GNU Emacs Common Lisp Emulation
@insertcopying
@end ifnottex
* Overview:: Basics, usage, etc.
* Program Structure:: Arglists, @code{cl-eval-when}, @code{defalias}.
* Predicates:: @code{cl-typep} and @code{cl-equalp}.
* Control Structure:: @code{cl-do}, @code{cl-loop}, etc.
* Macros:: Destructuring, @code{cl-define-compiler-macro}.
* Declarations:: @code{cl-proclaim}, @code{cl-declare}, etc.
* Symbols:: Property lists, @code{cl-gensym}.
* Numbers:: Predicates, functions, random numbers.
* Sequences:: Mapping, functions, searching, sorting.
* Lists:: @code{cl-caddr}, @code{cl-sublis}, @code{cl-member}, @code{cl-assoc}, etc.
* Structures:: @code{cl-defstruct}.
* Assertions:: @code{cl-check-type}, @code{cl-assert}.
* Efficiency Concerns:: Hints and techniques.
* Common Lisp Compatibility:: All known differences with Steele.
* Porting Common Lisp:: Hints for porting Common Lisp code.
* Obsolete Features:: Obsolete features.
* GNU Free Documentation License:: The license for this documentation.
* Function Index::
* Variable Index::
@end menu
@node Overview
@chapter Overview
@noindent @code{CL} package adds a number of Common Lisp functions and
control structures to Emacs Lisp. While not a 100% complete
implementation of Common Lisp, @code,
case-insensitive symbols, and complex numbers.
The @code{CL} package generally makes no attempt to emulate these
features.
@end itemize
This package was originally written by Dave Gillespie,
@file{daveg@@synaptics.com}, as a total rewrite of an earlier 1986
@file{cl.el} package by Cesar Quiroz. Care has been taken to ensure
that each function is defined efficiently, concisely, and with minimal
impact on the rest of the Emacs environment. Stefan Monnier added the
file @file{cl-lib.el} and rationalized the namespace for Emacs 24.3.
* Usage:: How to use the CL package.
* Organization:: The package's component files.
* Naming Conventions:: Notes on CL function names.
@end menu
@node Usage
@section Usage
@noindent
The @code{CL} package is distributed with Emacs, so there is no need
to install any additional files in order to start using it. Lisp code
that uses features from the @code{CL} package should simply include at
the beginning:
@example
(require 'cl-lib)
@end example
@noindent
You may wish to add such a statement to your init file, if you
make frequent use of CL features.
@node Organization
@section Organization
@noindent
The Common Lisp package is organized into four main files:
@table @file
@item cl-lib.el
This is the main file, which contains basic functions
and information about the package. This file is relatively compact.
@item cl-extra.el
This file contains the larger, more complex or unusual functions.
It is kept separate so that packages which only want to use Common
Lisp fundamentals like the @code{cl-incf} function won't need to pay
the overhead of loading the more advanced functions.
@item cl-seq.el
This file contains most of the advanced functions for operating
on sequences or lists, such as @code{cl-delete-if} and @code{cl-assoc}.
@item @file{cl-macs.el} so that they
won't take up memory unless you are compiling.
@end table
The file @file{cl-lib.el} includes all necessary @code{autoload}
commands for the functions and macros in the other three files.
All you have to do is @code{(require 'cl-lib)}, and @file{cl-lib.el}
will take care of pulling in the other files when they are
needed.
There is another file, @file{cl.el}, which was the main entry point to
the CL package prior to Emacs 24.3. Nowadays, it is replaced by
@file{cl-lib.el}. The two provide the same features (in most cases),
but use different function names (in fact, @file{cl.el} mainly just
defines aliases to the @file{cl-lib.el} definitions). Where
@file{cl-lib.el} defines a function called, for example,
@code{cl-incf}, @file{cl.el} uses the same name but without the
@samp{cl-} prefix, e.g. @code{incf} in this example. There are a few
exceptions to this. First, functions such as @code{cl-defun} where
the unprefixed version was already used for a standard Emacs Lisp
function. In such cases, the @file{cl.el} version adds a @samp{*}
suffix, e.g. @code{defun*}. Second, there are some obsolete features
that are only implemented in @file{cl.el}, not in @file{cl-lib.el},
because they are replaced by other standard Emacs Lisp features.
Finally, in a very few cases the old @file{cl.el} versions do not
behave in exactly the same way as the @file{cl-lib.el} versions.
@xref{Obsolete Features}.
Since the old @file{cl.el} does not use a clean namespace, Emacs has a
policy that packages distributed with Emacs must not load @code{cl} at
run time. (It is ok for them to load @code{cl} at @emph{compile}
time, with @code{eval-when-compile}, and use the macros it provides.)
There is no such restriction on the use of @code{cl-lib}. New code
should use @code{cl-lib} rather than @code{cl}.
There is one more file, @file{cl-compat.el}, which defines some
routines from the older Quiroz CL package that are not otherwise
present in the new package. This file is obsolete and should not be
used in new code.
@node Naming Conventions
@section Naming Conventions
@noindent
Except where noted, all functions defined by this package have the
same calling conventions as their Common Lisp counterparts, and
names that are those of Common Lisp plus a @samp{cl-} prefix.
Internal function and variable names in the package are prefixed
by @code{cl--}. Here is a complete list of functions prefixed by
@code{cl-} that were not taken from Common Lisp:
cl-callf cl-callf2 cl-defsubst
cl-floatp-safe cl-letf cl-letf*
@end example
The following simple functions and macros are defined in @file{cl-lib.el};
they do not cause other components like @file{cl-extra} to be loaded.
@example
cl-floatp-safe cl-endp
cl-evenp cl-oddp cl-plusp cl-minusp
cl-caaar .. cl-cddddr
cl-list* cl-ldiff cl-rest cl-first .. cl-tenth
cl-copy-list cl-subst cl-mapcar [2]
cl-adjoin [3] cl-acons cl-pairlis
cl-pushnew [3,4] cl-incf [4] cl-decf [4]
cl-proclaim cl-declaim
@end example
@noindent
[2] Only for one sequence argument or two list arguments.
@noindent
[3] Only if @code{:test} is @code{eq}, @code{equal}, or unspecified,
and @code{:key} is not used.
@noindent
[4] Only when @var{place} is a plain variable name.
@node Program Structure
@chapter Program Structure
@noindent
This section describes features of the @code{CL} package that have to
do with programs as a whole: advanced argument lists for functions,
and the @code{cl-eval-when} construct.
* Argument Lists:: @code{&key}, @code{&aux}, @code{cl-defun}, @code{cl-defmacro}.
* Time of Evaluation:: The @code{cl-eval-when} construct.
@node Argument Lists
mac clmac
@defmac cl-defsubst name arglist body...
This is just like @code{cl-defun}, except that the function that
is defined is automatically proclaimed @code{inline}, i.e.,
calls to it may be expanded into in-line code by the byte compiler.
This is analogous to the @code{defsubst} form;
@code{cl-defsubst} uses a different method (compiler macros) which
works in all versions of Emacs, and also generates somewhat more
efficient inline expansions. In particular, @code{cl-defsubst}
arranges for the processing of keyword arguments, default values,
etc., to be done at compile-time whenever possible.
@defmac cl}.
@defmac cl-function symbol-or-lambda
This is identical to the regular @code{function} form,
except that if the argument is a @code{lambda} form then that
form may use a full Common Lisp argument list.
Also, all forms (such as @code{cl-flet} and @code{cl-labels}) defined
in this package that include @var{arglist}s in their syntax allow
full Common Lisp argument lists.
Note that it is @emph{not} necessary to use @code{cl-defun} in
order to have access to most @code{CL} features in your function.
These features are always present; @code{cl
(cl.
You can also explicitly specify the keyword argument; it need not be
simply the variable name prefixed with a colon. For example,
@example
(cl-defun bar (&key (a 1) ((baz b) 4)))
@end example
@noindent
specifies a keyword @code{:a} that sets the variable @code{a} with
default value 1, as well as a keyword @code{baz} that sets the
variable @code{b} with default value 4. In this case, because
@code{baz} is not self-quoting, you must quote it explicitly in the
function call, like this:
@example
(bar :a 10 'baz 42)
@end example
Ordinarily, it is an error to pass an unrecognized keyword to
a function, e.g.,
(cl-defun find-thing (thing &rest rest &key need &allow-other-keys)
(or (apply 'cl-member thing thing-list :allow-other-keys t rest)
(if need (error "Thing not found"))))
@end smallexample
@noindent
This function takes a @code{:need} keyword argument, but also
accepts other keyword arguments which are passed on to the
@code{cl-member} function. @code{allow-other-keys} is used to
keep both @code{find-thing} and @code{cl-member} from complaining
about each others' keywords in the arguments.
(cl-defun foo (a b &aux (c (+ a b)) d)
@var{body})
(cl-defun foo (a b)
(let ((c (+ a b)) d)
@var{body}))
@end example
Argument lists support @dfn{destructuring}. In Common Lisp,
destructuring is only allowed with @code{defmacro}; this package
allows it with @code{cl
(clmac cl{cl{cl{cl-eval-when} acts like a
@code{progn} if @code{eval} is specified, and like @code{nil}
(ignoring the body @var{forms}) if not.
The rules become more subtle when @code{cl-eval-when}s are nested;
consult Steele (second edition) for the gruesome details (and
some gruesome examples).
Some simple examples:
@example
;;{cl-eval-when}s had been, say, inside a @code{defun},
then the first three would have been equivalent to @code{nil} and the
last four would have been equivalent to the corresponding @code{setq}s.
Note that @code{(cl-eval-when (load eval) @dots{})} is equivalent
to @code{(progn @dots{})} in all contexts. The compiler treats
certain top-level forms, like @code{defmacro} (sort-of) and
@code{require}, as if they were wrapped in @code{(cl-eval-when
(compile load eval) @dots{})}.
Emacs includes two special forms related to @code{cl-eval-when}.
One of these, @code{eval-when-compile}, is not quite equivalent to
any @code{cl-eval-when} construct and is described below.
The other form, @code{(eval-and-compile @dots{})}, is exactly
equivalent to @samp{(cl-eval-when (compile load eval) @dots{})} and
so is not itself defined by this package.
@defmac.
@defmac cl{cl{cl-load-time-value}
act exactly like @code{progn}.
@example
(defun report ()
(insert "This function was executed on: "
(current-time-string)
", compiled on: "
(eval-when-compile (current-time-string))
;; or '#.(current-time-string) in real Common Lisp
", and loaded on: "
(cl
@node Predicates
@chapter Predicates
@noindent
This section describes functions for testing whether various
facts are true or false.
* Type Predicates:: @code{cl-typep}, @code{cl-deftype}, and @code{cl-coerce}.
* Equality Predicates:: @code{cl-equalp}.
@node Type Predicates
@section Type Predicates
@defun cl-typep object type
Check if @var{object} is of type @var{type}, where @var{type} is a
(quoted) type name of the sort used by Common Lisp. For example,
@code{(cl{(cl-typep @var{object} t)} is always true. Likewise, the
type symbol @code{nil} stands for nothing at all, and
@code{(cl-typep @var{object} nil)} is always false.
@item
The type symbol @code{null} represents the symbol @code{nil}.
Thus @code{(cl-typep @var{object} 'null)} is equivalent to
@code{(null @var{object})}.
@item
The type symbol @code{atom} represents all objects that are not cons
cells. Thus @code{(cl-typep @var{object} 'atom)} is equivalent to
@code{(atom {cl{cl{cl-typep}.
@defun cl-coerce object type
This function attempts to convert @var{object} to the specified
@var{type}. If @var{object} is already of that type as determined by
@code{cl{cl-coerce} signals an
error.
@end defun
@defmac cl{cl{cl-defmacro} except that optional arguments without explicit
defaults use @code{*} instead of @code{nil} as the ``default''
default. Some examples:
@example
(cl-deftype null () '(satisfies null)) ; predefined
(cl-deftype list () '(or null cons)) ; predefined
(cl.
The @code{cl-typecase} and @code{cl-check-type} macros also use type
names. @xref{Conditionals}. @xref{Assertions}. The @code{cl-map},
@code{cl-concatenate}, and @code{cl-merge} functions take type-name
arguments to specify the type of sequence to return. @xref{Sequences}.
@node Equality Predicates
@section Equality Predicates
@noindent
This package defines the Common Lisp predicate @code{cl-equalp}.
@defun cl-equalp a b
This function is a more flexible version of @code{equal}. In
particular, it compares strings case-insensitively, and it compares
numbers without regard to type (so that @code{(cl{cl-equalp} also will
not compare strings against vectors of integers.
@end defun
Also note that the Common Lisp functions @code{member} and @code{assoc}
use @code{eql} to compare elements, whereas Emacs Lisp follows the
MacLisp tradition and uses @code{equal} for these two functions.
In Emacs, use @code{memq} (or @code{cl-member}) and @code{assq} (or
@code{cl-assoc}) to get functions which use @code{eql} for comparisons.
@node Control Structure
@chapter Control Structure
@noindent
The features described in the following sections implement
various advanced control structures, including extensions to the
standard @code{setf} facility, and a number of looping and conditional
constructs.
@c FIXME
@c flet is not cl-flet.
* Assignment:: The @code{cl-psetq} form.
* Generalized Variables:: Extensions to generalized variables.
* Variable Bindings:: @code{cl-progv}, @code{flet}, @code{cl-macrolet}.
* Conditionals:: @code{cl-case}, @code{cl-typecase}.
* Blocks and Exits:: @code{cl-block}, @code{cl-return}, @code{cl-return-from}.
* Iteration:: @code{cl-do}, @code{cl-dotimes}, @code{cl-dolist}, @code{cl-do-symbols}.
* Loop Facility:: The Common Lisp @code{cl-loop} macro.
* Multiple Values:: @code{cl-values}, @code{cl-multiple-value-bind}, etc.
@node Assignment
@section Assignment
@noindent
The @code{cl-psetq} form is just like @code{setq}, except that multiple
assignments are done in parallel rather than sequentially.
@defmac cl)
(cl-psetq x (+ x y) y (* x y))
x
@result{} 5
y ; @r{@code{y} was computed before @code{x} was set.}
@result{} 6
@end example
The simplest use of @code{cl-psetq} is @code{(cl-psetq x y y x)}, which
exchanges the values of two variables. (The @code{cl-rotatef} form
provides an even more convenient way to swap two variables;
@pxref{Modify Macros}.)
@code{cl-psetq} always returns @code{nil}.
@node Generalized Variables
@section Generalized Variables
A @dfn{generalized variable} or @dfn. For basic information,
@pxref{Generalized Variables,,,elisp,GNU Emacs Lisp Reference Manual}.
This package provides several additional features related to
generalized variables.
* Setf Extensions:: Additional @code{setf} places.
* Modify Macros:: @code{cl-incf}, @code{cl-rotatef}, @code{cl-letf}, @code{cl-callf}, etc.
@node Setf Extensions
@subsection Setf Extensions
Several standard (e.g. @code{car}) and Emacs-specific
(e.g. @code{window-point}) Lisp functions are @code{setf}-able by default.
This package defines @code{setf} handlers for several additional functions:
@itemize
@item
Functions from @code{CL} itself:
@smallexample
cl-caaar .. cl-cddddr cl-first .. cl-tenth
cl-rest cl-get cl-getf cl-subseq
@end smallexample
@noindent
Note that for @code{cl-getf} (as for @code{nthcdr}), the list argument
of the function must itself be a valid @var
@end smallexample
Most of these have directly corresponding ``set'' functions, like
@code{use-local-map} for @code{current-local-map}, or @code{goto-char}
for @code{point}. A few, like @code{point-min}, expand to longer
sequences of code when they are used with @code{setf}
(@code{(narrow-to-region x (point-max))} in this case).
@item
A call of the form @code{(substring @var{subplace} @var{n} [@var{m}])},
where @var{subplace} is itself a valid.
@c FIXME? Also `eq'? (see cl-lib.el)
@c Currently commented out in cl.el.
@ignore
}.
@xref{Obsolete Setf Customization}.
@end ignore
@item
A macro call, in which case the macro is expanded and @code{setf}
is applied to the resulting form.
@item
Any form for which a @code{defsetf} or @code{define-setf-method}
has been made. @xref{Obsolete Setf Customization}.
@end itemize
@c FIXME should this be in lispref? It seems self-evident.
@c Contrast with the cl-incf example later on.
@c Here it really only serves as a constrast to wrong-order.
The @code{setf} macro takes care to evaluate all subforms in
the proper left-to-right order; for example,
@example
(setf (aref vec (cl-incf i)) i)
looks like it will evaluate @code{(cl}.
@node Modify Macros
@subsection Modify Macros
@noindent
This package defines a number of macros that operate on generalized
variables. Many are interesting and useful even when the @var{place}
is just a variable name.
@defmac cl-psetf [place form]@dots{}
This macro is to @code{setf} what @code{cl-psetq} is to @code{setq}:
When several @var{place}s and @var{form}s are involved, the
assignments take place in parallel rather than sequentially.
Specifically, all subforms are evaluated from left to right, then
all the assignments are done (in an undefined order).
@defmac cl-incf place &optional x
This macro increments the number stored in @var{place} by one, or
by @var{x} if specified. The incremented value is returned. For
example, @code{(cl-incf i)} is equivalent to @code{(setq i (1+ i))}, and
@code{(cl-incf (car x) 2)} is equivalent to @code{(setcar x (+ (car x) 2))}.
As with @code{setf}, care is taken to preserve the ``apparent'' order
of evaluation. For example,
(cl-incf (aref vec (cl (cl-incf i))
(1+ (aref vec (cl-incf i)))) ; wrong!
@end example
@noindent
but rather to something more like
@example
(let ((temp (cl-incf i)))
(setf (aref vec temp) (1+ (aref vec temp))))
@end example
@noindent
Again, all of this is taken care of automatically by @code{cl-incf} and
the other generalized-variable macros.
As a more Emacs-specific example of @code{cl-incf}, the expression
@code{(cl-incf (point) @var{n})} is essentially equivalent to
@code{(forward-char @var{n})}.
@defmac cl-decf place &optional x
This macro decrements the number stored in @var{place} by one, or
by @var{x} if specified.
@defmac cl{cl-adjoin}.
@xref{Lists as Sets}.
@defmac cl-shiftf place@dots{} newvalue
This macro shifts the @var{place}s left by one, shifting in the
value of @var{newvalue} (which may be any Lisp expression, not just
a generalized variable), and returning the value shifted out of
the first @var{place}. Thus, @code{(cl-shiftf @var{a} @var{b} @var{c}
@var{d})} is equivalent to
@example
(prog1
@var{a}
(cl-psetf @var{a} @var{b}
@var{b} @var{c}
@var{c} @var{d}))
@end example
@noindent
except that the subforms of @var{a}, @var{b}, and @var{c} are actually
evaluated only once each and in the apparent order.
@defmac cl-rotatef place@dots{}
This macro rotates the @var{place}s left by one in circular fashion.
Thus, @code{(cl-rotatef @var{a} @var{b} @var{c} @var{d})} is equivalent to
(cl-psetf @var{a} @var{b}
@var{b} @var{c}
@var{c} @var{d}
@var{d} @var{a})
except for the evaluation of subforms. @code{cl-rotatef} always
returns @code{nil}. Note that @code{(cl-rotatef @var{a} @var{b})}
conveniently exchanges @var{a} and @var{b}.
The following macros were invented for this package; they have no
analogues in Common Lisp.
@defmac cl
(cl-letf (((point) (point-min))
(a 17))
...){cl-letf} on @code{(point)} is not quite like a
@code{save-excursion}, as the latter effectively saves a marker
which tracks insertions and deletions in the buffer. Actually,
a @code{cl{cl{cl-letf} is
to restore the original value of @var{place} afterwards.
@c I suspect this may no longer be true; either way it's
@c implementation detail and so not essential to document.
@ignore
(The redundant access-and-store suggested by the @code{(@var{place}
@var{place})} example does not actually occur.)
Note that in this case, and in fact almost every case, @var{place}
must have a well-defined value outside the @code{cl-letf} body.
There is essentially only one exception to this, which is @var{place}
a plain variable with a specified @var{value} (such as @code{(a 17)}
in the above example).
@c See
@c Some or all of this was true for cl.el, but not for cl-lib.el.
@ignore
The only exceptions are plain variables and calls to
@code{symbol-value} and @code{symbol-function}. If the symbol is not
bound on entry, it is simply made unbound by @code{makunbound} or
@code{fmakunbound} on exit.
@end ignore
|
https://emba.gnu.org/emacs/emacs/-/blame/516e1a08ce36fca220a0eaead731d3fe2d3bb271/doc/misc/cl.texi
|
CC-MAIN-2021-25
|
refinedweb
| 3,560
| 56.66
|
WinJS scheduling
A new scheduler API in Windows 8.1 lets you set the priority of tasks and manage jobs. This helps you write HTML5 apps that use system resources more efficiently and provide a more responsive experience to your users.
Writing apps that are always responsive can be challenging. You can combine multiple, complex UI elements, including ListView controls, SemanticZoom controls, and custom controls that all compete for system resources. Many elements require both immediate foreground work—such as animation— and additional background work.
With Windows 8 and the Windows Library for JavaScript 1.0, there was no single integrated scheduler. A low-priority background task could preempt foreground work and cause unresponsive or stuttering app behavior. Because work was scheduled on different queues, there was no easy way for you to coordinate between the queues to get the prioritization you want.
Windows 8.1 and the Windows Library for JavaScript 2.0 introduces the Scheduler, an object/namespace that consolidates all work queues into a single, universal queue. This new queue has a priority-based scheduling policy that supports fast and fluid apps and a more unified developer experience. You can easily schedule tasks and assign priorities so that the right things get done at the right time.
The Scheduler coordinates with the work performed by the Windows Library for JavaScript and the prioritized, asynchronous work performed by the Windows Runtime. Using the scheduler, you can get your app work scheduled at the correct priority in relation to all other work in the system.
Scheduling jobs
To schedule work, you use the schedule method to create a job. You pass this method a function that performs the task that you want to accomplish. You can also specify a priority for the job. The schedule method returns an object that implements the IJob interface, and you can use this object to pause, resume, and cancel the job that you scheduled.
Here's an example that schedules two simple jobs at normal priority.
For the full code, see the Scheduler sample.
For additional control, your work function can accept an IJobInfo object. You can use this object to determine whether the job should yield, schedule a second job to run after the current job finishes, and specify a function to run if the job yields control.
Managing jobs
The preceding section mentioned that you can use the IJob object returned by the schedule method to pause, cancel, and resume jobs. You can also use the Scheduler object's createOwnerToken method to obtain an IOwnerToken and use it to control any IJob objects it owns.
This example creates several IOwnerToken objects and uses them to set the owner property of several IJob objects. It then uses the IOwnerToken to cancel multiple jobs at once.
var ownerObject1 = S.createOwnerToken(); var ownerObject2 = S.createOwnerToken(); var ownerObject3 = S.createOwnerToken(); // Schedule some work. var job1 = S.schedule(function () { window.output("Running job1 with owner1"); }, S.Priority.normal); job1.owner = ownerObject1; window.output("Scheduled job1 with owner1"); // Schedule some work. var job2 = S.schedule(function () { window.output("Running job2 with owner2"); }, S.Priority.normal); job2.owner = ownerObject2; window.output("Scheduled job2 with owner2"); // Schedule some work. var job3 = S.schedule(function () { window.output("Running job3 with owner1"); }, S.Priority.normal); job3.owner = ownerObject1; window.output("Scheduled job3 with owner1"); // Schedule some work. var job4 = S.schedule(function () { window.output("Running job4 with owner3"); }, S.Priority.normal); job4.owner = ownerObject3; window.output("Scheduled job4 with owner3"); window.output("Canceling jobs with owner1"); ownerObject1.cancelAll();
For the full code, see the Scheduler sample.
For additional examples, including examples that show yielding and draining, see the Scheduler sample.
|
http://msdn.microsoft.com/library/windows/apps/bg182877.aspx
|
CC-MAIN-2014-41
|
refinedweb
| 609
| 51.95
|
Cubic bezier using beziersegment | ActionScript 3 AS3
Published by Nicholas Dunbar on December 27th, 2012
Fast Cubic Bezier in AS3
Because we use the machine code to do the calculations instead of doing them our self in interpreted AS3 this runs very fast.
When you look up Cubic Bezier on the web you find a ton of math and a bunch of libraries for ActionScript 3 (AS3) that have more features than you can shake a cat at. Damn it! I just want a simple solution a bit of code that I can just look at understand and use. Well the simple solution to generating a Cubic Bezier Curve is not using a bunch of fancy math but using a class that is already present amoung the native libraries. Behod the fl.motion.BezierSegment class! Since it is precompiled code, it is also faster than doing your own calculations. Where do you find the fl package? In windows try adding the class path C:/Program Files/Adobe/Adobe Flash CS3/en/Configuration/ActionScript 3.0/Classes
Here is how I use the BezierSegment class to generate a curve:
public class CubicBezier extends BezierSegment {
public function CubicBezier(anchor1:Point, control1:Point, control2:Point, anchor2:Point)
{
if (anchor1 == null || control1 == null || control2 == null || anchor2 == null){
Console.error("null object in CubicBezier constructor!");
}
super(anchor1, control1, control2, anchor2);
}
public function drawInto(g:Graphics):void
{//I use distance here because I want the curve to always be smooth but you may want to optimize this calculation.
var iterations:uint = Point.distance(a,d);
var newPoint:Point;
for (var i:uint; i < iterations; i++)
{
newPoint = this.getValue(i/iterations);
g.lineTo(newPoint.x, newPoint.y);
}
}
}
I extended The BezierSegment class inorder to create my own controler class CubicBezier. Below you will see how I use this class:
var path:CubicBezier;
path = new CubicBezier(anchorPoint1, controlPoint1, controlPoint2, anchorPoint2);
path.drawInto(this.graphics);
[See here for a better description]().
|
https://boulderappsco.postach.io/post/cubic-bezier-using-beziersegment-actionscript-3-as3
|
CC-MAIN-2019-43
|
refinedweb
| 322
| 53.51
|
The.
Terminology
Process – an OS object which represents an isolated address space containing threads.
Thread – an OS object which represents the smallest execution unit. Threads are constituent parts of processes, they divide memory and other resources between each other in the scope of a process.
Multitasking – an OS feature which represents the capability of executing multiple processes simultaneously.
Multi-core – a CPU feature which represents the ability to use multiple cores for data processing
Multiprocessing – the feature of a computer which represents the capability to physically work with multiple CPUs.
Multi-threading – the feature of a process which represents the capability of dividing and spreading the data processing between multiple threads.
Parallelism – simultaneous physical execution of multiple actions in a unit of time
Asynchrony – executing an operation without waiting for it to be fully processed, leaving the calculation of the result for later time.
A Metaphor
Not all definitions are effective and some of them require elaboration, so let me provide a cooking metaphor for the terminology I just introduced.
Making breakfast represents a process in this metaphor.
When making breakfast in the morning, I(CPU) go to the kitchen(Computer). I have two hands(Cores). On the kitchen, there is an assortment of devices(IO): stove, kettle, toaster, fridge. I turn on the stove, put a frying pan on it and pour some vegetable oil in it. Without waiting for the oil to heat (asynchronously, Non-Blocking-IO-Wait), I get some eggs from the fridge, crack them over a bowl and then whip them with one hand(Thread#1). Meanwhile, the second hand(Thread#2) is holding the bowl in place (Shared Resource). I would like to turn on the kettle, but I don’t have enough free hands at the moment (Thread Starvation). While I was whipping the eggs, the frying pan got hot enough (Result processing), so I pour the whipped eggs into it. I reach over to the kettle, turn it on and look at the water being boiled (Blocking-IO-Wait) – but I could have used this time to wash the bowl.
I only used 2 hands while making the omelet (because I don’t have more), but there were 3 simultaneous operations being executed: whipping the eggs, holding the bowl, heating the frying pan. CPU is the fastest part of the computer and IO is the part which requires waiting the most often, so it is quite effective to load the CPU with some work while it’s waiting for the data from IO.
To extend the metaphor:
If I was also trying to change my clothes while making the breakfast, then I would have been multitasking. Computers are way better at this than humans are.
A kitchen with multiple cooks – for example, in a restaurant – is a multi-core computer.
A mall food court with many restaurants would represent a data center.
.NET Tools
.NET is really good when it comes to working with threads – as well as at many other things. With each new version, it provides more tools for working with threads and new OS thread abstraction layers. When working with abstractions, the developers working with the framework are using an approach that allows them to go one or more layers down while using high-level abstractions. In most cases, there is no real need to do this (and doing this may introduce a possibility of shooting yourself in the foot), but sometimes this may be the only way to resolve an issue that cannot be solved on the current abstraction level.
When I said tools earlier, I meant both program interfaces (API) provided by the framework or third-party packages and full-fledged software solutions that simplify the process of searching for issues related to multi-threaded code.
Starting a Thread
The Thread class is the most basic .NET class for working with threads. Its constructor accepts one of these two delegates:
ThreadStart – no parameters
ParametrizedThreadStart – one object-type parameter.
The delegate will be executed in a newly-created thread after calling the Start method. If the ParametrizedThreadStart delegate was passed to the constructor, then an object should be passed to the Start method. This process is needed to pass any local information to the thread. I should point out that it takes a lot of resources to create a thread and the thread itself is a heavy object – at least because it requires interaction with the OS API and 1MB of memory is allocated to the stack.
new Thread(…).Start(…);
The ThreadPool class represents the concept of a pool. In .NET, the thread pool is a piece of engineering art and the Microsoft developers invested much effort to make it work optimally in all sorts of scenarios.
The general concept:
When started, the app creates a few threads in the background, allowing to access them when needed. If threads are used frequently and in great numbers, the pool is expanded to satisfy the needs of the calling code. If the pool doesn’t have enough free threads at the right time, it will either wait for one of the active threads to become unoccupied or create a new one. Based on this, it follows that the thread pool is perfect for short actions and does not work that well for processes that work as services for the whole duration of the application’s operation.
The QueueUserWorkItem method allows to use threads from the pool. This method takes the WaitCallback-type delegate. Its signature coincides with the signature of ParametrizedThreadStart, and the parameter that is passed to it serves the same role.
ThreadPool.QueueUserWorkItem(…)
The less-commonly-known RegisterWaitForSingleObject thread pool method is used to organize non-blocking IO operations. The delegate which is passed to this method will be called when the WaitHandle is released after being passed to the method.
ThreadPool.RegisterWaitForSingleObject(…)
There is a thread timer in .NET, and it differs from the WinForms/WPF timers in that its handler is called in the thread taken from the pool.
System.Threading.Timer
There is also a rather unusual way of sending the delegate to a thread from the pool – the BeginInvoke method.
DelegateInstance.BeginInvoke
I would also like to take a look at the function which many of the methods I mentioned earlier come down to – CreateThread from the Kernel32.dll Win32 API. There is a way to call this function with the help of the methods’ extern mechanism. I have only seen this being used once in a particularly bad case of legacy code – and I still don’t understand what its author’s reasons were.
Kernel32.dll CreateThread
Viewing and Debugging Threads
All threads – whether created by you, third-party components or the .NET pool – can be viewed in the Visual Studio’s Threads window. This window will only display the information about threads when the application is being debugged in the Break mode. Here, you can view the names and priorities of each thread and focus the debug mode on specific threads. The Priority property of the Thread class allows you to set the thread’s priority. This priority will be then taken into consideration when the OS and CLR are dividing processor time between threads.
Task Parallel Library
Task Parallel Library (TPL) has first appeared in .NET 4.0. Currently, it’s the main tool for working with asynchrony. Any code utilizing older approaches will be considered legacy code. TPL’s main unit is the Task class from the System.Threading.Tasks namespace. Tasks represent thread abstraction. With the latest version of C#, we acquired a new elegant way of working with Tasks – the async/await operators. These allow for asynchronous code to be written as if it were simple and synchronous, so those who are not well-versed in the theory of threads can now write apps that won’t struggle with long operations. Using async/await is really a topic for a separate article (or even a few articles), but I’ll try to outline the basics in a few sentences:
async is a modificator of a method which returns a Task or void
await is an operator of a non-blocking wait Task.
Once again: the await operator will usually (there are exceptions) let the current thread go and, when the task will be executed and the thread (actually, the context, but we’ll get back to it later) will be free as a result, it will continue executing the method. In .NET, this mechanism is implemented in the same way as yield return – a method is turned into a finite state machine class that can be executed in separate pieces based on its state. If this sound interesting, I would recommend writing any simple piece of code based on async/await, compiling it and looking at its compilation with the help of JetBrains dotPeek with Compiler Generated Code enabled.
Let’s look at the options we have when it comes to starting and using a task. In the example below, we create a new task which doesn’t actually do anything productive(Thread.Sleep(10000)). However, in real cases we should substitute it with some complex work that utilizes CPU resources.
using TCO = System.Threading.Tasks.TaskCreationOptions;
public static async void AsyncMethod() {
var cancellationSource = new CancellationTokenSource();
await Task.Factory.StartNew(
// Code of action will be executed on other context
() => Thread.Sleep(10000),
cancellationSource.Token,
TCO.LongRunning | TCO.AttachedToParent | TCO.PreferFairness,
scheduler
);
// Code after await will be executed on captured context
}
A task is created with the following options:
LongRunning – this option hints at the fact that the task can not be performed quickly. Therefore, it is possibly better to create a separate thread for this task rather than taking an existing one from the pool to minimize harm to other tasks.
AttachedToParent – Tasks can be arranged hierarchically. If this option is used, the task will be waiting for its children tasks to be executed after being executed itself.
PreferFairness – this option specifies that the task should better be executed before the tasks that were created later. However, it’s more of a suggestion, so the result is not always guaranteed.
The second parameter that was passed to the method is CancellationToken. For the operation to be properly cancelled after it was already started, the executable code should contain CancellationToken state checks. If there are no such checks, then the Cancel method called on the CancellationTokenSource object would only be able to stop the task execution before the task is actually started.
For the last parameter, we sent a TaskScheduler-type object called scheduler. This class, along with its children classes, is used to control how tasks are distributed between threads. By default, a task will be executed on a randomly-selected thread from the pool
The await operator is applied to the created task. This means that the code written after it (if there is such code) will be executed in the same context (often, this means ‘on the same thread’) as the code written before await.
This method is labelled as async void, which means that the await operator can be used in it, but the calling code would no be able to wait for execution. If such possibility is needed, the method should return a Task. Methods labelled as async void can be seen quite often: they are usually event handlers or other methods operating under the fire and forget principle. If it’s necessary to wait for the execution to be finished and return the result, then you should use Task<T>.
For tasks that return the StartNew method, we can call ConfigureAwait with the false parameter – then, the execution after await will be continued on a random context instead of a captured one. This should always be done if the code written after await does not require a specific execution context. This is also a recommendation from MS when it comes to writing code provided as a library.
Let’s look at how we can wait for a Task to be finished. Below, you can see an example piece of code with comments denoting when the waiting is implemented in a relatively good or bad manner.
public static async void AnotherMethod() {
int result = await AsyncMethod(); // good
result = AsyncMethod().Result; // bad
AsyncMethod().Wait(); // bad
IEnumerable<Task> tasks = new Task[] {
AsyncMethod(), OtherAsyncMethod()
};
await Task.WhenAll(tasks); // good
await Task.WhenAny(tasks); // good
Task.WaitAll(tasks.ToArray()); // bad
}
In the first example, we are waiting for the Task to be executed without blocking the calling thread, so we’ll come back to processing the result when it’s ready. Before that happens, the calling thread is left on its own.
In the second attempt, we are blocking the calling thread until the method’s result is calculated. This is a bad approach for two reasons. First of all, we are wasting a thread – a very valuable resource – on simple waiting. Additionally, if the method we’re calling contains an await while a return to the calling thread after await is intended by the synchronization context, we’ll get a deadlock. This happens because the calling thread will be waiting for the result of an asynchronous method, and the asynchronous method itself will be fruitlessly trying to continue its execution in the calling thread.
Another disadvantage of this approach is the increased complexity of error handling. The errors can actually be handled rather easily in asynchronous code if async/await is used – the process in this case is identical to that in synchronous code. However, when a synchronous wait is applied to a Task, the initial exception is wrapped in AggregateException. In other words, to handle the exception, we would need to explore the InnerException type and manually write an if chain in a catch block or, alternatively, use the catch when structure instead of the more usual chain of catch blocks.
The two last examples are also labelled as relatively bad for the same reasons and both contain the same issues.
The WhenAny and WhenAll methods are very useful when it comes to waiting for a group of Tasks – they wrap these tasks into one, and it will be executed either when one Task from the group is started or when all of these tasks are successfully executed.
Stopping Threads
For various reasons, there may be a need to stop a thread after it has been started. There are a few ways to do this. The Thread class has two methods with appropriate names — Abort and Interrupt. I would strongly discourage using the first one as, after it’s called, there would be a ThreadAbortedException thrown at any random moment while processing any arbitrarily chosen instruction. You’re not expecting such an exception to be encountered when an integer variable is incremented, right? Well, when using the Abort method, this becomes a real possibility. In case you need to deny the CLR’s ability of creating such exceptions in a specific part of the code, you can wrap it in the Thread.BeginCriticalRegion and Thread.EndCriticalRegion calls. Any code written in the finally block is wrapped in these calls. This is why you can find blocks with an empty try and a non-empty finally in the depths of the framework code. Microsoft dislike this method to the extent of not including it in the .NET core.
The Interrrupt method works in a much more predictable way. It can interrupt a thread with a ThreadInterruptedException only when the thread is in the waiting mode. It moves to this state when suspended while waiting for WaitHandle, a lock or after Thread.Sleep is called.
Both of these ways have a disadvantage of unpredictability. To escape this issue, we should use the CancellationToken structure and the CancellationTokenSource class. The general idea is this: an instance of the CancellationTokenSource class is created, and only those who own it can stop the operation by calling the Cancel method. Only CancellationToken is passed to the operation. CancellationToken’s owners cannot cancel the operation themselves – they can only check whether the operation has been cancelled. This can be achieved by using a Boolean property IsCancellationRequested and the ThrowIfCancelRequested method. The last one will generate a TaskCancelledException if the Cancel method has been called on the CancellationTokenSource instance which created the CancellationToken. This is the method I recommend using. It’s advantage over the previously-described methods lies in the fact that it provides full control over the exact exception cases in which an operation can be cancelled.
The most brutal way to stop a thread would be to call a Win32 API function called TerminateThread. After this function is called, the CLR’s behavior can be quite unpredictable. In MSDN, the following is written about this function: “TerminateThread is a dangerous function that should only be used in the most extreme cases. “
Turning a Legacy API Into a Task-Based One by Using FromAsync
If you were fortunate enough to work on a project which was started after the Tasks have been introduced (and when they are no longer inciting existential horror in most of developers), you will not have to deal with old APIs – both the third-party ones and those your team toiled on in the past. Fortunately, the .NET Framework development team made it easier for us – but this could have been self-care, for all we know. In any case, .NET has a few tools which help with seamlessly bringing the code written with old aprroaches to asynchrony in mind to an up-to-date form. One of these is the TaskFactory method called FromAsync. In the example below, I’m wrapping the old asynchronous methods of the WebRequest class into a Task by using FromAsync.
object state = null;
WebRequest wr = WebRequest.CreateHttp(“”);
await Task.Factory.FromAsync(
wr.BeginGetResponse,
we.EndGetResponse
);
It’s only an example, and you probably won’t be doing something of this sort with built-in types. However, old projects teem with BeginDoSomething methods that return IAsyncResult and EndDoSomething methods that receive them.
Turning a Legacy API Into a Task-Based One by Using TaskCompletionSource
Another tool worth exploring is the TaskCompletionSource class. In its functionality, purpose and operation principle, it resembles the RegisterWaitForSingleObject method from the ThreadPool class I mentioned earlier. This class allows us to easily wrap old asynchronous APIs into Tasks.
You may want to say that I already told about the FromAsync method from the TaskFactory class which served these purposes. Here, we would need to remember the full history of asynchronous models Microsoft provided in the last 15 years: before Task-Based Asynchronous Patterns (TAP), there were Asynchronous Programming Patterns (APP). APPs were all about BeginDoSomething returning IAsyncResult and the EndDoSomething method which accepts it – and the FromAsync method is perfect for these years’ legacy. However, as time passed, this was replaced with Event Based Asynchronous Patterns(EAP) which specified that an event is called when an asynchronous operation is successfully executed.
TaskCompletionSource are perfect for wrapping legacy APIs built around the event model into Tasks. This is how it works: objects of this class have a public property called Task<T>, the state of which can be controlled by various methods of the TaskCompletionSource class (SetResult, SetException etc.). In places where the await operator was applied to this Task, it will be executed or crashed with an exception depending on the method applied to TaskCompletionSource. To understand it better, let’s look at this example piece of code. Here, some old API from the EAP era is wrapped in a Task with the help of TaskCompletionSource: when an event is triggered, the Task will be switched to the Completed state while the method that applied the await operator to this Task will continue its execution after receiving a result object.
public static Task<Result> DoAsync(this SomeApiInstance someApiObj) {
var completionSource = new TaskCompletionSource<Result>();
someApiObj.Done +=
result => completionSource.SetResult(result);
someApiObj.Do();
result completionSource.Task;
TaskCompletionSource Tips & Tricks
TaskCompletionSource can do more than just wrapping obsolete APIs. This class opens an interesting possibility of designing various APIs based on Tasks that don’t occupy threads. A thread, as we remember, is a expensive resource limited mostly by RAM. We can easily reach this limit when developing a robust web application with complex business logic. Let’s look at the capabilities I mentioned in action by implementing a neat trick known as Long Polling.
In short, this is how Long Polling works:
You need to get some information from an API about events occurring on its side, but the API, for some reason, can only return a state rather than telling you about the event. An example of such would be any API built over HTTP before WebSocket appeared or in circumstances under which this technology can’t be used. The client can ask the HTTP server. The HTTP server, on the other hand, cannot initiate contact with the client by itself. The simplest solution would be to ask the server periodically using a timer, but this would create additional load for the server and a general delay which approximately equals to TimerInterval / 2. To bypass this, Long Polling was invented. It entails delaying the server response until the Timeout expires or an event happens. If an event occurs, it will be handled; if not – the request will be sent again.
A cycle begs to be written:
while(!eventOccures && !timeoutExceeded) {
CheckTimout();
CheckEvent();
Thread.Sleep(1);
}
However, this solution’s effectiveness will radically drop should the number of clients waiting for the event grow – each waiting client occupies a full thread. Also, we get an additional delay of 1ms for event triggering. Often, it’s not really that crucial, but why would we make our software worse than it could be? On the other hand, if we remove Thread.Sleep(1), one of the CPU cores will be loaded for the full 100% while doing nothing in a useless cycle. With the help of TaskCompletionSource, we can easily transform our code to resolve all of the issues we mentioned:
class LongPollingApi {
private Dictionary<int, TaskCompletionSource<Msg>> tasks;
public async Task<Msg> AcceptMessageAsync(int userId, int duration) {
var cs = new TaskCompletionSource<Msg>();
tasks[userId] = cs;
await Task.WhenAny(Task.Delay(duration), cs.Task);
return cs.Task.IsCompleted ? cs.Task.Result : null;
}
public void SendMessage(int userId, Msg m) {
if (tasks.TryGetValue(userId, out var completionSource))
completionSource.SetResult(m);
}
}
Please keep in mind that this piece of code is only an example, and in no way production-ready. To use it in real cases, we would at least need to add a way to handle situations in which a message is received when nothing was waiting for it: in this case, the AcceptMessageAsync method should return an already finished Task. If this case is the most common one, we can consider using ValueTask.
When receiving a message request, we create a TaskCompletionSource, place it in a dictionary, and then wait for one of the following events: either the specified time interval is spent or a message is received.
ValueTask: Why and How
async/await operators, just like the yield return operator, generate a finite state machine from a method, which means creating a new object – this doesn’t really matter most of the time, but can still create issues in some rare cases. One of these cases can occur with frequently-called methods – we’re talking tens and hundreds of thousands calls per second. If such a method is written in a way which makes it return the result while bypassing all await methods in most of the cases, .NET provides an optimization tool for this – the ValueTask structure. To understand how it works, let’s look at an example. Suppose there is a cache we access on a regular basis. If there are any values in it, we just return them; if there are no values – we try to get them from some slow IO. The latter should ideally be done asynchronously, so the whole method will be asynchronous. So, the most obvious way to implement this method will be as follows:
public async Task<string> GetById(int id) {
if (cache.TryGetValue(id, out string val))
return val;
return await RequestById(id);
}
With a desire to optimize it a little bit and a concern for what Roslyn will generate when compiling this code, we could re-write the method like this:
public Task<string> GetById(int id) {
if (cache.TryGetValue(id, out string val))
return Task.FromResult(val);
return RequestById(id);
}
However, the best solution in this case would be to optimize hot-path – specifically, getting dictionary values with no unnecessary allocations and no load on GC. Meanwhile, in those infrequent cases when we need to get data from IO, things will remain almost the same:
public ValueTask<string> GetById(int id) {
if (cache.TryGetValue(id, out string val))
return new ValueTask<string>(val);
return new ValueTask<string>(RequestById(id));
}
Let’s look at this code fragment more closely: if a value is present in the cache, we’ll create a structure; otherwise, the real task will be wrapped in a ValueTask. The path by which this code is executed is not important for the calling code: from the perspective of C# syntax, a ValueTask will behave just like a usual Task.
TaskScheduler: Controlling Task Execution Strategies
The next API I’d like to talk about is the TaskScheduler class and those derived from it. I already mentioned that TPL provides an ability to control how exactly Tasks are being distributed between threads. These strategies are defined in classes inheriting from TaskScheduler. Almost any strategy we may need can be found in the ParallelExtensionsExtras library. This library is developed by Microsoft, but is not a part of .NET – rather, it’s distributed as a Nuget package. Let’s have a look at some of the strategies:
CurrentThreadTaskScheduler – executes Tasks on the current thread
LimitedConcurrencyLevelTaskScheduler – limits the number of concurrently executed Tasks by using the N parameter which it accepts in the constructor
OrderedTaskScheduler – is defined as LimitedConcurrencyLevelTaskScheduler(1), so Tasks will be executed sequentially.
WorkStealingTaskScheduler – implements the work-stealing approach to task execution. Essentially, it can be viewed as a separate ThreadPool. This helps with the issue of ThreadPool being a static class in .NET — if it’s overloaded or used improperly in one part of the application, unpleasant side effects may occur in a different place. Real causes of such defects can be difficult to locate, so you may need to use separate WorkStealingTaskSchedulers in those parts of the application where ThreadPool usage can be aggressive and unpredictable.
QueuedTaskScheduler – allows to execute tasks on a basis of a prioritized queue
ThreadPerTaskScheduler – creates a separate thread for each Task that’s executed on it. This can be helpful for tasks the execution time of which cannot be estimated.
There is a very good article about TaskSchedulers on Microsoft’s blog, so feel free to check it out.
In Visual Studio, there is a Task window which can help with debugging everything related to Tasks. In this window, you can see the task’s state and jump to the currently executed line of code.
PLinq and the Parallel Class
Aside from Tasks and all things related to them, there are two additional tools in .NET we can find interesting – PLinq(Linq2Parallel) and the Parallel class. The first one promises parallel execution of all Linq operations on all threads. The number of threads can be configured by an extension method WithDegreeOfParallelism. Unfortunately, in most cases, PLinq in the default mode will not have enough information about the data source to provide a significant increase in speed. On the other hand, the cost of trying is very low: you only need to call AsParallel before the chain of Linq methods and carry out performance tests. Moreover, you can pass additional information about the nature of your data source to PLinq by using the Partitions mechanism. You can find more information here and here.
The Parallel static class provides methods for enumerating collections in parallel via Foreach, running the For cycle and executing several delegates in parallel to Invoke. Execution of the current thread will be stopped until the results are calculated. You can configure the number of threads by passing ParallelOptions as the last argument. TaskScheduler and CancellationToken can also be set with the help of options.
Summary
When I started writing this article based on my thesis and on the knowledge I gained while working after it, I didn’t think there would be this much information. Now, with the text editor reproachfully telling me that I’ve written almost 15 pages, I’d like to draw an intermediary conclusion. We will look at other techniques, APIs, visual tools and hidden hazards in the next article.
Conclusions:
To effectively use the resources of modern PCs, you would need to know tools for working with threads, asynchrony and parallelism.
There are many tools like this in .NET
Not all of them were created at the same time, so you may often encounter some legacy code – but there are ways of transforming old APIs with little effort.
In .NET, the Thread and ThreadPool classes are used for working with threads
The Thread.Abort and Thread.Interrupt method, along with the Win32 API function TerminateThread, are dangerous and not recommended for use. Instead, it’s better to use CancellationTokens
Threads are a valuable resource and their number is limited. You should avoid cases in which threads are occupied by waiting for events. The TaskCompletionSource class can help achieve this.
Tasks are the most powerful and robust tool .NET has for working with parallelism and asynchrony.
The async/await C# operators implement the concept of a non-blocking wait
You can control how Tasks are distributed between threads with the help of classes derived from TaskScheduler
The ValueTask structure can be used to optimize hot-paths and memory-traffic
The Tasks and Threads windows in Visual Studio provide a lot of helpful information for debugging multi-threaded or asynchronous code
PLinq is an awesome tool, but it may not have all required information about your data source – which can still be fixed with the partitioning mechanism
To be continued…
The post .NET: Tools for working with multi-threading and asynchrony – Part 1 appeared first on {coding}Sight.
|
https://online-code-generator.com/net-tools-for-working-with-multi-threading-and-asynchrony-part-1/
|
CC-MAIN-2021-43
|
refinedweb
| 5,058
| 52.39
|
This section describes some philosophical and technical design issues that have broad implications for the way your API will operate.
Various forms of REST, or Representational State Transfer, are currently the preferred style for writing APIs. The REST style was developed as a PhD dissertation by Roy Fielding, who was one of the authors of the HTTP protocol.
In essence, Fielding proposed using HTTP for inter-computer communications. Consequently, REST is based on the HTTP standard. Using the building blocks of HTTP, it divides the namespace into a set of “resources” based on unique URI patterns and uses the standard HTTP verbs—GET, POST, PUT, and DELETE—to map operations on top of those resources. These standard HTTP verbs map to the verbs create, read, update, and delete, familiar to generations of programmers as CRUD.
No credit card required
|
https://www.safaribooksonline.com/library/view/apis-a-strategy/9781449321628/ch05s03.html
|
CC-MAIN-2018-30
|
refinedweb
| 139
| 54.22
|
tap_tubewarmth - A port of Tom Szilagyi's TAP TubeWarmth LADSPA plugin to a Csound User-Defined OpcodeDownload UDO File
This is a port of Tom Szilagyi's TAP TubeWarmth LADSPA plugin to a Csound User-Defined Opcode.
From Tom Szilagyi's description:
"TAP TubeWarmth adds the character of vacuum tube amplification to your audio tracks by emulating the sonically desirable nonlinear characteristics of triodes. In addition, this plugin also supports emulating analog tape saturation."
More information about the original plugin here:
aout tap_tubewarmth ain, kdrive, kblend
ain - audio input signal
kdrive - Values between 2 and 5 are a good starting point for a variety of source materials. Since audio tracks can vary quite a bit in average and peak levels, experiment with this setting and use your ears to get the sound you want. (It's quite easy if you know how real tube amps sound like...) If the drive level is set too high, the signal will most likely sound distorted. If it's too low, you may not hear the effect working.
kblend - controls the colour of the TubeWarmth sound. When set all the way to the right (+10 or default position), the plugin emulates the sound of triode tube distortion. The result is asymmetrical, producing mostly second harmonics and some third. When set all the way to the left (-10), the plugin emulates the sound of analog tape. The result is symmetrical and produces mostly third harmonics and some second. With high drive settings, moving the blend control to the left increases the apparent loudness of low-level signals dramatically. This is because the zero-attack, zero-release compression effect is increased under these conditions. Use the blend control to set the sound of the plugin anywhere between Tape and Tube sound.
(The above descriptions of drive and blend were taken from Tom Szilagyi's Description of his plugin)
opcode tap_tubewarmth,a,akk setksmps 1 ain, kdrive, kblend xin kdrive limit kdrive, 0.1, 10 kblend limit kblend, -10, 10 kprevdrive init 0 kprevblend init 0 krdrive init 0 krbdr init 0 kkpa init 0 kkpb init 0 kkna init 0 kknb init 0 kap init 0 kan init 0 kimr init 0 kkc init 0 ksrct init 0 ksq init 0 kpwrq init 0 #define TAP_EPS # 0.000000001 # #define TAP_M(X) # $X = (($X > $TAP_EPS || $X < -$TAP_EPS) ? $X : 0) # #define TAP_D(A) # if ($A > $TAP_EPS) then $A = sqrt($A) elseif ($A < $TAP_EPS) then $A = sqrt(-$A) else $A = 0 endif # if (kprevdrive != kdrive || kprevblend != kblend) then krdrive = 12.0 / kdrive; krbdr = krdrive / (10.5 - kblend) * 780.0 / 33.0; kkpa = 2.0 * (krdrive*krdrive) - 1.0 $TAP_D(kkpa) kkpa = kkpa + 1.0; kkpb = (2.0 - kkpa) / 2.0; kap = ((krdrive*krdrive) - kkpa + 1.0) / 2.0; kkc = 2.0 * (krdrive*krdrive) - 1.0 $TAP_D(kkc) kkc = 2.0 * kkc - 2.0 * krdrive * krdrive $TAP_D(kkc) kkc = kkpa / kkc ksrct = (0.1 * sr) / (0.1 * sr + 1.0); ksq = kkc*kkc + 1.0 kknb = ksq $TAP_D(kknb) kknb = -1.0 * krbdr / kknb kkna = ksq $TAP_D(kkna) kkna = 2.0 * kkc * krbdr / kkna kan = krbdr*krbdr / ksq kimr = 2.0 * kkna + 4.0 * kan - 1.0 $TAP_D(kimr) kimr = 2.0 * kknb + kimr kpwrq = 2.0 / (kimr + 1.0) kprevdrive = kdrive kprevblend = kblend endif aprevmed init 0 amed init 0 aprevout init 0 kin downsamp ain if (kin >= 0.0) then kmed = kap + kin * (kkpa - kin) $TAP_D(kmed) amed = (kmed + kkpb) * kpwrq else kmed = kap - kin * (kkpa + kin) $TAP_D(kmed) amed = (kmed + kkpb) * kpwrq * -1 endif aout = ksrct * (amed - aprevmed + aprevout) kout downsamp aout kmed downsamp amed if (kout < -1.0) then aout = -1.0 kout = -1.0 endif $TAP_M(kout) $TAP_M(kmed) aprevmed = kmed aprevout = kout #undef TAP_D #undef TAP_M #undef TAP_EPS xout aout endop
Original LADSPA Code by Tom Szilagyi, Csound UDO code by Steven Yi (2006.08.31)
|
http://www.csounds.com/udo/displayOpcode.php?opcode_id=80
|
CC-MAIN-2016-18
|
refinedweb
| 642
| 76.72
|
a. This allows for data to be communicated back and forth, which is ideal for things like real-time chat applications, or even games.:
GET /ws/chat HTTP/1.1 Host: chat.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: q1PZLMeDL4EwLkw4GGhADm== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 15 Origin:
The server then sends back an HTTP 101 "Switching Protocols" response, acknowledging that the connection is going to be upgraded. Once the this connection has been made, it switches to a bidirectional binary protocol, at which point the application data can be sent.
All the protocol has to do to keep the connection open is send some ping/pong packets, which tells the other side that they're still there. To close the connection, a simple "close connection" packet is sent.
Some Websocket Examples
Of the many different websocket libraries for Node.js available to us, I chose to use socket.io throughout this article because it seems to be the most popular and is, in my opinion, the easiest to use. While each library has its own unique API, they also have many similarities since they're all built on top of the same protocol, so hopefully you'll be able to translate the code below to any library you want to use.
For the HTTP server, I'll be using Express, which is the most popular Node server out there. Keep in mind that you can also just use the plain http module if you don't need all of the features of Express. Although, since most applications will use Express, that's what we'll be using as well.
Note: Throughout these examples I have removed much of the boilerplate code, so some of this code won't work out of the box. In most cases you can refer to the first example to get the boilerplate code.
Establishing the Connection
In order for a connection to be established between the client and server, the server must do two things:
- Hook in to the HTTP server to handle websocket connections
- Serve up the
socket.io.jsclient library as a static resource
In the code below, you can see item (1) being done on the 3rd line. Item (2) is done for you (by default) by the
socket.io library and is served on the path
/socket.io/socket.io.js. By default, all websocket connections and resources are served within the
/socket.io path.
Server
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); server.listen(8080);
The client needs to do two things as well:
- Load the library from the server
- Call
.connect()to the server address and websocket path
Client
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('/'); </script>
If you navigate your browser to and inspect the HTTP requests behind the scenes using your browser's developer tools, you should be able to see the handshake being executed, including the GET requests and resulting HTTP 101 Switching Protocols response.
Sending Data from Server to Client
Okay, now on to some of the more interesting parts. In this example we'll be showing you the most common way to send data from the server to the client. In this case, we'll be sending a message to a channel, which can be subscribed to and received by the client. So, for example, a client application might be listening on the 'announcements' channel, which would contain notifications about system-wide events, like when a user joins a chat room.
On the server this is done by waiting for the new connection to be established, then by calling the
socket.emit() method to send a message to all connected clients.
Server
io.on('connection', function(socket) { socket.emit('announcements', { message: 'A new user has joined!' }); });
Client
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('/'); socket.on('announcements', function(data) { console.log('Got announcement:', data.message); }); </script>
Sending Data from Client to Server
But what would we do when we want to send data the other way, from client to server? It is very similar to the last example, using both the
socket.emit() and
socket.on() methods.
Server
io.on('connection', function(socket) { socket.on('event', function(data) { console.log('A client sent us this dumb message:', data.message); }); });
Client
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('/'); socket.emit('event', { message: 'Hey, I have an important message!' }); </script>
Counting Connected Users
This is a nice example to learn since it shows a few more features of
socket.io (like the
disconnect event), it's easy to implement, and it is applicable to many webapps. We'll be using the
connection and
disconnect events to count the number of active users on our site, and we'll update all users with the current count.
Server
var numClients = 0; io.on('connection', function(socket) { numClients++; io.emit('stats', { numClients: numClients }); console.log('Connected clients:', numClients); socket.on('disconnect', function() { numClients--; io.emit('stats', { numClients: numClients }); console.log('Connected clients:', numClients); }); });
Client
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('/'); socket.on('stats', function(data) { console.log('Connected clients:', data.numClients); }); </script>
A much simpler way to track the user count on the server would be to just use this:
var numClients = io.sockets.clients().length;
But apparently there are some issues surrounding this, so you might have to keep track of the client count yourself.
Rooms and Namespaces
Chances are as your application grows in complexity, you'll need more customization with your websockets, like sending messages to a specific user or set of users. Or maybe you want need strict separation of logic between different parts of your app. This is where rooms and namespaces come in to play.
Note: These features are not part of the websocket protocol, but added on top by
socket.io.
By default,
socket.io uses the root namespace (
/) to send and receive data. Programmatically, you can access this namespace via
io.sockets, although many of its methods have shortcuts on
io. So these two calls are equivalent:
io.sockets.emit('stats', { data: 'some data' }); io.emit('stats', { data: 'some data' });
To create your own namespace, all you have to do is the following:
var iosa = io.of('/stackabuse'); iosa.on('connection', function(socket){ console.log('Connected to Stack Abuse namespace'): }); iosa.emit('stats', { data: 'some data' });
Also, the client must connect to your namespace explicitly:
<script src="/socket.io/socket.io.js"></script> <script> var socket = io('/stackabuse'); </script>
Now any data sent within this namespace will be separate from the default
/ namespace, regardless of which channel is used.
Going even further, within each namespace you can join and leave 'rooms'. These rooms provide another layer of separation on top of namespaces, and since a client can only be added to a room on the server side, they also provide some extra security. So if you want to make sure users aren't snooping on certain data, you can use a room to hide it.
To be added to a room, you must
.join() it:
io.on('connection', function(socket){ socket.join('private-message-room'); });
Then from there you can send messages to everyone belonging to the given room:
io.to('private-message-room').emit('some event');
And finally, call
.leave() to stop getting event messages from a room:
socket.leave('private-message-room');
Conclusion
This is just one library that implements the websockets protocol, and there are many more out there, all with their own unique features and strengths. I'd advise trying out some of the others (like node-websockets) so you get a feel for what's out there.
Within just a few lines, you can create some pretty powerful applications, so I'm curious to see what you can come up with!
Have some cool ideas, or already created some apps using websockets? Let us know in the comments!
|
http://stackabuse.com/node-js-websocket-examples-with-socket-io/
|
CC-MAIN-2018-26
|
refinedweb
| 1,351
| 58.69
|
MS Dynamics CRM 3.0
Could you please point out how I can make this code more compact/cleaner/smarter??? Gotta be a block..I just don't see how to connect it.
Gratefully,
Chas
<------Switch File Names--->
ar = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"] br = ["first.txt", "second.txt", "third.txt", "fourth.txt", "fifth.txt"]
length = ar.length class FileNameSwap def switch( letters, ordinals, length) for i in 0..length -1 if File.file?(letters[i]) File.rename(letters[i], ordinals[i]) puts "switched to ordinal" else File.rename(ordinals[i], letters[i]) puts "switch to letter" end end end end
switcher = FileNameSwap.new switcher.switch(ar,br, length)
<---end---->
-- Posted via.
The only problem would be the ordinals[i] which could stay as it is and note your own iterations (not recommended) or do, instead of letters.each, do letters.each_index do |i| and little would change.
Both suggestions would rid you of needing the length argument, but to be honest that's the only real disadvantage to your algorithm. It's pretty much fine how it is. You should only change it if it's really hard to find length in my opinion.
HTH, Sebastian Hungerecker -- NP: Sentenced - Blood & Tears Ist so, weil ist so Bleibt so, weil war so
- Hide quoted text -
> I'll try:
> ar = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"] > br = ["first.txt", "second.txt", "third.txt", "fourth.txt", "fifth.txt"]
>
def switch(letters, ordinals) letters.zip(ordinals).each do |*a| File.rename(*(File.file? a[0] ? a : a.reverse)) end end
:-)
robert
PS: Sorry to all who expected an #inject solution. ;-)
|
http://www.megasolutions.net/ruby/How-to-improve-iteration-78188.aspx
|
CC-MAIN-2014-10
|
refinedweb
| 276
| 70.29
|
Hi,
I am using Arduino for many years now. There are some issues which I often face. The first difficulty I face is with the documentation for libraries.
Let me give you an example.
I was working with Serial communication with Arduino.
I defined something like
int rgb;
In the loop(), I wanted to use
Serial1.write(rgb,5);
Obviously, it will give me an error, and then I will have a look at the documentation. first, looking at Serial.write() documentation will not say anything about the type of an array one must have to send the data over serial
The next thing I was doing was looking at Arduino array documentation.
By looking there also one will not get any information as the array can also be of type int.
Then, I had googled it but didn’t find an example, as a result, I struggled and changed every bit of a code one by one, and by luck, I ended up with the right syntax.
Am I missing anything?
#include <Arduino_APDS9960.h> #include <Wire.h> int r,g,b,c; float sum; int rgb[5]; //Here was an issue that I must have char array to send over UART but the official //documentation of Serial.write() or Arduino array doest' give a clue!! void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial1.begin(9600); Wire.begin(); if (!APDS.begin()) { Serial.println("Error initializing APDS9960 sensor."); } } void loop() { // put your main code here, to run repeatedly: while(!APDS.colorAvailable()){ delay(10); } APDS.readColor(r,g,b,c); sum = r+g+b; delay(100); int redratio = r / sum; int greenratio = g / sum; int blueratio = b / sum; rgb[1]=r; rgb[2]=g; for(int i=0;i<5;i++){ rgb[i]==i; } if(Serial1.available()){ Serial1.write(redratio); Serial1.write(greenratio); Serial1.write(blueratio); Serial1.write(rgb,5); } else{ Serial.println("Serial is not availble"); } }
|
https://forum.arduino.cc/t/anyone-else-facing-problems-with-arduino-documentation/688381
|
CC-MAIN-2021-31
|
refinedweb
| 321
| 59.19
|
I have this piece of code which creates a note and adds to the notebook. When I run this I get a Iteration over non-sequence error.
import datetime class Note: def __init__(self, memo, tags): self.memo = memo self.tags = tags self.creation_date = datetime.date.today() def __str__(self): return 'Memo={0}, Tag={1}'.format(self.memo, self.tags) class NoteBook: def __init__(self): self.notes = [] def add_note(self,memo,tags): self.notes.append(Note(memo,tags)) if __name__ == "__main__": firstnote = Note('This is my first memo','example') print(firstnote) Notes = NoteBook() Notes.add_note('Added thru notes','example-1') Notes.add_note('Added thru notes','example-2') for note in Notes: print(note.memo)
Error:
C:Python27BasicsOOPformytesting>python notebook.py Memo=This is my first memo, Tag=example Traceback (most recent call last): File "notebook.py", line 27, in for note in Notes: TypeError: iteration over non-sequence
Solution #1:
You are trying to iterate over the object itself, which is returning the error. You want to iterate over the list inside the object, in this case
Notes.notes (which is somewhat confusing naming, you may want to distinguish the internal list by using another name for the instance of the notebook object).
for note in Notes.notes: print(note.memo)
Solution #2:
Notes is an instance of
NoteBook. To iterate over such an object, it needs an
__iter__ method:
class NoteBook: def __iter__(self): return iter(self.notes)
PS. It is a PEP8 recommendation/convention in Python to use lowercase variable names for instances of classes, and CamelCase for class names.
Following this convention will help you instantly recognize your class instances from your classes.
If you wish to follow this convention (and endear yourself to others who like this convention), change
Notes to
notes.
Solution #3:
If you wanted to actually iterate Notes itself, you could also add a custom
__iter__ method to it that returns the .notes property.
class Notebook: def __iter__(self): return iter(self.notes) ...
Solution #4:
The problem is in the line
for note in Notes: since Notes is an object not a list. I believe you want
for note in Notes.notes:
also as unutbu pointed out, you can overload the
__iter__ operator which will allow your current loop to work. It depends how you want this to outwardly appear. Personally I would overload
__iter__
|
https://techstalking.com/programming/question/solved-python-iteration-over-non-sequence/
|
CC-MAIN-2022-40
|
refinedweb
| 392
| 59.7
|
Pipes.Text.IO
Synopsis
- fromHandle :: MonadIO m => Handle -> Producer Text m ()
- stdin :: MonadIO m => Producer Text m ()
- readFile :: MonadSafe m => FilePath -> Producer Text m ()
- toHandle :: MonadIO m => Handle -> Consumer' Text m r
- stdout :: MonadIO m => Consumer' Text m ()
- writeFile :: MonadSafe m => FilePath -> Consumer' Text m ()
Text IO
Where pipes
IO replaces lazy
IO,
Producer Text IO r replaces lazy
Text.
This module exports some convenient functions for producing and consuming
pipes
Text in
IO, namely,
readFile,
writeFile,
fromHandle,
toHandle,
stdin and
stdout. Some caveats described below.
The main points are as in Pipes.ByteString:
A
Handle can be associated with a
Producer or
Consumer according
as it is read or written to.
import Pipes import qualified Pipes.Text as Text import qualified Pipes.Text.IO as Text import System.IO main = withFile "inFile.txt" ReadMode $ \hIn -> withFile "outFile.txt" WriteMode $ \hOut -> runEffect $ Text.fromHandle hIn >-> Text.toHandle hOut
To stream from files, the following is perhaps more Prelude-like (note that it uses Pipes.Safe):
import Pipes import qualified Pipes.Text as Text import qualified Pipes.Text.IO as Text import Pipes.Safe main = runSafeT $ runEffect $ Text.readFile "inFile.txt" >-> Text.writeFile "outFile.txt"
Finally, you can stream to and from
stdin and
stdout using the predefined
stdin
and
stdout pipes, as with the following "echo" program:
main = runEffect $ Text.stdin >-> Text.stdout
Caveats
The operations exported here are a convenience, like the similar operations in
Data.Text.IO (or rather,
Data.Text.Lazy.IO, since, again,
Producer Text m r is
'effectful text' and something like the pipes equivalent of lazy Text.)
- Like the functions in
Data.Text.IO, they attempt to work with the system encoding.
- Like the functions in
Data.Text.IO, they significantly slower than ByteString operations. Where you know what encoding you are working with, use
Pipes.ByteStringand
Pipes.Text.Encodinginstead, e.g.
view utf8 Bytes.stdininstead of
Text.stdin
- Like the functions in
Data.Text.IO, they use Text exceptions, not the standard Pipes protocols.
Something like
view utf8 . Bytes.fromHandle :: Handle -> Producer Text IO (Producer ByteString m ())
yields a stream of Text, and follows standard pipes protocols by reverting to (i.e. returning) the underlying byte stream upon reaching any decoding error. (See especially the pipes-binary package.)
By contrast, something like
Text.fromHandle :: Handle -> Producer Text IO ()
supplies a stream of text returning '()', which is convenient for many tasks,
but violates the pipes
pipes-binary approach to decoding errors and
throws an exception of the kind characteristic of the
text library instead.
Producers
fromHandle :: MonadIO m => Handle -> Producer Text m ()
readFile :: MonadSafe m => FilePath -> Producer Text m ()
Stream text from a file in the simple fashion of
Data.Text.IO
>>>
runSafeT $ runEffect $ Text.readFile "hello.hs" >-> Text.map toUpper >-> hoist lift Text.stdoutMAIN = PUTSTRLN "HELLO WORLD"
Consumers
toHandle :: MonadIO m => Handle -> Consumer' Text m r
Convert a text stream into a
Handle
Note: again, for best performance, where possible use
(for source (liftIO . hPutStr handle)) instead of
(source >-> toHandle handle).
stdout :: MonadIO m => Consumer' Text m ()
|
https://hackage.haskell.org/package/pipes-text-0.0.0.12/docs/Pipes-Text-IO.html
|
CC-MAIN-2015-40
|
refinedweb
| 504
| 52.05
|
student info
information using jsp and servelts
Hi Friend,
Please visit the following links:
The above links will be helpful
additinal info - JSP-Interview Questions
and grade for your purpose.
Thanks
seeking info - JSP-Servlet
seeking info Looking for the information on Java, JSP and Servlet... codes. - JSP... and JSP-Servlet Programs.Then check your program for all necessary files.I guess
info button iphone example
info button iphone example I'm looking for a simple info button example in iPhone XCode.
Thanks
thanks - JSP-Servlet
thanks thanks sir i am getting an output...Once again thanks for help
The info Attribute of page Directive In JSP
The info Attribute of page Directive In JSP
... about the info
attribute of the page directive in JSP. This attribute simply... is the JSP code:
<%@page info="This is the example of info
attribute
thanks - JSP-Servlet
thanks thanks sir its working
Vendor Info Error - WebSevices
Vendor Info Error Hi,
i wrote the code for Vendor Information using java script. If its full time the vendor info alert box is not displayed....
Thanks
The info Attribute of page Directive In JSP
The info Attribute of page Directive In JSP
... about the info
attribute of the page directive in JSP. This attribute simply... is the JSP code:
<%@page info="This is the example of info
Page Directive attribute - info
Page Directive attribute - info
This tutorial contains description of info attribute of page Directive.
info Attribute :
info attribute of page directives sets the information of the JSP page which
can be retrieved me
The "isThreadSafe" & "info" Attribute of JSP page directive
;info
"attribute of JSP
page directive.
The "isThreadSafe" attribute of JSP page Directive
This attribute tells us whether thread...The "isThreadSafe" & "info" Attribute of JSP page
how to return to main menu after adding all the info. - Java Beginners
how to return to main menu after adding all the info. import java.util.Scanner;
public class RegistrationSystem {
public static void main...()+" " +s.getName());
}
}
}
}
Thanks
Java to extract info to HTML
Java to extract info to HTML I need to write a java program that will extract information (events) from .ics files, such as those used in iCalendar, into HTML format. I started by creating string instance variables for each
date_sun_info
date_sun_info() Function of PHP
date_sun_info function returns... on success or False on failure.
Description on PHP date_sun_info() Function
array date_sun_info ( int $time , float $latitude , float $longitude
Java to extract info from .iCalendar files
Java to extract info from .iCalendar files I need to write a java program that will extract information (events) from .ics files, such as those used in iCalendar, into HTML format. I started by creating string instance variables
java - JSP-Servlet
;Hi friend,
display data from the table using jsp
Data from the table 'stu_info' of database 'student...://
Thanks
how to get harddisk info using S.M.A.R.T using java
how to get harddisk info using S.M.A.R.T using java how to get harddisk info using S.M.A.R.T using java
sql/xml query in jsp - JSP-Servlet
Testing JSP
select id
from "SYSTEM..."
name:PROFILE
columns:id (bigint) and INFO (xml)
data stored:id=1 and info=nitin... with example.
Thanks
JSP page directive tag atributes
JSP page directive tag atributes The list of the page directive tag attributes in the JSP.
Hi,
The list of the JSP page directive tag attributes is:
language
extends
import
session
info
errorPage
Answer me ASAP, Thanks, very important
Answer me ASAP, Thanks, very important Sir, how to fix this problem in mysql
i have an error of "Too many connections" message from Mysql server,, ASAP please...Thanks in Advance
JSP
; Hi Friend,
Please visit the following links:
Thanks
java - JSP-Servlet
INFO: Installing web application at context path /jsp-examples from URL file:C... org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote... load
INFO: Initialization processed in 1063 ms
Sep 15, 2008 8:00:03 PMdbc-jsp
jdbc-jsp <html>
<head>
<title>your info mail<...;<font color=#1f2e3c>your info mail</font></u></center>... the following code:
1)form.jsp:
<html>
<head>
<title>your info
jsp or sevlet and html form to send picture to database - JSP-Servlet
that will browse for the picture, jsp or servlet that the info from html will go...jsp or sevlet and html form to send picture to database Hello guys, thanks for your help. Please help me.. I want to insert student information
jsp
jsp p>in my project i have following jsp in this jsp the pagesize...-info-of-fileRef-table" requestURI="">
<tr>
<td... = fileRefDO.getFileRefTitle();
%>
<tr class="doc-info>
Thanks
Doubt regarding charts and jsp
");
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
} catch (Exception e...");
Thanks in advance calculate mark..using radio button?????? Hello,
Please specify some more details.
Thanks
;" import = "java.io.*" errorPage = "" %>
<jsp:useBean id = "formHandler... = "java.io.*" errorPage = "" %>
<jsp:useBean id = "formHandler" class...;
<td align="left" valign="middle"><jsp:getProperty
JSP
in listview or in gridview within JSP?
Hi Friend,
Try...;Pagination of JSP page</h3>
<body>
<form>
<input type="hidden...,marks,grade).
Thanks
continue..
<%
int i=0;
int cPage=0 Comminication - JSP-Servlet
.
Thanks...Jsp-Jsp Comminication Can we make jsp to jsp communication Hi friend,
Name Saved
Next Page to view the session value
web-design - JSP-Servlet
" +
"\n" +
" Info TypeValue\n... and JSP Examples.
Servlet and JSP Examples
getsession
javacode.GetSession
getsession
/jsp/GetSession
logout problem.. - JSP-Servlet
logout problem.. hi...
first of all thanks for ur... done in the code i have used session object in project's servlet and jsp for trsferring info between various servlet & jsp.and made a logout servlet.which
JSP to Excel - JSP-Servlet
JSP to Excel Need an example of JSP and Excel database connection. Thanks
JBoss and Sevlet - JSP-Servlet
) and I get the message:
15:58:57,130 INFO [TomcatDeployer] deploy, ctxPath=/gg...://
Thanks
<c:forNext/> - JSP-Servlet
information.
Thanks. Dude thanks... help would be greatly appreciated.
Thanks much,
Bill Hi friend... I want to choose a row and send that info to another program then after done
servlet - JSP-Servlet
" +
" Info TypeValue\n" +
"\n" +
" ID\n...(request, response);
}
}
Thanks
servlet - JSP-Servlet
");
PreparedStatement pst = connection.prepareStatement("update emp_info set... the problem with this code explain in details.
Thanks
session tracking - JSP-Servlet
username on top of page( that is how do i transfer info from one page to other...
Thanks
jsp - JSP-Interview Questions
-----------------------------------------
Read for more information.
Thanks...jsp what are the life cycles of jsp and give a brief description Hi friend,
The lifecycle of jsp page
life cycle of jsp
dependent drop down box - JSP-Servlet
;
window.location.replace(""+cid+"&&value="+val);
}
function extract(){
var ide=document.getElementById("info").selectedIndex;
var bookname = document.getElementById("info").options[ide].text cannot log to FileAppender - Log4J
JSP cannot log to FileAppender Hi,
Thank you for your attention... and when called from jsp.
However, when i change the log4j.properties to use... method.
But when the LogClass is called from jsp file, no log file is created - JSP-Servlet
to :
Thanks...JSP how to get the input in a jsp page which was entered by the user in another jsp page??
'request.getParameter' that is used for html to jsp
clarification in jsp - JSP-Servlet
the following link:
Thanks...clarification in jsp Hi
did jsp supports post method to send values to next jsp?
if possible how to use post method in jsp?and what
jsp code - JSP-Servlet
jsp code Can anyone help me in writing jsp/servlet code to retrieve files and display in the browser from a given directory. Hi Friend,
Try the following code:
Thanks
jsp - JSP-Servlet
box in another page in jsp program. I need coding for that.
Hi Friend,
Use in the first jsp page.
Then create another jsp page to retrieve... :
Thanks... problem visit this link....
Thanks
vineet
EL(JSP) - JSP-Servlet
://
Thanks...EL(JSP) Dear Sir,
I want to ask that Whether BEA Application server weblogic 8.1 support to Expression language(JSP) or not. Because EL require jsp
|
http://www.roseindia.net/tutorialhelp/comment/5684
|
CC-MAIN-2015-11
|
refinedweb
| 1,347
| 59.19
|
enum in c# .NET
In this article I will explain about enum, how to create and use enum..
enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Program to demonstrate how to create and Use an Enum:
using System;
namespace example_enum
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
static void Main(string[] args)
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Sunday, DayofWeek.Sunday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Monday, DayofWeek.Monday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Tuesday, DayofWeek.Tuesday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Wednesday, DayofWeek.Wednesday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Thursday, DayofWeek.Thursday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Friday, DayofWeek.Friday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Saturday, DayofWeek.Saturday);
Console.ReadLine();
}
}
Some points about enum:
You give two same values in enum type?
Yes we can have same value in enum type. Example when we want to set priority options like
Normal 0
Excellent 1
Default 0
Good 3
namespace enum_example4
Sunday = 1, Monday, Tuesday = 1, Wednesday, Thursday = 2, Friday, Saturday
{
string[] values = Enum.GetNames(typeof(DayofWeek));
foreach (string s in values)
{
Console.WriteLine(s);
}
Console.WriteLine();
int[] n = (int[])Enum.GetValues(typeof(DayofWeek));
foreach (int x in n)
Console.WriteLine(x);
namespace enum_exampl3
int total = 0;
total++;
Console.WriteLine("Total values in enum type is : {0}", total);
Console.WriteLine();
In the above program you have string and numeric representation of enum values. Enum class contains many useful methods for working with enumerations. The beauty of enum is that your can process it as integer value and display as string.
Hope the article would have helped you in understanding enum and their usage. Your feedback and constructive contributions are welcome. Please feel free to contact me for feedback or comments you may have about this article.
Working as a Software professional.
©2015
C# Corner. All contents are copyright of their authors.
|
http://www.c-sharpcorner.com/uploadfile/puranindia/enums-in-C-Sharp/
|
CC-MAIN-2015-32
|
refinedweb
| 335
| 52.36
|
UPDATE: 2019-06-25
Test your paths
def check_path(out_fc):
"""Check for a filegeodatabase and a filename"""
_punc_ = '!"#$%&\'()*+,-;<=>?@[]^`{|}~ '
flotsam = " ".join([i for i in _punc_]) + " ... plus the `space`"
msg = msg0.format(flotsam)
if np.any([i in out_fc for i in _punc_]):
return (None, msg)
pth = out_fc.split("\\")
if len(pth) == 1:
return (None, msg)
name = pth[-1]
gdb = "\\".join(pth[:-1])
if gdb[-4:] != '.gdb':
return (None, msg)
return gdb, name
What 'flotsam' in the _punc_ list do you use?
Is it a work restriction?
Did you work institute 'dot' user names than have to backtrack and replace them with underscores?
Would love to hear the stories.
-------------------------------------------------------------------------------------------
Warnings
People still continue to be confused about file path naming conventions when using python. Please take the time to read. Python 3.x is used in ArcGIS Pro so you may encounter a new problem...
pth = "C:\Users\dan_p\AppData\Local\ESRI\ArcGISPro"
File "<ipython-input-66-5b37dd76b72d>", line 1
pth = "C:\Users\dan_p\AppData\Local\ESRI\ArcGISPro"
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
# ---- the fix is still raw encoding
pth = r"C:\Users\dan_p\AppData\Local\ESRI\ArcGISPro"
pth
'C:\\Users\\dan_p\\AppData\\Local\\ESRI\\ArcGISPro'
-------------------------------------------------------------------------------------------
READINGS: String and bytes literals
Still not allowed
pth = r"C:\Users\dan_p\AppData\Local\ESRI\ArcGISPro\" # ---- note the \ at the end
File "<ipython-input-86-70ede0dfa3fe>", line 1
pth = r"C:\Users\dan_p\AppData\Local\ESRI\ArcGISPro\"
^
SyntaxError: EOL while scanning string literal # ---- which means you 'escaped' the "
-------------------------------------------------------------------------------------------
HISTORY: take the poll first before you read on How do you write Python path strings?
I am sure everyone is sick of hearing ... check your filenames and paths and make sure there is no X or Y. Well, this is going to be a work in progress which demonstrates where things go wrong while maintaining the identity of the guilty.
Great examples there, thanks for sharing. What are your thoughts on using os.path for this stuff?
|
https://community.esri.com/blogs/dan_patterson/2016/08/14/filenames-and-file-paths-in-python
|
CC-MAIN-2019-39
|
refinedweb
| 333
| 66.84
|
C#.
Steps
Part One of Three:
Seting Up (Windows)
Part Two of Three:
Creating Your First Program
- 1Run Visual C# CommunityMake sure it looks like this:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.ReadLine(); } } }
- 7Click the Run [►] button on the toolbar. This will build the program and run the program. Congratulations!
- 8View the result. This should have produced a console window, reading Hello World!
Advertisement
- If it did not, then you did something incorrectly.
Part Three of Three:
Setting Up (Free Software)
- 1Download CVS and GNU build tools. This should be included into the majority of Linux distributions.
- 2Go to the DotGNU project () that provides FOSS implementation of C#. Read the chapter about the installation. These instructions are simple to follow even for beginners.
- 3Decide if you want to get the source code and build you C# environment from scratch or you may try pre-compiled distributions first. The project is relatively easy to build from the source so we suggest to try this way first.
- 4Try to start some examples that also come in precompiled (.exe) form. For instance, FormsTest.exe will show large collection of various GUI controls. The folder pnetlib/samples contains the script ilrun.sh that can launch precompiled executables, for instance sh ./ilrun.sh forms/FormsTest.exe (from inside that folder).
- 5Use!Advertisement
Community Q&A
Search
-
-
- QuestionI created a Windows Forms C #, but I do not know how I can make this app available to my users. In fact, I really do not know how the program can be run outside of Visual Studio. What do I do?
-
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.Submit
Advertisement
Tips
- If installing Visual C# 2010/2012 express, it will either automatically download or give you the option to do this.
- Visual C# 2005/2008 Express Editions comes with an option to install the Microsoft MSDN 2005 Express Edition. This is a great reference and can be accessed through Help:Contents or by highlighting a keyword and pressing F1. It is strongly recommended that you download and install the MSDN library.
- There are more good C# implementations than the two described here. Mono project may be interesting for you as well.
Advertisement
About This Article
Is this article up to date?
Yes
No
Advertisement
|
https://m.wikihow.com/Create-a-Program-in-C-Sharp
|
CC-MAIN-2019-39
|
refinedweb
| 405
| 59.6
|
On Tue, Dec 02, 2008 at 02:43:38PM -0600, Hollis Blanchard wrote: > On Tue, 2008-12-02 at 14:22 -0600, Anthony Liguori wrote: > > Hollis Blanchard wrote: > > > > > +#include "pci.h" > > > +#include "pci_host.h" > > > +#include "bswap.h" > > > + > > > +#undef DEBUG > > > +#ifdef DEBUG > > > +#define DPRINTF(fmt, args...) do { printf(fmt, ##args); } while (0) > > > +#else > > > +#define DPRINTF(fmt, args...) > > > +#endif /* DEBUG */ > > > > > > > This is a GCC-ism that's deprecated. The proper syntax (C99) is: > > > > #define DPRINTF(fmt, ...) do { printf(fmt, ## __VA_ARGS__); } while (0) > > Will do. > > > > +struct ppc4xx_pci_t { > > > + struct pci_master_map pmm[PPC44x_PCI_NR_PMMS]; > > > + struct pci_target_map ptm[PPC44x_PCI_NR_PTMS]; > > > + > > > + PCIHostState pci_state; > > > +}; > > > +typedef struct ppc4xx_pci_t ppc4xx_pci_t; > > > > > > > It would be better to use QEMU style type naming. > > I copied this style from ppc405_uc.c, but I will ChangeItLikeThis. > > > > +static void pci4xx_cfgaddr_writel(void *opaque, target_phys_addr_t addr, > > > + uint32_t value) > > > +{ > > > + ppc4xx_pci_t *ppc4xx_pci = opaque; > > > + > > > +#ifdef TARGET_WORDS_BIGENDIAN > > > + value = bswap32(value); > > > +#endif > > > > > > > > > > Is this byte swapping correct? > > I hate this byte swapping, because as we've discussed at great length in > the past, "TARGET_WORDS_BIGENDIAN" never should have existed. > > That said, as far as I can tell it is correct for the current state of > qemu. I changed it to this style due to Aurelien's previous request. As > I noted in the patch description, I can only test on > big-endian/big-endian guest/host. > To summarize the discussion we had last time, this is actually needed depending on how the PCI controller is connected to the CPU, it's not dependent on the CPU itself. But we put it here in QEMU, as we currently don't model buses. It reflects all byte swapping that is done between the CPU and the controller, either by the chipset (which can be dependent on the device or address range), by the bus being wired reversed, or whatever. If your controller works with byte-swapping enabled, it means that byte-swapping is necessary for a big-endian guest. It may or may not be necessary for a little endian guest, but I guess we have no way to try. The other solution to find the answer it looking at the docs, get a headache, and maybe no answer. Not sure we want that. So I think this code is ok, at least until we get more details or until a bus model is developed in QEMU. -- .''`. Aurelien Jarno | GPG: 1024D/F1BCDB73 : :' : Debian developer | Electrical Engineer `. `' address@hidden | address@hidden `- people.debian.org/~aurel32 |
|
http://lists.gnu.org/archive/html/qemu-devel/2008-12/msg00078.html
|
CC-MAIN-2014-35
|
refinedweb
| 396
| 65.93
|
Tribal Pong - 0.0.1
A pong clone(it's going to be one)
Silas Gaisser
(smileymensch)
I know... There are so many Pong-Clones... But I wanted to make another one... and I did :D
Changes
Links
Releases
Tribal Pong 0.0.1 — 6 Dec, 2012
Pygame.org account Comments
Mekire 2012-12-07 03:39:34
You appear to have forgotten your levels.py module; as such I can't run your program. Other than that, I strongly recommend you not use multiple * imports in a single module. It collapses everything into one namespace and makes it impossible for someone reading your code to know where things are coming from. Also, global constants are fine, but you should really try to refrain from using global variables (like lives points and level).
-Mek
spacemax 2012-12-21 21:35:38
It look like a breakout clone without any bricks :(
sadly...
|
http://www.pygame.org/project-Tribal+Pong-2739-4401.html
|
CC-MAIN-2018-51
|
refinedweb
| 151
| 77.13
|
Will.”
Edwards said Ovum recommends what he calls “business-grade” cloud collaboration services such as Box and Huddle because of their superior feature management and administration capabilities. Google Drive is seen as a prime competitor to these services as well as other popular file sharing clouds from Citrix, Dropbox, Egnyte, Nomadix, SpiderOak, SugarSync and Syncplicity.
Andres Roldriguez, CEO of cloud NAS vendor Nasuni, said Google Drive can go beyond the file sharing services already on the market because it controls the application stack and a mobile operating system. And while he doesn’t see Google Drive as a competitor to enterprise storage vendors, he does warn that enterprise vendors need to address data on mobile devices in a hurry.
“File storage and synchronization engines are changing storage as we know it,” Rodriguez wrote in an email. “Any large storage vendor that isn’t thinking about how to extend its current data center offerings to mobile is going to be unpleasantly surprised in the next 24 months as more workers shift to accessing data from tablets and smart phones. The pressure on IT is already intense. The control points for much corporate storage today are the Domain Controller (DC) and the CIFS protocol. No one wants to re-architect access control because of mobile users. What we need to figure out is how to extend the access control model we have today to include the new platforms.”
Ranajit Nevatia, VP of marketing for Nasuni rival Panzura, says Google Drive is a long way from becoming an enterprise service because adding features such as global namespace, file locking and enterprise encryption is “damn hard.” He said there is a big difference between file sharing and project sharing, which is what enterprise storage must support.
“Google Drive, Box, Dropbox, iDrive, these are becoming a dime a dozen now,” Nevatia said. “Everybody’s coming up with file sharing with free amounts of storage associated with them. When you look at the target market and use cases they’re going after, it’s not overlapping with what we’re doing. It will put pressure on consumer level file sharing services, but it’s not meant for large enterprises. Our customers collaborate on projects like architectural engineer design or handle large amounts of research data. We’re not talking about two gigabytes or five gigabytes. We’re talking terabytes of data.”
Tom Gelson, Imation’s director of business development and its cloud strategist, said he has mixed reactions about Google’s entry into cloud storage. Imation’s data protection appliances are used by cloud providers and Gelson said the vendor plans on launching its own cloud service. And as an SMB vendor, that would make it a Google competitor. But Gelson agrees with Nevatia about the need for security in the cloud.
“Google rubber stamps cloud backup, because everybody knows Google,” he said. “It’s exciting, but we’re all concerned. Imation is focused on SMBs and if you talk to an SMB IT director, the biggest concern is security. That’s Imation’s biggest focus. We want to make sure data is secure once it sits on the cloud.”
Gelson pointed out Imation acquired three security companies in 2011-– Encryptx, MXI and Iron Key. He said Imation encrypts data in flight to the cloud, and also encrypts data on its RDX removable hard drive media.
Ethan Oberman, CEO of online file sharing company SpiderOak, brings up another potential sore spot for Google – privacy. Oberman wonders if Google will try to integrate Google Drive with Google Plus and if it will record users’ activities.
“Google has definitely been one of the more innovative companies since its inception, so the market will have high expectations for how Google Drive might change the way we work within the cloud,” said Oberman wrote in an e-mail statement. .”
Comment on this Post
|
http://itknowledgeexchange.techtarget.com/storage-soup/will-google-drive-cloud-storage-adoption-or-it-headaches/
|
CC-MAIN-2015-40
|
refinedweb
| 643
| 61.26
|
This post is intended to give you a feel for using 8th, but it is not a tutorial per se. If you're not familiar with "8th", please view my previous blog post.
Resources:
If you don't yet have a copy of 8th, you should get one now and follow the installation instructions in the manual.
I assume you do have a copy of 8th, and have followed the installation instructions as presented in the manual, and know how to start and stop it at least. If that's not true, take care of it now so you can follow along!
The word "word" is used a lot in 8th (and in Forth, in general), to describe what other languages call a "function" or "procedure". Unlike most other languages, 8th lets you use any sequence of UTF-8 characters not containing whitespace to name a word. So "I'm-doing-fine" is a valid word-name, but "I'm doing fine" is not. The reason for this lies with the way 8th parses input, which we'll describe later on.
I'm-doing-fine
I'm doing fine
You can get "inline help" when you're using the 8th console, by typing the word "help" followed by the word you want help on. For example:
ok> help modns: nname: modstack: n m -- rdesc: Divide the numbers "n" by "m", returning the remainder as a number "r"
This gives you all the information you need to use the "n:mod" word properly: that it is in the "n" namespace, what its "stack-effect diagram" (a.k.a. "SED") is, and a concise description of what the word does. If there is more than one word with the name you give (for example, "+") then the help system will display the help for all the words with that name. In that case, you can specify the "fully-qualified name" of the word; for example, "n:mod" instead of "mod".
To list all the words 8th currently knows, type "words". That spews a very long list, though. You might be more interested in just knowing what words are in a particular namespace:
ok> words/ a:a! + - @ bsearch clear close dot each exists? filter indexof insert join len map new op op! open pop push reduce rev shift shuffle slice slide sort when when! y zip
The word "words/" returns the words which match the text you type after it. In this example, you typed "a:", which it interprets as "find all the words in the 'a' namespace". You can get a different kind of help by typing "apropos". That will search for the given text across all the different help text, and will return help on anything which mentions that text. It's like "grep" for the inline help system.
We mentioned the "stack-effect diagram", or SED; now we'll explain it. All it is, really, is a more or less standardized way of documenting what effect a word has on the stack. That is to say, what items the word consumes from the stack, and what items it puts on the stack.
To remind you: 8th (and Forths in general) utilize a "stack" as the central means of passing parameters to, and getting results from, the words invoked. So a correct SED is really crucial to understand how to use a word.
The general SED format is:
in3 in2 in1 -- out2 out1
This is understood to mean that on entry, the word expects "in1" on TOS (top of stack), and then "in2" underneath it and "in3" underneath that. It consumes those, then pushes "out2" on the stack and leaves "out1" on TOS.
It takes a bit of getting used to and you must learn to read it properly, because it is a complete documentation of how the stack should be used by that word.
Note that the SED doesn't tell you what the semantics of the word are, or what it's good for. That's what the help system, manual, and sample code are for.
The 8th interpreter is also known as a "REPL". It works like this, if you type "10 5 / . cr":
ok> 10 5 / . cr2
The REPL parses whitespace-delimited strings of text from the input, and attempts to interpret what it finds. In this case, 8th looks up "10" in its dictionary of known words and can't find it. It then tries to interpret "10" as a number. That succeeds, so it "pushes" the number 10 on the stack, and similarly the "5". It then looks up "/" in its dictionary and finds code for it, which it executes - and that does what you expect: it divides 10 by 5. Then 8th looks up "." executes it. Its effect is to print whatever is on TOS. The final "cr" was likewise looked up and executed; its effect is to print a line-termination appropriate for the OS.
That's why you see the "2" on the line under the one you typed. If you hadn't put the ". cr" there, 8th would have kept mum. It's good at that; you have to tell it when you want to see anything.
You may be forgiven for thinking 8th is solely an interpreted language, given the previous examples. In fact, it is both an interpreted and a compiled language: the REPL interprets input from the console, or a file, or some other input stream, and when a word is found in the dictionary it's executed. But by using the ":" and ";" words, you can create new named words:
ok> : div5 5 / ;ok> 10 div5 . cr2
The "compiler" word ":" tells the REPL to enter compilation mode, so instead of immediately executing the words it parses, it compiles what it finds into the word being created. By the way: if you want an "anonymous" word, you use "(" and ")" instead of ":" and ";".
A "named word" is one which has a name, and can be found in the dictionary using the word "w:find" (among others). An "anonymous word" is invisible to the dictionary, and is widely used in iterators. For example:
ok> [1,2,3] ( . cr drop ) a:each123
Note that in the 'div5' example you could also have created a new word '10' which did something other than push the number 10:
ok> : 10 "ten" ;ok> 10 div5 Exception: Expected Number but got String: at offset 8 in console: G:>n
8th threw an exception here, because the "/" word in "div5" expected to be given two numbers, but instead you gave it "ten" and 5, and 8th considers that a fatal error and throws an exception.
Let's see what '10' does now:
ok> 10 .s1 s: 00000000038d6580 3 ten
The ".s" word displays the top ten items on the stack. Here it's showing that after invoking "10", a string "ten" is on the stack. That's because we created the word "10", and the stack-effect is what we would expect. It's just a really bad idea to create a word like this - but 8th doesn't prevent you from doing it anyway!
This brings us to the final topic we'll discuss today: "exceptions".
Unlike most other languages with exceptions (C++, Java etc), 8th throws exceptions when something really bad happens, something which really can't be handled. Thus, exceptions are considered "fatal errors" and generally cause your 8th program to terminate. You can, however, override that behavior by intercepting "handler". From the "debug/nicer" library:
( "\nException: '%s'\nBacktrace:\n" s:strfmt . backtrace cr bye ) w:is handler
This also terminates the application, but it prints a backtrace for debugging purposes. This utilizes a feature of 8th (and Forths) called "deferred words". Those are words whose name is fixed at declaration time, but whose code can be modified at a later time. That's what the "w:is" does: it assigns the code in the anonymous word to the "handler" deferred word.
Remember: in 8th, exceptions are fatal and almost always indicate a programming error which you need to correct!
This post gave you a peek at some of the internal workings of 8th, and a feel for some of what it can do. The next post will talk about solving real problems, with a particular emphasis on embedded Linux on Raspberry Pi platforms.
|
https://community.arm.com/iot/embedded/b/embedded-blog/posts/8th-grokking-the-repl
|
CC-MAIN-2017-43
|
refinedweb
| 1,389
| 70.84
|
Get Column Names of pandas DataFrame as List in Python (2 Examples)
In this tutorial you’ll learn how to create a list of column names in Python programming.
Table of contents:
You’re here for the answer, so let’s get straight to the exemplifying Python syntax.
Creation of Example Data
Let’s first create some example data. For this, we have to load the pandas library to Python:
import pandas as pd # Load pandas
As the next step, we can create a pandas DataFrame as shown below:
data = pd.DataFrame({"x1":["xxx", "yyy", "abc", "xxx"], # Create example data "x2":range(1, 5), "x3":["a", "d", "a", "b"], "x4":[10, 30, 50, 70]}) print(data) # Print example data # x1 x2 x3 x4 # 0 xxx 1 a 10 # 1 yyy 2 d 30 # 2 abc 3 a 50 # 3 xxx 4 b 70
Have a look at the previous output of the console. As you can see, we have created a pandas DataFrame with four rows and four columns.
In the following examples, I’ll explain how to extract the header names of our DataFrame columns and how to store these names in a list.
Let’s do this!
Example 1: Create List of Column Names Using list() Function
In this example, I’ll illustrate how to apply the list() function to create a Python list containing all variables names of a pandas DataFrame.
Have a look at the following Python syntax and its output:
my_column_names_1 = list(data) # Apply list function print(my_column_names_1) # ['x1', 'x2', 'x3', 'x4']
As you can see, we have created a list object called my_column_names_1 that consists of the character strings x1, x2, x3, and x4 (i.e. the column names of our DataFrame).
Example 2: Create List of Column Names Using columns Attribute & tolist() Function
The Python syntax below illustrates an alternative to the list() function that I have explained in the previous example.
In this example, we’ll use the columns attribute and the tolist() function to get a list of all column names of a pandas DataFrame:
my_column_names_2 = data.columns.tolist() # Apply tolist function print(my_column_names_2) # ['x1', 'x2', 'x3', 'x4']
The previous output shows exactly the same values as in the first example. However, this time we have used a different Python syntax to construct our list of variable names.
Video & Further Resources
In case you need further information on the Python syntax of this article, I recommend watching the following video on the YouTube channel of Erik Marsja. In the video, he explains six different ways on how to get a list of column names in Python:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may read the related tutorials on my website:
To summarize: In this Python article you have learned how to get all variable names of a pandas DataFrame. Let me know in the comments section, in case you have any further comments or questions.
|
https://statisticsglobe.com/get-column-names-of-pandas-dataframe-as-list-python
|
CC-MAIN-2021-31
|
refinedweb
| 521
| 64.24
|
In this article, we will learn how to install Django and Django REST framework in an isolated environment. We will also look at the Django folders, files, and configurations, and how to create an app with Django. We will also introduce various command-line and GUI tools that are use to interact with the RESTful Web Services.
Installing Django and Django REST frameworks in an isolated environment
First, run the following command to install the Django web framework:
pip install django==1.11.5
The last lines of the output will indicate that the django package has been successfully installed. The process will also install the pytz package that provides world time zone definitions. Take into account that you may also see a notice to upgrade pip. The next lines show a sample of the four last lines of the output generated by a successful pip installation:
Collecting django Collecting pytz (from django) Installing collected packages: pytz, django Successfully installed django-1.11.5 pytz-2017.2
Now that we have installed the Django web framework, we can install Django REST framework. Django REST framework works on top of Django and provides us with a powerful and flexible toolkit to build RESTful Web Services. We just need to run the following command to install this package:
pip install djangorestframework==3.6.4
The last lines for the output will indicate that the djangorestframework package has been successfully installed, as shown here:
Collecting djangorestframework Installing collected packages: djangorestframework Successfully installed djangorestframework-3.6.4
After following the previous steps, we will have Django REST framework 3.6.4 and Django 1.11.5 installed in our virtual environment.
Creating an app with Django
Now, we will create our first app with Django and we will analyze the directory structure that Django creates. First, go to the root folder for the virtual environment: 01.
In Linux or macOS, enter the following command:
cd ~/HillarDjangoREST/01
If you prefer Command Prompt, run the following command in the Windows command line:
cd /d %USERPROFILE%\HillarDjangoREST\01
If you prefer Windows PowerShell, run the following command in Windows PowerShell:
cd /d $env:USERPROFILE\HillarDjangoREST\01
In Linux or macOS, run the following command to create a new Django project named restful01. The command won’t produce any output:
python bin/django-admin.py startproject restful01
In Windows, in either Command Prompt or PowerShell, run the following command to create a new Django project named restful01. The command won’t produce any output:
python Scripts\django-admin.py startproject restful01
The previous command creates a restful01 folder with other subfolders and Python files. Now, go to the recently created restful01 folder. Just execute the following command on any platform:
cd restful01
Then, run the following command to create a new Django app named toys within the restful01 Django project. The command won’t produce any output:
python manage.py startapp toys
The previous command creates a new restful01/toys subfolder, with the following files:
- views.py
- tests.py
- models.py
- apps.py
- admin.py
- init .py
In addition, the restful01/toys folder will have a migrations subfolder with an init .py Python script. The following diagram shows the folders and files in the directory tree, starting at the restful01 folder with two subfolders – toys and restful01:
Understanding Django folders, files, and configurations
After we create our first Django project and then a Django app, there are many new folders and files. First, use your favorite editor or IDE to check the Python code in the apps.py file within the restful01/toys folder (restful01\toys in Windows). The following lines show the code for this file:
from django.apps import AppConfig class ToysConfig(AppConfig): name = 'toys'
The code declares the ToysConfig class as a subclass of the django.apps.AppConfig class that represents a Django application and its configuration. The ToysConfig class just defines the name class attribute and sets its value to ‘toys’.
Now, we have to add toys.apps.ToysConfig as one of the installed apps in the restful01/settings.py file that configures settings for the restful01 Django project. I built the previous string by concatenating many values as follows: app name + .apps. + class name, which is, toys + .apps. + ToysConfig. In addition, we have to add the rest_framework app to make it possible for us to use Django REST framework.
The restful01/settings.py file is a Python module with module-level variables that define the configuration of Django for the restful01 project. We will make some changes to this Django settings file. Open the restful01/settings.py file and locate the highlighted lines that specify the strings list that declares the installed apps. The following code shows the first lines for the settings.py file. Note that the file has more code:
""" Django settings for restful01 project. Generated by 'django-admin startproject' using Django 1.11 = '+uyg(tmn%eo+fpg+fcwmm&x(2x0gml8)[email protected]$nijab%)y$a*x', ]
Add the following two strings to the INSTALLED_APPS strings list and save the changes to the restful01/settings.py file:
'rest_framework' 'toys.apps.ToysConfig'
The following lines show the new code that declares the INSTALLED_APPS string list with the added lines highlighted and with comments to understand what each added string means. The code file for the sample is included in the hillar_django_restful_01 folder:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Django REST framework 'rest_framework', # Toys application 'toys.apps.ToysConfig', ]
This way, we have added Django REST framework and the toys application to our initial Django project named restful01.
Installing tools
Now, we will leave Django for a while and we will install many tools that we will use to interact with the RESTful Web Services that we will develop throughout this book.
We will use the following different kinds of tools to compose and send HTTP requests and visualize the responses throughout our book:
- Command-line tools
- GUI tools
- Python code
- Web browser
- JavaScript code
You can use any other application that allows you to compose and send HTTP requests. There are many apps that run on tablets and smartphones that allow you to accomplish this task. However, we will focus our attention on the most useful tools when building RESTful Web Services with Django.
Installing Curl
We will start installing command-line tools. One of the key advantages of command-line tools is that you can easily run again the HTTP requests again after we have built them for the first time, and we don’t need to use the mouse or tap the screen to run requests. We can also easily build a script with batch requests and run them.
As happens with any command-line tool, it can take more time to perform the first requests compared with GUI tools, but it becomes easier once we have performed many requests and we can easily reuse the commands we have written in the past to compose new requests.
Curl, also known as cURL, is a very popular open source command-line tool and library that allows us to easily transfer data. We can use the curl command-line tool to easily compose and send HTTP requests and check their responses.
In Linux or macOS, you can open a Terminal and start using curl from the command line. In Windows, you have two options. You can work with curl in Command Prompt or you can decide to install curl as part of the Cygwin package installation option and execute it
from the Cygwin terminal. You can read more about the Cygwin terminal and its installation procedure at:. Windows Powershell includes a curl alias that calls the Invoke-WebRequest command, and therefore, if you want to work with Windows Powershell with curl, it is necessary to remove the curl alias.
If you want to use the curl command within Command Prompt, you just need to download and unzip the latest version of the curl download page:. Make sure you download the version that includes SSL and SSH.
The following screenshot shows the available downloads for Windows. The Win64 – Generic section includes the versions that we can run in Command Prompt or Windows Powershell.
After you unzip the .7zip or .zip file you have downloaded, you can include the folder in which curl.exe is included in your path. For example, if you unzip the Win64 x86_64.7zip file, you will find curl.exe in the bin folder. The following screenshot shows the results of executing curl –version on Command Prompt in Windows 10.
The –version option makes curl display its version and all the libraries, protocols, and features it supports:
Installing HTTPie
Now, we will install HTTPie, a command-line HTTP client written in Python that makes it easy to send HTTP requests and uses a syntax that is easier than curl. By default, HTTPie displays colorized output and uses multiple lines to display the response details. In some cases, HTTPie makes it easier to understand the responses than the curl utility. However, one of the great disadvantages of HTTPie as a command-line utility is that it takes more time to load than curl, and therefore, if you want to code scripts with too many commands, you have to evaluate whether it makes sense to use HTTPie.
We just need to make sure we run the following command in the virtual environment we have just created and activated. This way, we will install HTTPie only for our virtual environment.
Run the following command in the terminal, Command Prompt, or Windows PowerShell to install the httpie package:
pip install --upgrade httpie
The last lines of the output will indicate that the httpie package has been successfully installed:
Collecting httpie Collecting colorama>=0.2.4 (from httpie) Collecting requests>=2.11.0 (from httpie) Collecting Pygments>=2.1.3 (from httpie) Collecting idna=2.5 (from requests>=2.11.0->httpie) Collecting urllib3=1.21.1 (from requests>=2.11.0->httpie) Collecting chardet=3.0.2 (from requests>=2.11.0->httpie) Collecting certifi>=2017.4.17 (from requests>=2.11.0->httpie) Installing collected packages: colorama, idna, urllib3, chardet, certifi, requests, Pygments, httpie Successfully installed Pygments-2.2.0 certifi-2017.7.27.1 chardet-3.0.4 colorama-0.3.9 httpie-0.9.9 idna-2.6 requests-2.18.4 urllib3-1.22
Now, we will be able to use the http command to easily compose and send HTTP requests to our future RESTful Web Services build with Django. The following screenshot shows the results of executing http on Command Prompt in Windows 10. HTTPie displays the valid options and indicates that a URL is required:
Installing the Postman REST client
So far, we have installed two terminal-based or command-line tools to compose and send HTTP requests to our Django development server: cURL and HTTPie. Now, we will start installing Graphical User Interface (GUI) tools.
Postman is a very popular API testing suite GUI tool that allows us to easily compose and send HTTP requests, among other features. Postman is available as a standalone app in Linux, macOS, and Windows. You can download the versions of the Postman app from the following URL:.
The following screenshot shows the HTTP GET request builder in Postman:
Installing Stoplight
Stoplight is a very useful GUI tool that focuses on helping architects and developers to model complex APIs. If we need to consume our RESTful Web Service in many different programming languages, we will find Stoplight extremely helpful. Stoplight provides an HTTP request maker that allows us to compose and send requests and generate the necessary code to make them in different programming languages, such as JavaScript, Swift, C#, PHP, Node, and Go, among others.
Stoplight provides a web version and is also available as a standalone app in Linux, macOS, and Windows. You can download the versions of Stoplight from the following URL:.
The following screenshot shows the HTTP GET request builder in Stoplight with the code generation at the bottom:
Installing iCurlHTTP
We can also use apps that can compose and send HTTP requests from mobile devices to work with our RESTful Web Services. For example, we can work with the iCurlHTTP app on iOS devices such as iPad and iPhone:. On Android devices, we can work with the HTTP Request app:.
The following screenshot shows the UI for the iCurlHTTP app running on an iPad Pro:
At the time of writing, the mobile apps that allow you to compose and send HTTP requests do not provide all the features you can find in Postman or command-line utilities.
We learnt to set up a virtual environment with Django and Django REST framework and created an app with Django. We looked at Django folders, files, and configurations and installed command-line and GUI tools to interact with the RESTful Web Services.
This article is an excerpt from the book, Django RESTful Web Services, written by Gaston C. Hillar. This book serves as an easy guide to build Python RESTful APIs and web services with Django. The code bundle for the article is hosted on GitHub.
|
https://hub.packtpub.com/django-and-django-rest-frameworks-build-restful-app/
|
CC-MAIN-2019-26
|
refinedweb
| 2,199
| 62.58
|
beginner.
import arrow.* import arrow.core.* val throwsSomeStuff: (Int) -> Double = {x -> x.toDouble()} val throwsOtherThings: (Double) -> String = {x -> x.toString()} val moreThrowing: (String) -> List<String> = {x -> listOf(x)} val magic = throwsSomeStuff.andThen(throwsOtherThings).andThen(moreThrowing) magic // (A) -> C
Assume we happily throw exceptions in our code. Looking at the types of the above functions, any of them could throw any number of exceptions – we do not know. When we compose, exceptions from any of the constituent
functions can be thrown. Moreover, they may throw the same kind of exception
(e.g.
IllegalArgumentException) and thus it gets tricky tracking exactly where an exception came from.
How then do we communicate an error? By making it explicit in the data type we return.
In general,
Validated is used to accumulate errors, while
Either is used to short-circuit a computation
upon the first error. For more information, see the
Validated vs
Either section of the
Validated documentation.
By convention the right hand side of an
Either is used to hold successful values.
val right: Either<String, Int> = Either.Right(5) right // Right(b=5)
val left: Either<String, Int> = Either.Left("Something went wrong") left // Left(a=Something went wrong)
Because
Either is right-biased, it is possible to define a Monad instance for it.
Since we only ever want the computation to continue in the case of
Right (as captured by the right-bias nature),
we fix the left type parameter and leave the right one free.
So the map and flatMap methods are right-biased:
val right: Either<String, Int> = Either.Right(5) right.flatMap{Either.Right(it + 1)} // Right(b=6)
val left: Either<String, Int> = Either.Left("Something went wrong") left.flatMap{Either.Right(it + 1)} // Left(a=Something went wrong)
As a running example, we will have a series of functions that will:
Using exception-throwing code, we could write something like this:
// Exception Style fun parse(s: String): Int = if (s.matches(Regex("-?[0-9]+"))) s.toInt() else throw NumberFormatException("$s is not a valid integer.") fun reciprocal(i: Int): Double = if (i == 0) throw IllegalArgumentException("Cannot take reciprocal of 0.") else 1.0 / i fun stringify(d: Double): String = d.toString()
Instead, let’s make the fact that some of our functions can fail explicit in the return type.
// Either Style fun parse(s: String): Either<NumberFormatException, Int> = if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt()) else Either.Left(NumberFormatException("$s is not a valid integer.")) fun reciprocal(i: Int): Either<IllegalArgumentException, Double> = if (i == 0) Either.Left(IllegalArgumentException("Cannot take reciprocal of 0.")) else Either.Right(1.0 / i) fun stringify(d: Double): String = d.toString() fun magic(s: String): Either<Exception, String> = parse(s).flatMap{reciprocal(it)}.map{stringify(it)}
These calls to
parse returns a
Left and
Right value
parse("Not a number") // Left(a=java.lang.NumberFormatException: Not a number is not a valid integer.)
parse("2") // Right(b=2)
Now, using combinators like
flatMap and
map, we can compose our functions together.
magic("0") // Left(a=java.lang.IllegalArgumentException: Cannot take reciprocal of 0.)
magic("1") // Right(b=1.0)
magic("Not a number") // Left(a=java.lang.NumberFormatException: Not a number is not a valid integer.)
In the following exercise we pattern-match on every case the
Either returned by
magic can be in.
Note the
when clause in the
Left - the compiler will complain if we leave that out because it knows that
given the type
Either[Exception, String], there can be inhabitants of
Left that are not
NumberFormatException or
IllegalArgumentException. You should also notice that we are using
SmartCast for accessing to
Left and
Right
value.
val x = magic("2") val value = when(x) { is Either.Left -> when (x.a){ is NumberFormatException -> "Not a number!" is IllegalArgumentException -> "Can't take reciprocal of 0!" else -> "Unknown error" } is Either.Right -> "Got reciprocal: ${x.b}" } value // Got reciprocal: 0.5
Instead of using exceptions as our error value, let’s instead enumerate explicitly the things that can go wrong in our program.
// Either with ADT Style sealed class Error { object NotANumber : Error() object NoZeroReciprocal : Error() } fun parse(s: String): Either<Error, Int> = if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt()) else Either.Left(Error.NotANumber) fun reciprocal(i: Int): Either<Error, Double> = if (i == 0) Either.Left(Error.NoZeroReciprocal) else Either.Right(1.0 / i) fun stringify(d: Double): String = d.toString() fun magic(s: String): Either<Error, String> = parse(s).flatMap{reciprocal(it)}.map{stringify(it)}
For our little module, we enumerate any and all errors that can occur. Then, instead of using
exception classes as error values, we use one of the enumerated cases. Now when we pattern match,
we are able to comphrensively handle failure without resulting to an
else branch; moreover
since Error is sealed, no outside code can add additional subtypes which we might fail to handle.
val x = magic("2") when(x) { is Either.Left -> when (x.a){ is Error.NotANumber -> "Not a number!" is Error.NoZeroReciprocal -> "Can't take reciprocal of 0!" } is Either.Right -> "Got reciprocal: ${x.b}" }
Either can also map over the
left value with
mapLeft which is similar to map but applies on left instances.
val r : Either<Int, Int> = Either.Right(7) r.mapLeft {it + 1} val l: Either<Int, Int> = Either.Left(7) l.mapLeft {it + 1} // Left(a=8)
Either<A, B> can be transformed to
Either<B,A> using the
swap() method.
val r: Either<String, Int> = Either.Right(7) r.swap() // Left(a=7)
For using Either’s syntax on arbitrary data types.
This will make possible to use the
left(),
right(),
contains(),
getOrElse() and
getOrHandle() methods:
7.right() // Right(b=7)
"hello".left() // Left(a=hello)
val x = 7.right() x.contains(7) // true
val x = "hello".left() x.getOrElse { 7 } // 7
val x = "hello".left() x.getOrHandle { "$it world!" } // hello world!
For creating Either instance based on a predicate, use
Either.cond() method :
Either.cond(true, { 42 }, { "Error" }) // Right(b=42)
Either.cond(false, { 42 }, { "Error" }) // Left(a=Error)
Another operation is
fold. This operation will extract the value from the Either, or provide a default if the value is
Left
val x : Either<Int, Int> = 7.right() x.fold({ 1 }, { it + 3 }) // 10
val y : Either<Int, Int> = 7.left() y.fold({ 1 }, { it + 3 }) // 1
The
getOrHandle() operation allows the transformation of an
Either.Left value to a
Either.Right using
the value of
Left. This can be useful when a mapping to a single result type is required like
fold() but without
the need to handle
Either.Right case.
As an example we want to map an
Either<Throwable, Int> to a proper HTTP status code:
val r: Either<Throwable, Int> = Either.Left(NumberFormatException()) val httpStatusCode = r.getOrHandle { when(it) { is NumberFormatException -> 400 else -> 500 } } // 400
The
leftIfNull operation transforms a null
Either.Right value to the specified
Either.Left value.
If the value is non-null, the value wrapped into a non-nullable
Either.Right is returned (very useful to
skip null-check further down the call chain).
If the operation is called on an
Either.Left, the same
Either.Left is returned.
See the examples below:
Right(12).leftIfNull({ -1 }) // Right(b=12)
Right(null).leftIfNull({ -1 }) // Left(a=-1)
Left(12).leftIfNull({ -1 }) // Left(a=12)
Another useful operation when working with null is
rightIfNotNull.
If the value is null it will be transformed to the specified
Either.Left and if its not null the type will
be wrapped to
Either.Right.
Example:
"value".rightIfNotNull { "left" } // Right(b=value)
null.rightIfNotNull { "left" } // Left(a=left)
Arrow contains
Either instances for many useful typeclasses that allows you to use and transform right values.
Both Option and Try don’t require a type parameter with the following functions, but it is specifically used for Either.Left
Transforming the inner contents
import arrow.instances.either.functor.* Right(1).map {it + 1} // Right(b=2)
Computing over independent values
import arrow.instances.either.applicative.* tupled(Either.Right(1), Either.Right("a"), Either.Right(2.0)) // Right(b=Tuple3(a=1, b=a, c=2.0))
Computing over dependent values ignoring absence
import arrow.instances.either.monad.* binding { val a = Either.Right(1).bind() val b = Either.Right(1 + a).bind() val c = Either.Right(1 + b).bind() a + b + c } // Right(6)
|
https://arrow-kt.io/docs/arrow/core/either/
|
CC-MAIN-2018-51
|
refinedweb
| 1,397
| 52.97
|
ARCreateAlertEvent
Note
You can continue to use C APIs to customize your application, but C APIs are not enhanced to support new capabilities provided by Java APIs and REST APIs.
Description
Enters an alert event on the specified server. The BMC Remedy AR System server sends an alert to the specified, registered users.
Privileges
All users.
Synopsis
#include "ar.h" #include "arerrno.h" #include "arextern.h" #include "arstruct.h" int ARCreateAlertEvent( ARControlStruct *control, ARAccessNameType user, char *alertText, int priority, ARNameType sourceTag, ARServerNameType serverName, ARNameType formName, char *objectId,.
user
The user who receives the alert. Specify * (
AR_REGISTERED_BROADCAST) to create an alert event for all users that are currently registered to receive alerts with the BMC Remedy AR System server. You cannot specify a group name for this argument.
alertText
The text that the alert contains.
priority
A relative value that represents the priority for this alert. The range of acceptable values is between 0 and 10.
sourceTag
A string that identifies the source of the alert. The BMC Remedy AR System provides two predefined values for this string:
AR— alert originated from the BMC Remedy AR System
FB— alert originated from Flashboards
serverName
The name of the server that is the source of the alert. Use
@ to specify the current server. Specify
NULL for this parameter if the parameter is not applicable to the type of alert that this call creates.
formName
The name of the form that is the source of the alert. For Flashboards, this is the name of the Flashboard that generated the alert. Specify
NULL for this parameter if the parameter is not applicable to the type of alert that this call creates.
objectId
The identifier for the object. For BMC Remedy AR System, this value is the entry ID of the originating request. For Flashboards, this value is the name of the Flashboard alert that the user provides. Specify
NULL for this parameter if the parameter is not applicable to the type of alert that this call creates. Join forms have multiple entry Ids (000000000000001|000000000000002) separated by vertical bars.
Return values
entryId
The unique identifier for the new alert (system-generated).
status
A list of zero or more notes, warnings, or errors generated from a call to this function. For a description of all possible values, see Error checking.
See also
ARRegisterForAlerts, ARDeregisterForAlerts. See FreeAR for: FreeARStatusList.
|
https://docs.bmc.com/docs/ars91/en/arcreatealertevent-609071630.html
|
CC-MAIN-2019-47
|
refinedweb
| 392
| 59.19
|
table of contents
NAME¶
signbit - test sign of a real floating-point number
SYNOPSIS¶
#include <math.h>
int signbit(x);
Link with -lm.
signbit():
DESCRIPTION¶
signbit() is a generic macro which can work on all real.
NaNs and infinities have a sign bit.
RETURN VALUE¶
The signbit() macro returns nonzero if the sign of x is negative; otherwise it returns zero.
ERRORS¶
No errors occur.
ATTRIBUTES¶
For an explanation of the terms used in this section, see attributes(7).
CONFORMING TO¶
POSIX.1-2001, POSIX.1-2008, C99. This function is defined in IEC 559 (and the appendix with recommended functions in IEEE 754/IEEE 854).
SEE ALSO¶
COLOPHON¶
This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at
|
https://dyn.manpages.debian.org/bullseye/manpages-dev/signbit.3.en.html
|
CC-MAIN-2022-21
|
refinedweb
| 143
| 68.77
|
Introduction
Here I will explain how to use richtextbox and how we can save our richtextbox data in database and how we can retrieve and display saved richtextbox data into our application using asp.net.
Description:
Today I am writing this post to explain about freely available richtextbox. Previously I worked on one social networking site for that we got requirement to use richtextbox at that time we search so many websites to use richtextbox but we didn’t find useful ones. Recently I came across one website and I found one free available richtextbox. We can validate and we can use richtextbox very easily and by using this richtextbox we can insert data in different formats like bold, italic and different color format texts and we can insert images also. To use free Richtextbox download available dll here FreeTextbox . After download dll from that site create one new website in visual studio and add FreeTextbox dll reference to newly created website after that design aspx page like this
After that Design your aspx page like this
After that run your application richtextbox appears like this
Now our richtextbox is ready do you know how we can save richtextbox data into database and which datatype is used to save richtextbox data and do you know how to display richtextbox on our web page no problem we can implement it now.
To save richtextbox data we need to use datatype nvarchar(MAX) now Design table like this in your SQL Server database and give name as RichTextBoxData
After that add following namespaces in code behind
Now write the following code in code behind
Demo
Download sample code attached
56 comments :
Hi Suresh
i have problem wit tis cod at saving data with style in tbl
the Error is:-
A potentially dangerous Request.Form value was detected from the client (FreeTextBox1="sdsd").
TNX
You might want to add Server.HtmlEncode(freetextbox.Text) when saving to the database and Server.HtmlDecode() when retrieving. Otherwise a serious security problem exists.
Subhash, you have to set ValidateRequest="false" on the @Page line, that opens the door to security problems but you should be ok if you use HtmlEncode/Decode.
Thank u very much sir ..Ur Great..It helped me a lot..
A potentially dangerous Request.Form value was detected from the client (FreeTextBox1="sdsd").
this error is coming after giving ValidateRequest="false" in iis.
Could you please help in this
thanks so lot dear. Its really so good and excellent. thanks again.
Raja chaturvedi
please add with me at facebook
krishna chaturvedi gonda up
or
send
invitation at-krishnachaturvedimca@gmail.com
@subhash
check the below post to solve your problem
Hi Suresh,
Thank you very much for this article. It is simply good.
ADODB.Recordset rs = new ADODB.Recordset();
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from table1",con);
rs.Open("select RichTextData from table1",con,ADODB.CursorTypeEnum.adOpenKeyset,ADODB.LockTypeEnum.adLockPessimistic,1);
When run that above the error becomes
Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
plz give solution for it......
After enter the data that will store it in database.then how to edit the typed content?
in your above exercise can you explain with vb coding instead of C#...
required validations not working either through jquery or through fieldvalidators.
Folks will you pls help me I'm doing windowsform in that we are using saving data of richtextbox field in ".Rtf" format and i'm adding dataset required field to ".Rdlc" and showing it in reportViewer but Rtf format data is not working it showing same as it saving..??
but i tried to do it in html I do modified one record in html when i'm showing its working but how to save data in Html for RTB field?? do you have any idea's...
Thanks
Pruthvi
Hi, i'm having problems with the formatting of the control on my site? Looks like it inherits from the site master css? Is there a way of setting it to ignore the css or defaulting to what it should look like? Thanks Rich
Different font colors in Text box
Hi all . I have a requirement to add details of a paragraph with its header. The color of the header is different from the paragraph. can any one tell me how to add different colors in a textbox
sir,,this code not working....
how to use fck editor in our web site insert data through fck editor or show data into fck editor
can u tel me how to use it in the wpf,c#
What is the coading og Logout in aasp dot net using c#?
How to create a rich tex in asp dot net using c#?
Hi,
i have problem with integrating...
Error message is:
Error 4 Unable to resolve type 'FreeTextBoxControls.FreeTextBox, FreeTextBox, Version=3.3.1.12354, Culture=neutral, PublicKeyToken=5962a4e684a48b87'
in file license.licx
Could you help me please?
Sorry, problem solved:)
I have the same probles as @kapuc.
Error 1 Unable to resolve type 'FreeTextBoxControls.FreeTextBox, FreeTextBox, Version=3.3.1.12354, Culture=neutral, PublicKeyToken=5962a4e684a48b87'
in file licenses.licx
Need help!
How did you make it?
Hi,
I am using FreeTextBox in my web application which is developed in asp.net 4.0.
I have button under the free textbox.Button is working fine when there is no text in FreeTextBox,but if we enter any text inside FreeTextBox,button is not working.
Whats wrong?
in the case of mvc how is doing
Hi,
i have write ValidateRequest="false" in page directive but still i have problem with this code.
It shows the following error:-
A potentially dangerous Request.Form value was detected from the client (FreeTextBox1="<font face="Georgia"...").
how to disalble right click and Copy,paste options in free text box?
gkhghghghg
gjghjhjh
kjbjhbjhjh
jhjhjhjhhjhjh
456789076543245678
Master Of asp.net
Hi Evertone,
i need to retrive image and data stored in dattabase and display it in textbox not in gridview what to use for it can help me please ?
data is inserted using the freetextbox concept.
Thanks in advance.
How to retrieve freetextbox placed in gridview
ccccccccc
Hello Sir,
How to auto enter data in all fields when we search any particular entry from the list. When we type some characters in search field if its relevant data is available in database then its details should appear in all the available fields.
Help me out sir! thanks in advance!
do send me the code on my id: surajjavarat17@gmail.com
I am using Microsoft Studio Pro V9 SP1 2008 always gives this error:
Server Error in '/WebRichText' email is dladlzn@gmail.com
Source Error:
Line 24: protected void BindGridview()
Line 25: {
Line 26: con.Open();
Line 27: SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
Line 28: SqlDataAdapter da = new SqlDataAdapter(cmd);
Source File: c:\Documents and Settings\xxxxxxx\My Documents\Visual Studio 2008\WebSites\Tutor\RichTextboxSample\RichTextboxSample\Default.aspx.cs Line: 26
nfgfgnfng
i just want how to insert image from local drive to rich text box.......
i just want how to insert image from local drive to rich text box.......
SUTESH BHAI KI JAI..........
dear sir;
I have Problem when I use tag
and use fonts color are error.
A potentially dangerous Request.Form value was detected from the client (MainContent_FreeTextBox2="sf<font color="#FF1493...").
Please tell me too....
Sir, I want a particular record from the database that we already inserted into database....please help me...
thanks.
How to add text editor in windows form by vb.net
sandeep yadav
sandeepyadav.bca@gmail.com
How Can I Implement With Jquery..
plz suggest me other free Editor bcoz this editor is conflict with my other Ajax control.
jhjh
jhjh
kkjk
kkkm
Nice application .. You are genious.
Good example,
Hi suresh can you provide code for Downloading functionality as you provide in your article just like( Download sample code attached)
Really Good Post. Thanks
Hi Suresh,
Thanks for really nice post.
But i have problem here :
I can enter the richtext into the database but how can we display the text as a label in rich text format.
Kindly help me ....
How to add text editor in windows form by vb.net
sandeepyadav.bca@gmail.com
I have a problem:
error is:
A potentially dangerous Request.Form value was detected from the client (adminmaster_ftxtname="<font color="#000080...").
how do i use that downloaded dll ..do i have to install it or where do i place it
please help
Hi,suresh if i am copy text from anywhere and on right click paste it i want on that paste validate that textbox for enter digit only
MVC 3.0 the FreeTextBoxControls showing disabled
I am saving the text as a html file, the text appears properly in html but the image doesn't get diplayed,
i.e because it get saved in temp folder of the system, I want to save it to my path.
Hi Suresh, may i know why we are using the free rich text control when we have it is asp. ajaxcontroltoolkit
|
http://www.aspdotnet-suresh.com/2011/05/richtextbox-sample-in-aspnet-or-how-to.html?showComment=1327054830972
|
CC-MAIN-2013-48
|
refinedweb
| 1,525
| 66.13
|
Asked by:
Get WRONG primary key when i use DbDataAdapter.FillSchema or DbDataReader.GetSchemaTable
Hi All:
I have one table at below:
Table Name=T_APP
Columns:
APP_ID IDENTITY(1,1) NOT NULL,
NAME nvarchar,
LOWERED_APP_NAME nvarchar
The table has one pk :
CONSTRAINT [C_IC_APP_PK] PRIMARY KEY NONCLUSTERED
(
[APP_ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY],
it also has one uk:
CONSTRAINT [C_IC_APP_UK1] UNIQUE CLUSTERED
(
[LOWERED_APP_NAME] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
But when i use DbDataAdapter.FillSchema or DbDataReader.GetSchemaTable, they return LOWERED_APP_NAME as primary key to me NOT APP_ID.
But when i try to make C_IC_APP_UK1 to non-Unique, others still remain, the two methods return me correct column.
Is it a bug? After all, APP_ID is the pk not LOWERED_APP_NAME.
Hope someone can help me.
Thanks and Regards
Carol
Question
All replies
- Have you tried to use native provider (SqlClient namespace) to get this information instead of using base class? It is quite possible that because DbDataAdapter is not database specific, it does not handle all the information the way you are expecting
Hi VMazur:
Thanks your help. But I still did not get the correct column even i use the objects in SqlClient. The following code is i used:
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[selectedDatabase].ConnectionString))
{
conn.Open();
SqlCommand command = new SqlCommand(string.Format("Select * from {0}", tableName),conn);
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo))
{
DataTable dt = reader.GetSchemaTable();
Console.WriteLine("--------- Schema ------------");
ShowTableDetails(dt);
}
}
Is my code not correct?
Regards
Carol
Look at the MSDN docs () and you're gonna have an idea about why it behaves that way:
Essentially, IsKey can be true for primarykey, OR unique key.
the msdn docs has explicitly convey the idea that the generated set with IsKey=true MAY be a primary key, or a unique key. So App_ID happens to be out of the set in your case. Futhurmore, the set was generated by the server, not the Client.
FillSchema uses the same property the server returned.
Hi Carol
Thought I'd let you know that you are not mad: I get the same problem where I have a Primary Key AND another column specified as being a unique index - seems that the SQL provider doesn't pick up the primary key at all - in our case we have some failsafe code that is supposed to work it out from the GetSchemaTable on a DataReader - which has IsKey on the unique index, but doesn't notice that I also have a primary key on the table.
Good luck. I've had to take the unique index off to get my software to work.
Andy
Sorry folks, this one totally slipped my radar and I forgot to follow up.
Here is the story:
Our code to fetch the "primary key" relies on server BMM (Browse Mode Metadata). What is BMM you ask? We'll let me try to explain.
Normally to fetch metadata from SQL Server you have to make calls to system stored procedures or look at system tables, etc... This causes your client code to make extra expensive round trips to the server. To improve performance in certain common metadata scenarios, we created browse mode in the underlying TDS (Tabular Data Stream) protocol. When you are in browse mode, the server will append extra metadata about results each time it sends them back. We don't leave browse mode on all the time because in most cases the client only needs a small amount of metadata about the result (like column name and data type).
BM includes things like what is the base table name for each column and addition things like is the column part of a primary key, etc... All of this is called BMM.
Now in BMM mode, a unique clustered index is considered a better candidate for a primary key than another index that is marked as a primary key. This is just how it always worked and can lead to some confusion IF you have a unique clustered index AND a primary key on the same table. This choice is smarter because a unique clustered index is actually more efficient than a non-clustered primary key.
So just something to remember, this behavior is by design and we're not going to change it.
- Greetings,
I'm having an issue similar to this and I'm wondering if you could help me with it.
We are doing a Database Refactor project where we are redesigning an existing table and creating a view that looks exactly the same as the old table, so that legacy code doesn't break. We found a problem with exposing the base tables' browse-mode metadata, so we used the VIEW_METADATA option on the said view. However, we are now finding that the SQL code generators in our legacy apps are using this BMM to generate UPDATE statements, and the problem it's having is that it can't find a good primary key to generate the UPDATE statement. So, instead of using the PK to build the WHERE clause of the UPDATE, it uses ALL the columns of the table in the WHERE clause to try to make up for the fact that it can't find a PK. This results in a messy UPDATE statement and is actually causing bugs in some areas.
I imagine that it can't find a PK because it only has access to the View's metadata, and Views don't have PKs. Is there any way we can get around this problem? Is there a way to 'mark' columns of a view as the key columns (other than by doing an indexed view)? Is there a setting somewhere that controls this other than VIEW_METADATA?
Thanks,
SB
|
http://social.msdn.microsoft.com/Forums/en-US/c1c113e2-32dc-4826-b6e0-17dff29c1baf/get-wrong-primary-key-when-i-use-dbdataadapterfillschema-or-dbdatareadergetschematable?forum=adodotnetdataproviders
|
CC-MAIN-2013-48
|
refinedweb
| 961
| 60.95
|
I think I don’t like to be limited and thus I keep exploring and learning new technologies; however, I made a conscious choice in college not to do Java (for whatever reason) and that kept me off Android for so long. But then, there came Xamarin! A cross platform mobile app development software.
Installation
Xamarin allows you to write code in C# and then build it for Android, iOS or Windows Phone. Visual Studio has it integrated, and now we have a Visual Studio for Mac. I grabbed a copy online and installed it to go exploring.
New Project
Launch Visual Studio and pick an Android app project:
Give your app a name and an organisation identifier, together they form the package name on Android Play Store. Complete the Wizard and you have a basic template ready!
IDE
Visual Studio IDE has a familiar interface. The solution will have one project – TipCalculator in this case.
In Android, Resources > layout has Main.axml. “axml” files are created by Xamarin and are equivalent to xml layout files in native Android apps. Layout means the UI.
The code behind file for this layout is MainActivity.cs. An Android app can be described as a set of activities, where each activity has a UI and some code-behind, and some extra files like images, data files, etc.
For example, an activity in this case is to calculate tip: we will design a UI for the user to input bill amount and calculate tip, and we will write code in the code behind to make it work. There can be multiple activities in a complex scenario and navigation from one UI to another while you interact with the app through widgets/controls.
The App
We need to create a UI first. Open Main.axml in designer/source editor and add an
editText to receive input, a calculate button and a
textView to display calculated Tip value.
We added an ‘ID’ to every control in the UI. This will be accessed in the code behind file to make it work. A corresponding ID is generated in Resource.designer.cs
Now some code in code behind file – MainActivity.cs
using Android.App; using Android.Widget; using Android.OS; using System; namespace TipCalculator { [Activity(Label = "Tip Calculator", MainLauncher = true, Icon = "@mipmap/icon")] public class MainActivity : Activity { EditText inputBill; Button cmdCalculate; TextView outputTip; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); inputBill = FindViewById<EditText>(Resource.Id.edittext1); cmdCalculate = FindViewById<Button>(Resource.Id.button1); outputTip = FindViewById<TextView>(Resource.Id.textView3); cmdCalculate.Click += onCalculateClick; } void onCalculateClick(object sender, EventArgs e) { var bill = double.Parse(inputBill.Text); outputTip.Text = (bill * 0.05).ToString(); } } }
In this code,
Label=”Tip Calculator” set the application title.
MainLauncher=true is set to make this activity start on process launch.
OnCreate() takes an argument of type
Bundle. This is passed every time the activity window is destroyed and recreated, and that happens very often including the time we rotate. The previous state is saved in a bundle and calling the constructor with the bundle helps restore the cached state.
To instantiate a layout, we find the layout using
Resource.Layout.Main and set it the current view. This is done by the ID that was created in Resource.designer.cs and maps to the right axml file. This builds the UI and shows it for the current activity.
We then search for ID for the controls of our interest on the UI. In our axml, we declared ID as:
android:id=“@+id/textView3“
This generates an integer ID for the name – textView3:
// aapt resource value: 0x7f0c0055public const int textView3 = 2131492949;
Set an event to button click and add logic to it.
cmdCalculate.Click += onCalculateClick;
Wow! First Android app. With basic knowledge of application development on Windows (.NET), this was quick!
Tip
The application can be deployed to an emulator and tested. If you get deployment error for x86:
Deploying package to 'emulator-5554' The package does not support the device architecture (x86). You can change the supported architectures in the Android Build section of the Project Options. Deployment failed. Architecture not supported.
Right click on Project > Options > Build > Android Build > Advanced tab and select x86.
|
https://www.hackster.io/achindra/android-app-with-xamarin-on-mac-1f0ddf
|
CC-MAIN-2018-34
|
refinedweb
| 712
| 59.09
|
#5 Logging Within My Lambda Function
Before we get to much further and our code gets to complicated, we probably should look at adding some sort of logging within AWS. There are ways in which you can run your code locally for debugging purposes and we will look into this approach later on, but for now we want to leverage AWS Cloud Watch and create a log group specifically for our Lambda function.
appsettings.json
Within the appsettings.json file we want to add some additional JSON which is in two main sections; Logging, and Serilog. There are many logging packages that you can use with AWS and are supported by AWS but Serilog is probably the best one. The Logging section just defines that fact that we want to log some information. Since we’re using Serilog, we have to add a Serilog section that defines it’s AWS usage. This section also allows us to define a custom Log Group which will essentially categorize our logs into a single group and make them easy to find.
So lets add the definition as shown below, you can change the ‘LogGroup’ and ‘CustomLogGroup’ names as required.
{ "Logging": { "LogLevel": { "Default": "Information" } }, "Serilog": { "Region": "eu-west-1", "LogGroup": "MyFirstLambda_AppLog", "CustomLogGroup": "MyFirstLambda_AppLog", "LogLevel": 4, "RetentionPolicy": 5 }, "AllowedHosts": "*", "AppS3Bucket": "", "AWSProfileName": "AWS Default" }
NuGet Packages
To make this work we need to add two additional NuGet packages; Serilog.AspNetCore, and Serilog.Sinks.Console.
This is achieved by right- mouse clicking on the project and selecting Manage NuGet Packages… from the contextual menu.
Within the Browse tab key-in ‘Serilog’ and press enter. A list of all the Serilog Packages will be shown.
From this list select a package and then select ‘Install’.
Then follow the prompts. Repeat this process for all of the required Serilog Packages.
Startup.cs
Within the Startup.cs file add the ‘Using’ reference for Serilog and then within the Startup constructor add the Log.Logger section of code as shown below.
using Serilog; public Startup(IConfiguration configuration) { Configuration = configuration; Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Information() .WriteTo.Console() .CreateLogger(); }
Processor
Within the Processor class which contains the methods for each controller end point. We will add a ‘Using’ reference to Serilog again and then create an instance of ILogger. We can then start logging Information, Warnings, or Errors, in the example below the instance of ILogger has also been passed to the ‘DataRepo’ constructor.
using Serilog; public class DataModelProcessor : IDataModelProcessor { private readonly DataRepo _DataRepo = null; private ILogger _log = null; public DataModelProcessor() { _log = Log.Logger; _log.Information("Creating New Data Model Processor."); _DataRepo = new DataRepo(_log); } }
Once we have implemented the logging through the code we must again publish the project to Lambda and using Postman, call one of the API endpoints. Then we can go to AWS Cloud Watch to review the log in the newly created log group.
AWS Cloud Watch
Now we have provided a way in which we can record log-able events to AWS Cloud Watch and made a request to one of our end points we should now be able to review the log in the custom log group. To do this, let’s log back into the AWS Services Console, and Navigate to Cloud Watch.
Within the Cloud Watch console select the Log Groups link in the sidebar menu.
Within the Log Groups we will then select the Log Group that we created.
The Log Group will contain one or more Log Streams, select the Latest Log Stream.
Within the selected Log Stream, we can see some of the Logged Information. Now we can log Information, Errors, or Warnings we can easily debug our code once we start to create the database connection and start making MySQL calls.
|
http://www.catiawidgets.net/2021/03/11/5-logging-within-lambda/
|
CC-MAIN-2022-21
|
refinedweb
| 624
| 54.52
|
Client Server Java app
Client Server Java app I developed a client server based java networking Instant Messaging app. The client program is needed to be run on the client computer whereas the server program is on server computer. This works in my
Client-Server Architecture
Client-Server Architecture
Client-server architecture can be considered
as a network environment that exchanges information between a server
machine
Server calling of .exe file in the client
Server calling of .exe file in the client I have a requirement with java webapplication.
We are using jboss as appserver on Linux machine.
How can I call a .exe file from client machine?
I want to run .exe from webpage like
proxy server and client using java - Java Beginners
proxy server and client using java how to write program in java for proxy server and client
server client comms
server client comms i am trying to return frame through server client comms anyone can help me about that
i want to return a class to client side but my class defined in server side
Application Server : Java Glossary
Application Server : Java Glossary
... to the
client through the computer network or they can exist on the same....
An
application server can also works as a part of a three-tier architecture
model
Create text file at client's directory from server.
Create text file at client's directory from server. Need java code to create text file at client's directory from server.....
Please Help
tcp client server communication
tcp client server communication i am not been able to find the error in the program
server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws
Multicast under UDP(client server application)
Multicast under UDP(client server application) UDP is used...:
In this project, you will write two classes RMulticastServer (called server in the
following) and RMulticastClient (called client in the following) in Java
RMI Client And RMI Server Implementation
RMI Client And RMI Server Implementation
... comprises of the two separate programs, a server and a client. A typical server... application
provides the mechanism by which the server and the client communicate
Java FTP Client Example
Java FTP Client Example How to write Java FTP Client Example code?
Thanks
Hi,
Here is the example code of simple FTP client in Java which downloads image from server FTP Download file example.
Thanks
What is Java Client Socket?
What is Java Client Socket? Hi,
What is client socket in Java.... The socket that make connectivity with socket client and with a socket server... socket connections. To get connection in client socket in java used the class
Java FTP Client
Java FTP Client What all Java FTP Client available to the Java programmers? Is there any Free FTP Client Library?
Thanks
Hi,
Apache... Client libraries which can be used to connect to the FTP server for:
Uploading
Client's Data with Axis2 and Java
client's data? First of all back-end will be build in Java(will try to implement some... worked with Eclipse(duh) there is very nice feature of generating server/client...Client's Data with Axis2 and Java Hello everyone,
I am studying
Chat Server
-application, server application (which runs on server side) and client application... to make server and for client we have to run
MyClient.java file on the
system that we...;
Server Side Application
Client Side Application
Datagram in network environment
Datagram in network environment
In a network
environment the client... dedicated point-to-point channel between
client and server. All data sent over
how to connect client to server using Sockets
how to connect client to server using Sockets how to connect client to server using Sockets
Web Server
server interacts with the client through a web browser. It delivers
the web... e-mail and building and publishing
web pages. A web server works on a client server model. A computer connected to
the Internet or intranet must have a server
Rmi client
Rmi client Sir i just created client and server following the RMI rule, its running properly in the localhost, when i am trying to run the program in the different machine its not working, i changed the ip also, when i copied
Client Socket Information
Client Socket Information
In this section, you will learn how to get client
socket information. This is a very simple program of java network. Here, we have
Server side validation vs client side validation
Server side validation vs client side validation Can any one tell me... of Server side validation vs client side validation.
The client side validation runs in the browser where as server side validation runs on server
Client Side Coding
sending and receiving data over a network are not considered client-side scripting...
Client Side Coding
Here, the client side coding refers to the code scripted for the end
server
at the client end. He
tries using the following code to create a reliable connection between server and
client:
public Server()
{
try
{
serverSocket... the server and clients exist on the same machine. But, when a client executes
UDP Client in Java
UDP Client in Java
... or
messages for UDP server by the UDP client. For this process you must require..., then you
send messages to UDP server. The sending process has been defined just
Client Side and Server Side coding
Client Side and Server Side coding
The combo of client side and server side coding... to write code in both client side and server side. Some other combinations are &ndash
MySQL Client
a cityscape from a helicopter. MySQL operates on a client-server model...). This general-purpose client provides a graphical interface to the MySQL server. It can... library.
* When connecting to the server with a pre-4.1 client
MySQL Client
a helicopter. MySQL operates on a client-server model, not unlike many other... connecting to the server with a pre-4.1 client program, use an account that still has... it.
The server matches a client against entries in the grant tables based
Network programming
Network programming
write and run a client and a server program using C language in Unix as per the following specifications:
a) A TCP client program will establish a connection and send a text string to the server.
b) A TCP
VOIP Network
-to-use Java client graphical user interface, as well as SNMP/Corba and billing interfaces for straightforward integration into existing network management systems...
VOIP Network
VoIP
Network Management
The MetaSwitch
Application Server
run remotely (connected to
client through a computer network) or can exist...
Application Server
An application server is an application program that accepts connections in order
Chapter 5. Client View of an Entity
client view can also be mapped to non-Java client environments... about the
entity bean. The meta-data information allows loose client/server...
Chapter 5. Client View of an EntityPrev Part I. Exam
What do you think about client-side/server-side coding ?
What do you think about client-side/server-side coding ? Hi,
What do you think about client-side/server-side coding
Multicast Client in Java
UDP Multicast Client in Java
... to send and receive the IP
packet or message by multicast client. Here, we provide...') and port number(5000). Those of any client sends
and receives IP packet
Web Server
pages to the client. Apache and Microsoft's Internet
Information Server (IIS) are two leading web servers. In the case of java
language, a web server is used... for EJB component. Web server accepts HTTP
requests from the client and provides
Installing programs over a network
Installing programs over a network Hi, i want to write a java program that will allow me to install programs from a server to a client machine. Any help will be appreciated. Thanks
How to print list of files in client system
need to come from client system. but i done this functionality in java ,it is giving prints to server printer not to client printer.Is it possible....
Thanks...How to print list of files in client system have some list of files
Server Sockets
program and a server program. In java there is a java.net package, which...
the client side connection and second is server socket, which implement
the server side connection.
In
Java there are many socket class that is used
server with two port - Java Server Faces Questions
server with two port Hello,
want to write two port server socket program using Java, (i.e. single server program which is listening on two ports...
information.
Thanks
Failed Client-Socket Communication
Failed Client-Socket Communication I hve written a server program & a client program. The server is supposed to echo watever is typed in the client. I hve to get 16 values to be echoed. I hve created a string and all
java client server program for playing video file(stored in folder in the same workspace) using swings
java client server program for playing video file(stored in folder in the same... a client server program to play a video file, when I run both client and server... class client extends JFrame
{
clientreceive cr;
JPanel p;
public void init to create a client/server app.
i know that JIternalFrame should be used
Unable to create web service client in java
Unable to create web service client in java When i try to create a client for the WSDL with JBossAS 4.2 server configuration and JBossWS as server runtime.
I get the following
Eclipse Plugin-Rich Client Applications
Eclipse Plugin-Rich Client Applications.... Is is an example of a business oriented, rich client application which benefits from..., and many unique and very useful features. With IAB Studio RIA Enterprise Server
what is the server
different servers to clients on the network. Sometimes server software is designed...what is the server what is the server?
Server: A computer, or a software package, that provides a specific kind of service to client
Installing programs over a network using java
Installing programs over a network using java Hi, i want to write a java program that will allow me to install programs from a server to a client machine. Any help will be appreciated. Thanks
Client Side Application
Client Side Application
For creating the Client side application firstly... the login button it shows the next frame that Client Frame and it
consist one
FTP Server
FTP Server i'm working on ftp server if one client has uploaded a file i need to save the details of the user who has uploaded the file like username,filename & ipaddress using java
Tomcat Server
Tomcat Server Why my tomcat server installation stop at
using:jvm c:\program files\java\jdk 1.6.0\bin\client\jvm.dll.
Even though i trying to install several times.
please help me....
Installing Tomcat Server
Sending and receiving information to the UDP Client in Java
Sending and receiving information to the UDP Client in Java... will provide send and receive information by
the UDP client in Java. UDP client... to be send into the UDP
server and it also sends a message to UDP client in the text
Web 2.0 Model
Web 2.0 Model
Web 2.0 includes two major model move, one is ?user
generated content? and other is ?thin client computing?.
User
Generated Content
User generated
java with brava server integaration
java with brava server integaration how to integrate java with brava java client
Chapter 2. Client View of a Session Bean
to discover information about the
session bean, and to allow loose client/server...
Chapter 2. Client View of a Session BeanPrev ...;Client View of a Session BeanIdentify correct and incorrect statements
java server - Development process
java server Develop multi-threaded echo server and a corresponding GUI client in java
Server side Validation
Server Side Validation
It is very important to validate the data coming from the client side, so
that wrong data could not process into the application...;/html>
Write a Simple Model for login application
LoginModel.java
package
Java Client Application
Java Client Application Java Client Application
Java HTML Client Application
Java HTML Client Application Java HTML Client Application
Java Client Application example
Java Client Application example Java Client Application example
Java server Faces Books
Java server Faces
Books
Java
server Faces...;
Core
Java server Faces
weblogic server
and applications.
WebLogic server is based on Java 2 Platform, Enterprise Edition (J2EE... application on any client to interoperate with server applications, Enterprise...weblogic server as a java developer how much knowledge he has
Difference between Web Server and Application Server
the
Application server allows business logic to client through various protocols... dynamically.
For example, J2EE application server can run EJBs (Enterprise Java Beans... Application server
provides methods that client applications can call.
Application
Client Side validation in Struts 2 application
that will
generate Java Script code for client side validation. In the last section we... for
generating the client side java script.
Developing JSP pages
Here... Client Side validation in Struts 2 application
write a program that Implement an integrated COM client server to add two numbers.by visuall studio 2010
write a program that Implement an integrated COM client server to add two numbers.by visuall studio 2010 write a program that Implement an integrated COM client server to add two
numbers.by visuall studio 2010 if someone can do
Server_Gives_Null_Response
port(6066). I have one client class which is in different java project. My... for connection at port 6066.
When i run my client class form different java... the server.
Kindly give the solution how can i get response at client class.
I
Save file on Client Machine - Development process
Save file on Client Machine Hi my application is running on main server machine and all the users of the application are accessing them as where boserver is the name of server machine, now when a client
Network Project
Network Project I am writting a java program for a LAN which creates accounts for students and allows them to view assignments posted by lecturers... would create folders for each student on the server and also how i would verify
web server - WebSevices
web server web server we need to restart tomcat server when we upload java class file but no need to restart when we upload jsp file. why? A web server handles the HTTP protocol while an application server exposes
CORBA and RMI Books
;
Client/Server Programming with Java... of the client/server architectures of Java and CORBA. It then goes on to cover...;
Client/Server Programming with Java and CORBA, 2E
Programming
Java Client webservice
for factorial calculation.
Then develop a Java Client file instead of Servlet or Jsp... a new project for the Client
Take a new Java Application project
Give the name as Java-webservice-Client
Now Right Click on this client project
Tomcat server/any application server
Tomcat server/any application server how the server understands request is coming from client and how can it give response within very short span of time
Java socket Programming - Java Server Faces Questions
Java socket Programming I want to create a web server. How do I retrieve URL sent by client and how do server responds to the specific URL requested by the client
chat server
chat server how to write code for Many-Many (Broad cast): Each client opens a socket connection to the chat server and writes to the socket. Whatever is written by one party can be seen by all other parties
Tomcat Server
is Tomcat Server?
Tomcat Server is a pure Java HTTP web server environment to run Java code.
Tomcat Server is an open source web server. Tomcat Server... for receiving the request
from client on specific TCP port on the server and send
Application Server and Web Server - WebSevices
. An application server providers allows the client to access the business logic for use...Application Server and Web Server General difference, Application Server and Web Server Answer: A Web server handles the HTTP protocol
http Client Authentication
http Client Authentication hi friends,
i am trying a java API using HTTPCLient post method. in which i am getting output having some... {
System.out.println("\n Place Collection URL = "+ placeurl);
HttpClient client = new
Vayala
is automatically connected to one network of chat client without a central server or much... administration chat client
No server required
Multicast file...;
Vayala is a multipurpose chat client for developers. It offers a platform
Server running Button - Java Beginners
Server running Button Hi there,
I have a created a GUI using NetBeans IDE 6.1. The aim of this interface is to display the messages that have been recived by the server , when the client is connected , in the textArea
Identify correct and incorrect statements or examples about the client's view
of exceptions received from an enterprise bean invocation.
the client's view
of exceptions received from an enterprise bean invocation...;
Identify correct and incorrect statements or examples about the client's view....
A client accesses an enterprise Bean either through
Chat Server
What is Java Server Faces?
, developed through Java Community Process (JCP), that makes it easy to build user interfaces for java web applications by assembling reusable components... in a form.
JSF is based on well established
Model-View-Controller
Open Source E-mail Server
;
Webmail client, Mail
server
Innovating within the email server industry since... making its Java Enterprise System server software open-source, John Loiacono...Open Source E-mail Server
MailWasher Server Open Source
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles
|
http://www.roseindia.net/tutorialhelp/comment/99445
|
CC-MAIN-2015-22
|
refinedweb
| 2,941
| 54.93
|
Returns an
XPathResult based on an XPath expression and other given parameters.
Syntax
var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );
xpathExpressionis a string representing the XPath to be evaluated.
contextNodespecifies the context node for the query (see the XPath specification). It's common to pass
documentas the context node.
namespaceResolveris a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document.
nullis common for HTML documents or when no namespace prefixes are used.
resultTypeis an integer that corresponds to the type of result
XPathResultto return. Use named constant properties, such as
XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9.
resultis an existing
XPathResultto use for the results.
nullis the most common and will create a new
XPathResult
Example
var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null); /* Search the document for all h2 elements. * The result will likely be an unordered node iterator. */ var thisHeading = headings.iterateNext(); var alertText = "Level 2 headings in this document are:\n"; while (thisHeading) { alertText += thisHeading.textContent + "\n"; thisHeading = headings.iterateNext(); } alert(alertText); // Alerts the text of all h2 elements
Note, in the above example, a more verbose XPath is preferred over common shortcuts such as
//h2. Generally, more specific XPath selectors as in the above example usually gives a significant performance improvement, especially on very large documents. This is because the evaluation of the query spends does not waste time visiting unnecessary nodes. Using // is generally slow as it visits every node from the root and all subnodes looking for possible matches.
Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the body tag, you can use this:
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
Notice in the above
document.body has been used as the context instead of
document so the XPath starts from the body element. (In this example, the
"." is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving
//h2) the query would start from the root node (
html) which would be more wasteful.)
See Introduction to using XPath in JavaScript for more information.
Notes
- XPath expressions can be evaluated on HTML and XML documents.
- While using document.evaluate() works in FF2, in FF3 one must use someXMLDoc.evaluate() if evaluating against something other than the current document.
Result types
(Merge with Template:XPathResultConstants?
These are supported values for the
resultType parameter of the
evaluate method:
Results of
NODE_ITERATOR types contain references to nodes in the document. Modifying a node will invalidate the iterator. After modifying a node, attempting to iterate through the results will result in an error.
Results of
NODE_SNAPSHOT types are snapshots, which are essentially lists of matched nodes. You can make changes to the document by altering snapshot nodes. Modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed.
Specifications
Browser compatibility
Legend
- Full support
- Full support
- No support
- No support
|
https://developer.mozilla.org/it/docs/Web/API/Document/evaluate
|
CC-MAIN-2020-29
|
refinedweb
| 562
| 50.53
|
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.. Segher 2018-07-24 Segher Boessenkool <segher@kernel.crashing.org> PR rtl-optimization/85160 * combine.c (is_just_move): New function. (try_combine): Allow combining two instructions into two if neither of the original instructions was a move. --- gcc/combine.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/gcc/combine.c b/gcc/combine.c index cfe0f19..d64e84d 100644 --- a/gcc/combine.c +++ b/gcc/combine.c @@ -2604,6 +2604,17 @@ can_split_parallel_of_n_reg_sets (rtx_insn *insn, int n) return true; } +/* Return whether X is just a single set, with the source + a general_operand. */ +static bool +is_just_move (rtx x) +{ + if (INSN_P (x)) + x = PATTERN (x); + + return (GET_CODE (x) == SET && general_operand (SET_SRC (x), VOIDmode)); +} + /* Try to combine the insns I0, I1 and I2 into I3. Here I0, I1 and I2 appear earlier than I3. I0 and I1 can be zero; then we combine just I2 into I3, or I1 and I2 into @@ -2668,6 +2679,7 @@ try_combine (rtx_insn *i3, rtx_insn *i2, rtx_insn *i1, rtx_insn *i0, int swap_i2i3 = 0; int split_i2i3 = 0; int changed_i3_dest = 0; + bool i2_was_move = false, i3_was_move = false; int maxreg; rtx_insn *temp_insn; @@ -3059,6 +3071,10 @@ try_combine (rtx_insn *i3, rtx_insn *i2, rtx_insn *i1, rtx_insn *i0, return 0; } + /* Record whether i2 and i3 are trivial moves. */ + i2_was_move = is_just_move (i2); + i3_was_move = is_just_move (i3); + /* Record whether I2DEST is used in I2SRC and similarly for the other cases. Knowing this will help in register status updating below. */ i2dest_in_i2src = reg_overlap_mentioned_p (i2dest, i2src); @@ -4014,8 +4030,10 @@ try_combine (rtx_insn *i3, rtx_insn *i2, rtx_insn *i1, rtx_insn *i0, && XVECLEN (newpat, 0) == 2 && GET_CODE (XVECEXP (newpat, 0, 0)) == SET && GET_CODE (XVECEXP (newpat, 0, 1)) == SET - && (i1 || set_noop_p (XVECEXP (newpat, 0, 0)) - || set_noop_p (XVECEXP (newpat, 0, 1))) + && (i1 + || set_noop_p (XVECEXP (newpat, 0, 0)) + || set_noop_p (XVECEXP (newpat, 0, 1)) + || (!i2_was_move && !i3_was_move)) && GET_CODE (SET_DEST (XVECEXP (newpat, 0, 0))) != ZERO_EXTRACT && GET_CODE (SET_DEST (XVECEXP (newpat, 0, 0))) != STRICT_LOW_PART && GET_CODE (SET_DEST (XVECEXP (newpat, 0, 1))) != ZERO_EXTRACT -- 1.8.3.1
|
https://gcc.gnu.org/ml/gcc-patches/2018-07/msg01412.html
|
CC-MAIN-2018-43
|
refinedweb
| 331
| 55.84
|
Martin Sebor wrote:
>
>Travis Vitek wrote:
>> As most of us know, I've been working on type_traits for the 4.3
>> release. In doing so, I've noticed that there are some pretty
>> significant differences between tr1 and c++0x. My question is what
>> _exactly_ are we wanting to implement here? Do we want to
>> have the tr1 stuff as it is documented [in the tr1 final], or do
>> we want the tr1 additions as they appear in the c++0x working
>> draft?
>>
>> Some of the issues...
>>
>> 1. The namespace that these features appear in [std::tr1 vs std]
>> 2. Section numbers for test names [4.meta.rel.cpp vs
>> 20.meta.rel.cpp]
>> 3. Subtle differences between behavior of traits
>> 4. Deprecated traits like add_reference [now
>> add_lvalue_reference]
>>
>> I just want to make absolutely sure that I'm working with the same
>> expectations as everyone else and that we are trying to implement the
>> c++0x draft features that were introduced in tr1. I'm
>currently writing
>> to the c++0x draft, but my tests use old section numbers from the tr1
>> final, and everything I've written is currently in the std::tr1
>> namespace [using a macro _TR1].
>
>IMO, we should target C++ 0x and forget TR1 even exists ;-)
So no _TR1 macro, no std::tr1 namespace, all tests named according to
the section in the draft in which the feature appears, and requirements
directly from the draft. That sounds good.
>That said, all C++ 0x code should be guarded with the same
>macro until the next standard is released. Maybe something
>like _RWSTD_NO_EXT_CXX_0X?
>
That is something that I hadn't considered. I'll add that immediately.
>Martin
>
|
http://mail-archives.apache.org/mod_mbox/stdcxx-dev/200805.mbox/%3CCFFDD219128FD94FB4F92B99F52D0A499AA85B@exchmail01.Blue.Roguewave.Com%3E
|
CC-MAIN-2015-35
|
refinedweb
| 279
| 72.97
|
in reply to
Module naming problems, or time ill spent.
I've been spending a lot more time programming in Ruby lately, but I have OO Perl (and merlyn's 'perlboot' intro) to thank for having a hope in heck of doing OO anything. In Ruby or Perl, if my classes are specific to the application at hand, I would make that my namespace and then group functions or objects accordingly. Say my application was a tool for writing books, I'd make package names like BookMaster::TOC (for managing tables of contents), BookMaster::Chapter (for managing chapters), and BookMaster::DB (for interfacing with a DB).
Now, if I found that I had some general utility function that was important to me-- suppose I were making a linked list class to make it so I could store each paragraph in a chapter in a list that would be more efficient to insert and delete items from than a vanilla array, then I might look on CPAN and see if there is a fitting namespace, like List::* and then call my class List::Linked.
And just to soothe your naming concerns, there is a whole big section on naming variables and stuff in "Code Complete". So you're not the first person to take it seriously. :)
Yes
No
Other opinion (please explain)
Results (99 votes),
past polls
|
http://www.perlmonks.org/?node_id=174055
|
CC-MAIN-2015-40
|
refinedweb
| 226
| 60.69
|
scrolling GUICtrlCreateGroup groups
Started by
DrPickles,
3 posts in this topic
You need to be a member in order to leave a comment
Sign up for a new account in our community. It's easy!
Register a new account
Already have an account? Sign in here.
Similar Content
- By mpower
Hi
- By AndyS01
I would like to center the text on a Group box (GUICtrlCreateGroup()) along its top horizontal line, but I can't find any examples of this.
Can this be done?
Example script:
#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <EditConstants.au3> Example() Func Example() Local $flags = 0, $iMsg = 0 GUICreate("My GUI group") $flags = BitOR($flags, $WS_THICKFRAME) $flags = BitOR($flags, $ES_CENTER) GUICtrlCreateGroup("Group 1", 10, 20, 190, 140, $flags) ; I want to cnter "Group 1" GUICtrlCreateRadio("Radio 1", 20, 50, 50, 20) GUICtrlCreateRadio("Radio 2", 20, 70, 60, 50) GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) ; Loop until the user exits. While 1 $iMsg = GUIGetMsg() If $iMsg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example
- By Bakiki
The title says it all really. I've tried to achieve this using arrays & dividing the gui into chunky blocks , but so far have fail....
Any idea would be appreciated.
Thanks
- By zvvyt
Hello once again!
What I have is:
A groupcontrol created by GuiCtrlCreateGroup and inside it I have a few icons from GuiCtrlCreateIcon.
What I want to do is when I click within the group or on the icons I'll get a notification, or a message retrieveable by GuiGetMsg().
Any suggestions?
Best regards,
zvvyt
- By Quinch
I?
|
https://www.autoitscript.com/forum/topic/181036-scrolling-guictrlcreategroup-groups/
|
CC-MAIN-2017-43
|
refinedweb
| 258
| 55.95
|
Gl, then this is probably way over your head.
This document began its life as a post to gtk-perl-list about a redesign of the fundamentals of the bindings; today it is the reference documentation for the developers of the bindings.
To reduce confusion, refer to GLib, the C library, with a capital L, and Glib the perl module with a lower-case l. While the Gtk2 module is the primary client of Glib, it is not necessarily the only one; in fact, the perl bindings for the GStreamer library build directly atop Glib. Therefore, this document describes just the GLib/Glib basics. For details on how Gtk2 extends upon the concepts presented here, see Gtk2::devel.
In various places, we use the name GPerl to refer to the actual binding subsystem.
In order to avoid getting very quickly out of date, this document doesn't go into great detail on APIs. gperl.h is rather heavily commented, and should be considered the canonical source of correct API information.
GLib is a portability library for C programs, providing a common set of APIs and services on various platforms. Along with that you get libgobject, which provides an inheritance-based type system and other spiffy things.
Glib, as a perl module, must decide which portions of GLib's facilities to map to perl and which to abstract and encapsulate.
In the grand scheme, the bindings have been designed with a few basic tenets in mind:
Stick close to the C API, to allow a perl developer to use knowledge from the C API and API reference docs with the perl bindings; this is overruled in some places by the remaining tenets.
Be perlish. This is the most important. The user of the perl bindings should not have to worry about memory management, reference counting, freeing objects, and all that stuff, else he might as well go write in C instead.
Leave out deprecated functionality.
Don't add new functionality. The exceptions to this rule are consolidation of methods where default parameters may be used, or where the direct analog from C is not practical.
Be lightweight. As little indirection and bloat as possible. If possible, implement each toplevel module (e.g., Glib, Gtk2, Gnome2, GtkHTML, etc) as one .pm and one .so.
Be extensible. Export header files and typemaps so that other modules can easily chain off of our base. Do not require the entirely of Gtk2 for someone who needs only to build atop GObject.
In keeping with the tenet of not requiring the entire car for someone who only needs a single wheel, I broke the glib/gobject library family into its own module and namespace. This has proved to be a godsend, as it has made things very easy to debug; there's a clean separation between the base of the type system and the stuff on top of it.
The Glib module takes care of all the basic types handled by the GObject library --- GEnum, GFlags, GBoxed, GObject, GValue, GClosure --- as well has signal marshalling and such in GSignal. I'll discuss each of these separately.
In practice, you will rarely see direct calls to the functions that convert objects in and out of perl. Most code should use the C preprocessor to provide easier-to-remember names that follow the perl API style, e.g., newSVGObject(obj) rather than gperl_new_object(type,obj) and SvGObject(sv) instead of gperl_get_gobject(type, sv). The convention used in all of gtk2-perl is described in Gtk2::devel.
FIXME maybe this section should be rolled into the GBoxed and GObject sections?
In order to use the C data structures from Perl, we need to wrap those objects up in Perl objects. In general, a Perl object is simply a blessed reference. A typical scheme for representing C objects in perl is bless a reference to a scalar holding the C pointer value; perl will destroy the reference-counted scalar when there are no more references to it, and one would normally destroy the underlying data structure at this point. However, GLib is a little more complex than your typical C library, so this easy, typical setup won't work for us.
GBoxed types are opaque wrappers for C structures, providing copy and free functions, to allow the types to be used generically. For the most part we can get away with using the typical scheme described above to provide an opaque object, but in some instances an opaque object is very alien in perl. The Glib::Boxed section explains how we get around this.
GObject, on the other hand, is a type-aware, reference-counted object with lifetime semantics that differ somewhat from perl SVs. Thus we need something a bit more sophisticated than a plain old opaque wrapper; in fact, we use a blessed hash reference with the pointer to the C object tucked away in attached magic, and a pointer to the SV stored in the GObject's user data. The combined perl/C object does some nifty reference-count borrowing to ensure that object lifetime is managed correctly.
If an object is created by a function that returns directly to perl, then the wrapper returned by that function should "own" the object. If no other code assumes ownership of that object (by ref'ing a GObject or copying a GBoxed), then the object should be destroyed when the perl scalar is destroyed (actually, as part of its destruction).
If a function returns a preexisting object owned by someone else, then the bindings should NOT destroy the object with the perl wrapper. How we handle this for the various types is described below.
GType is the GObject library's unique type identifier; this is a runtime variable, because GLib types may be loaded dynamically. The direct analog in perl is the package name, which uniquely specifies an object's class. Since these do about the same thing, we completely replace the GType with the perl package.
For various reasons, mostly to do with robustness and performance, there is a one-to-one mapping between GType classes and perl package names. These must be registered, usually as part of the module initialization process.
In addition, the type system tries as hard as it can to recover when things don't go well, using the GType system to its advantage. If you return a C object of a type that is not registered with Gperl, such as MyCustomTypeFoo, gperl_new_object (see below) will warn you that it has blessed the unknown MyCustomTypeFoo into the first known package in its ancestry, Gtk2::VBox.
GBoxed and GObject have distinct mapping registries to avoid cross-pollination and mistakes in the type system. See below.
To assist in handling inheritance that isn't specified directly by the GType system, the function gperl_set_isa allows you to add elements to the @ISA for a package. gperl_register_object does this for you, but you may need to add additional parents, e.g., for implementing GInterfaces. (see Gtk2/xs/GtkEntry.xs for an example)
You may be thinking that we could use substitution rules to map the GObject classes to perl packages. In practice, this is a bad idea, fraught with problems; the substitution rules are not easily extendable and are easily broken by extension packages which don't follow the naming conventions.
GLib provides a mechanism for creating runtime type information about enumeration and flag types. Enumerations are lists of specific values, one of which may be used at at time, whereas multiple flag values may be supplied at a time. In C flags are meant to be used with bitfields. A GType is associated with the various valid values for a given GEnum or GFlags type as strings, in both full-name and nickname forms.
GPerl uses this mechanism to avoid the need to know integer values for enum and flag types at the perl level. An enum value is just a string; a bitfield of flag values is represented as a reference to an array of strings. These strings are the GLib-provided nicknames. For the convenience of a perl developer, the bindings treat '-' and '_' as equivalent when looking up the corresponding integer values during conversion.
A GEnum or GFlags type mapping should be registered with
void gperl_register_fundamental (GType gtype, const char * package);
so that their package names can be used where a GType is required (for example, as GObject property types or GtkTreeModel column types).
The basic functions for converting between C and perl values are
/* croak if val is not part of type, otherwise return * corresponding value. this is the general case. */ gint gperl_convert_enum (GType type, SV * val); /* return a scalar which is the nickname of the enum value * val, or croak if val is not a member of the enum. */ SV * gperl_convert_back_enum (GType type, gint val); /* collapse a list of strings to an integer with all the * correct bits set, croak if anything is invalid. */ gint gperl_convert_flags (GType type, SV * val); /* convert a bitfield to a list of strings, or croak. */ SV * gperl_convert_back_flags (GType type, gint val);
Other utility functions allow for finer-grained control, such as the ability to pass unknown values, which can be necessary in special cases. In general, each of these functions raises an exception when something goes wrong. To be helpful, they croak with a message listing the valid values when they encounter invalid input.
GBoxed provides a way to register functions that create, copy, and destroy opaque structures. For our purposes, we'll allow any perl package to inherit from Glib::Boxed and implement accessors for the struct members, but Glib::Boxed will handle the object and wrapper lifetime issues.
There are two functions for creating boxed wrappers:
SV * gperl_new_boxed (gpointer boxed, GType gtype, gboolean own); SV * gperl_new_boxed_copy (gpointer boxed, GType gtype);
If own is TRUE, the wrapper returned by gperl_new_boxed will take boxed with it when it dies. In the case of a copy, own is implied, so there's a separate function which doesn't need the own option.
To get a boxed pointer out of a scalar wrapper, you just call gperl_get_boxed_check --- this will croak if the sv is undef or not blessed into the specified package.
When you register a boxed type you get the option of supplying a table of function pointers describing how the boxed object should be wrapped, unwrapped, and destroyed. This allows you to decide in the wrapping function what subclass of the boxed type's class the wrapper should actually take (a trick used by Gtk2::Gdk::Event), or represent a boxed type as a native perl type (such as using array references for Gnome2::Canvas::Point objects). All of this happens automagically, behind the scenes, and most types assume the default wrapper class.
See the commentary in gperl.h for more information.
The GObject knows its own type. Thus, we need only one parameter to create a GObject wrapper. In reality, we ask for two:
SV * gperl_new_object (GObject * object, gboolean own);
The wrapper SV will be blessed into the package corresponding to the gtype returned by G_OBJECT_TYPE (object), that is, the bottommost type in the inheritance chain. If that bottommost type is not known, the function walks back up the tree until it finds one that's known, blesses the reference into that package, and spits out a warning on stderr. To hush the warning, you need merely call
In general, this process will claim a reference on the GObject (with g_object_ref()), so that the C object stays alive so long as there is a perl wrapper for it. If <i>own</i> is set to TRUE, the perl wrapper will claim ownership of the C object by removing that reference; in theory, for a new GObject, fresh from a constructor, this leaves the object with a single reference owned by the perl object. The next question out of your mouth should be, "But what about GObject derivatives that require sinking or other strange methods to claim ownership?" For the answer, see the GtkObject section's description of sink functions.
void gperl_register_object (GType gtype, const char * package);
This magical function also sets up the @ISA for the package to point to the package corresponding to g_type_parent (gtype). [Since this requires the parent package to be registered, there is a simple deferral mechanism, which means your @ISA might not be set until the next call to gperl_register_object.]
There are two ways to get an object out of an SV (though I think only one is really needed):
GObject * gperl_get_object (SV * sv); GObject * gperl_get_object_check (SV * sv, GType gtype);
The second one is like the first, but croaks if the object is not derived from gtype.
You can get and set object data and object parameters just like you'd expect.
All of this GObject stuff wouldn't be very useful if you couldn't connect signals and closures. I got most of my handling code from gtk2-perl and pygtk, and it's pretty straightforward. The data member is optional, and must be a scalar.
To connect perl subroutines to GSignals I use GClosures, which require the handling of GValues.
Use a GPerlClosure wherever you could use a GClosure and things should work out great. FIXME say more here
Function pointers are required in many places throughout gtk+, usually for a callback to be used as a "foreach" function or for some other purpose. Unfortunately, a majority of these spots aren't designed to work with GClosures (usually by lacking a way to destroy data associated with the callback when it is no longer needed). For this purpose, the GPerlCallback wraps up the gruntwork of using perl's call_sv to use a callback function directly.
perl(1), perlxs(1), perlguts(1), perlapi(1), perlxstut(1), ExtUtils::Depends(3pm), ExtUtils::PkgConfig(3pm) Glib(3pm), Glib::Object::Subclass(3pm), Glib::xsapi(3pm)
muppet <scott at asofyet.
|
http://search.cpan.org/~xaoc/Glib-1.261/devel.pod
|
CC-MAIN-2013-48
|
refinedweb
| 2,315
| 59.03
|
Writing PHP Extensions with Zephir
PHP would not be as popular today if it was not for its extension system. Developers for PHP have created extensions that hook into just about everything, and by that token end-users can turn around and use systems that are not natively in PHP.
A good example is the database drivers. Many new developers may not realize it right away, but PHP does not natively support all of its databases in core. Things like Firebird, Oracle, and MSSQL are provided as extensions to the core system.
There's other things too, like cURL, XSL(T), and Subversion, that are made available to the language via extensions. If you want a full list, feel free to check out.
The downside to extensions is that they cannot be written in PHP. Extensions are generally written in C and require a decent knowledge of how the PHP core language works. I can write C code, and I could probably learn to write extensions without too much trouble, but many people don't know C. Those developers are generally out of luck and must rely on other developers to make extensions for them.
Why would you need an extension in the first place? The most common reason is that you need access to an existing library. You can create a wrapper around the existing library as a PHP extension, and PHP will then be able to use that library. That is the motivation behind many popular extensions developers install for PHP (like cURL).
The other reason is performance. PHP is a dynamic language and that comes with some pitfalls. Using an extension brings your code down to running at the C level and means that it doesn't need to go through as much to be compiled and run by the server. If you have lots of computationally expensive instructions you need to run, porting that logic to an extension might be a good way to increase performance.
For those that do not want to learn C, but want to get a taste of building their own extensions, there is a new project from the Phalcon project named Zephir. It was born out of a need to make Phalcon, an extension-based framework, easier to maintain, and it sits in between the C and PHP level as a language. Zephir will take the source code you generate and create a PHP extension out of it that you can install on your server. It does not help expose things like libraries on the system, but it will definitely help move logic into an extension.
Why?
As made evident by projects like Facebook's HHVM, some developers need the performance that a compiled language provides as well as the structure that a staticly-typed language provides. In PHP when you type
$a = 1,
$a can be used as a string, integer, float, or boolean value. The engine will take care of converting it to the most appropriate type of value and you do not have to worry about doing that yourself.
In staticly typed languages you tell the compiler if something is an integer or string, and if you need to convert it to something else you must do it manually. The dynamic nature of PHP comes at a cost though. Moving the logic to a staticly compiled language will allow better compilation (since that happens outside of PHP) and faster code.
The Zephir Code
Zephir is a system that you install on your development machine, so the first thing to do is actually install Zephir.
Their Github page has instructions for doing this, but I also went ahead and created a vagrant box that will install everything you need for Zephir and will set it up. It is stuck at whatever version of Zephir I put in the repository last, but updating it is fairly easy. You can clone/fork the code at.
Once you have Zephir installed, go to wherever you have the project checked out. If you are using my Vagrant box, make sure to
vagrant ssh in and switch to the
/vagrant directory.
In here you'll find everything Zephir needs to build extensions for you. If you want to look at some sample code have a peek inside the
tests/ folder. In fact, let's look at
tests/arithmetic.zep and poke around the code a bit.
The first thing you'll notice is that the code is pretty readable. It is kind of a mashup between C and PHP, so PHP developers should feel quite at home reading this code. We have namespaces, classes, functions, and variables. Not too bad.
namespace Test; class Arithmetic { public function intSum() { int a, b, c; let a = 1, b = 2, c = a + b; return c; } // ...
The first main difference we seen is on line 12, where we declare
a,
b, and
c as integers. You can use
var instead and let the compiler handle it, but Zephir has support for static typing. Zephir will allow you to staticly type Integers, Booleans, Logs, and Characters. Things like Strings, arrays, and other Objects are declared using the
var keyword.
On line 14 we see another difference with the keyword
let.
Unlike PHP we have to let Zephir know we're assigning a value to a variable after it's been instantiated (though you can assign it a default value when you declare it).
If you want to look at all the differences, check out the official website at.
Let's build an extension
The first thing we need to do is let Zephir know about our new namespace. Everything that Zephir does is namespaced, and the default checkout of Zephir has it set to the
Test namespace. Open up
config.json, and let's type in a new namespace under the
namespace key. For the sake of the example and to keep it unique, we'll call it 'myframework'.
Zephir will use the namespace to figure out which folder the source code is in. Since we set our namespace to 'myframework', we need to create a new folder in the project named
myframework/. Inside of here all of our code will live. You can nest folders in here as well, which will just create a deeper namespace. For example, if you have a folder structure of
myframework/graphing/, then the namespace will be
Myframework\Graphing. The folder structure is pretty much PSR-1 standards, if you want to think of it that way.
We are going to build a basic calculator. Inside of our
myframework/ folder, create a file named
calculator.zep. Inside there, let's create our class (
Calculator) and give it a basic addition function:
namespace Myframework; class Calculator { public function add(int a, int b) { return a + b; } }
This may be pretty bare bones, but it will be enough for right now. We're going to have a class named
Myframework\Calculator with an
add() function. It takes two integers and adds them together. Now we need to let Zephir translate this into C code. To do this, run
bin/zephir compile from the root of our project. This will invoke the Zephir compiler and generate the extension files for us. For our basic little project this should take just a moment. The compiled output is stored in the
ext/ directory. You can see the actual code that is generated if you look in
ext/myframework/calculator.c.
Now, this doesn't work automatically with PHP because this extension isn't compiled as an extension. This is just all translated into what we need to build an extension. The nice thing is that you build this extension just like you do any other extension! We'll phpize it, configure, and make it.
$ cd ext/ $ phpize $ ./configure $ make $ sudo make install $ echo "extension=/usr/lib/php5/20100525/myframework.so" | sudo tee -a /etc/php5/cli/conf.d/myframework.ini
The last line may need to be modified for your specific installation, but that should work with our vagrant box. The extension should now be available to your PHP installation. Let's take a look at it through the CLI interface:
vagrant@precise64:/vagrant$ php -a Interactive mode enabled php > $calc = new Myframework\Calculator; php > var_dump($calc->add(2, 1)); int(3)
Where To Go From Here
Making more complex extensions is just as easy. Create more classes under your namespace, compile for Zephir, and then compile for your PHP installation. Take a look at the documentation and their blog for more information about control structures, using arrays, and more language constructs. Zephir does warn that it is not ready for production (in fact, at the time of this writing it is only at 0.2.0a), but it will be growing more and more mature as they get it ready for use with the Phalcon framework.
Zephir seems like a great way to port complex or domain-specific logic into an extension without having to learn the nitty-gritty details of learning C.
Share your thoughts with @engineyard on Twitter
|
https://blog.engineyard.com/2014/writing-php-extensions-with-zephir
|
CC-MAIN-2015-40
|
refinedweb
| 1,512
| 71.85
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.