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 |
|---|---|---|---|---|---|
Reporting application for PyFB project
Project description
Your project description goes here
Documentation
The full documentation is at.
Quickstart
Install pyfb-reporting:
pip install pyfb-reporting
Add it to your INSTALLED_APPS:
INSTALLED_APPS = ( ... 'pyfb_reporting.apps.PyfbReportingConfig', ... )
Add pyfb-reporting’s URL patterns:
from pyfb_reporting import urls as pyfb_reporting_urls urlpatterns = [ ... url(r'^', include(pyfb_reporting_urls)), ... ]
Features
- TODO
Running Tests
Does the code actually work?
source <YOURVIRTUALENV>/bin/activate (myenv) $ pip install tox (myenv) $ tox
Credits
Tools used in rendering this package:
History
1.2.1 (2020-10-11)
- Correct cdr detailed view (billsec and costsec were inversed)
1.2.0 (2020-10-06)
- Update API
- Add field in CDR to have the correct value of the billed duration by provider
1.1.2 (2020-05-29)
- Correct little bug
1.1.0 (2020-05-27)
- Add a link to gross CDRs in CDR detail view
- Add CDR export feature
- New date filter in CDR list
1.0.0 (2020-05-21)
- Provider can be search in CDR list view
- CDR detail view has been reworked
- Call class has been added (on-net / off-net)
0.9.5 (2020-02-21)
- Error in DB migration
0.9.4 (2020-02-19)
- Add uuid field for CDR
- Create RREvent model
0.9.3 (2019-06-23)
- Show CDR form Latest one to older ones
0.9.2 (2019-06-22)
- Add route_json in cdr
- Remove unused field
- Admin interface enhancements
0.9.1 (2019-06-18)
- Change duration filed from integer to decimal.
0.9.0 (2019-04-30)
- First release on PyPI.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyfb-reporting/1.2.1/ | CC-MAIN-2021-39 | refinedweb | 287 | 58.48 |
On Sat, Apr 17, 2004 at 10:01:55PM +0200, Thomas Dupouy wrote: >Hi debian mentors. >I am looking for a sponsor for two packages : > newpki-server : PKI based on the OpenSSL low-level API (server package) > newpki-client : PKI based on the OpenSSL low-level API (client package) >Here is the story : as a journalist for a french magazine, I was asked >to write an article about PKI's. PKI's are systems designed to manage >cetificates on a long term (creation, revocation, etc). The first think >I did was an "apt-cache search pki" and... surprisingly found (almost) >nothing ! >After some investigations on Google, it appeared that, except openCA et >idx-pki, a promising software exists : NewPKI. >Produced by Frederic Giudicelli (french person too), NewPKI is a C++ >client-server software. The server part uses a MySQL database to keep >all certificates, and the client part is a WxWindows GUI used to manage >the server. >As there are my first packages, I've tried my best to make them well. >Instead of running as root, the server part runs as unauthorised user >"newpki", and manual changes to configuration files are kept on >upgrade. >It will need some work to validate and maybe correct the scripts and >comments, but not so much. Frederic Giudicelli is motivated, as I am, >to see his software entering the Debian pools. >This software is GPL v2 licensed. I've supposed it should take place >in section "utils" as OpenSSL is. >Packages are available at > >and the author page is at > > >Description: PKI based on the OpenSSL low-level API (client package) > All the datas are handled through a database, which provides > a much more flexible PKI than with OpenSSL, such as seeking > a certificate with a search engine. > . > There is an SQL abstraction layer, the one provided is for a MySQL database. > . > NewPKI is developed in c++, there are only a few public classes, > which allows to handle any kind of application, a standalone, a PHP module, > or to easily integrate NewPKI in an existing project. > . > Here are the key features of the actual version of NewPKI: > - Handling of multiple CAs in one server. > - Publish a certificate request from CSR. > - Publish a certificate request, by specifying the DN fields. > - Certify a request, specifying the DN Policy and the certificate extension. > - Revoke a certificate. > - Generate the CRL. > - Search for the waiting requests, or the certificates. > - OCSP responder. > - LDAP seek and publication. > >The newpki-client package is lintian clean. The newpki-server report a >warning due to the option "start at boot" which optionnaly update-rc.d >depending on the customer answer. >So I'm looking for a sponsor, please have a look The packages look as if they are Debian native packages. Obviously, there are not. I suggest you to read the policy [0] and developer's reference [1] documents carefully. I couldn't find the corresponding ITP reports for both newpki-server and newpki-client at [2]. See [3] and [4]. Don't forget to include a 'CLoses: #nnnnnn' in the corresponding debian/changelog files to close the ITP reports. Please read [5] if you haven't done so. Why are not the versions 2.0.0-beta3.1 and 2.0.0-beta3 for the client and the server packages, respectively? See [4]. Before you build the packages, the name of the original tarball newpki-client-2.0.0-beta3.1.tar.gz should be changed to newpki-client_2.0.0-beta3.1.orig.tar.gz (note the '_' and the '.orig'). Similarly, the name of the original tarball newpki-server-2.0.0-beta3.tar.gz should be changed to newpki-server_2.0.0-beta3.orig.tar.gz. Renaming the original tarballs, will indicate to dpkg-buildpackage that the packages are not native packages, see [7]. Please read [8] and change your debian/copyright files accordingly. Please read [9] and change the package descriptions accordingly. [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] >Best regards, > >-- >Thomas Dupouy >moz@gmx.fr > >---------------------------------------------------------------------- >GnuPG public key ID : 35293BA8ECA61F4E >GnuPG fingerprint : E71F DAB5 987B CCC9 FF56 38FE 3529 3BA8 ECA6 1F4E >---------------------------------------------------------------------- Anibal Monsalve Salazar -- .''`. Debian GNU/Linux | Building 28C : :' : Free Operating System | Monash University VIC 3800, Australia `. `' | `- |
Attachment:
pgpSw5gsjuLuy.pgp
Description: PGP signature | https://lists.debian.org/debian-mentors/2004/04/msg00305.html | CC-MAIN-2016-40 | refinedweb | 710 | 58.48 |
Statiq Web can locally mirror remote resources such as scripts and stylesheet links.
To enable this feature, set the
MirrorResources setting to
true (like most Statiq Web settings this key is strongly-typed via the
WebKeys class):
using System; using System.Threading.Tasks; using Statiq.App; using Statiq.Web; namespace MySite { public class Program { public static async Task<int> Main(string[] args) => await Bootstrapper .Factory .CreateWeb(args) .AddSetting(WebKeys.MirrorResources, true) .RunAsync(); } }
When resource mirroring is on, all
<script> and
<link> resources will be copied to the local output directory and the HTML elements will be rewritten to point to the local path. This can be especially helpful when combined with HTTP pipelining and HTTP/2 multiplexing. However, it's not appropriate for all cases. Some cases where resource mirroring will not work well include:
- Resources where the content might change.
- Resources that use relative paths to point to other resources.
To disable resource mirroring for a particular resource when the feature is turned on globally, use a
data-no-mirror attribute on the HTML element:
<script src=" data-no-mirror></script> | https://www.statiq.dev/guide/web/content-files/resource-mirroring | CC-MAIN-2022-21 | refinedweb | 182 | 56.25 |
:)
There's a fascinating look at Microsoft's history, year-by-year, on Channel 9. I hadn't looked at these before, but they're relatively short so you can view them whenver you have a break and come back later.
Looking forward to more of these.
I've written about performance tools in the past - it's a topic that interests me quite a bit, because I believe that perceived performance is a very fundamental part of the user experience and can wow you or frustrate you immensely. And I believe "real performance" (so to speak) is very important of course, especially when you don't have a person sitting in front of the computer, but I think every developer will appreciate the difference that a 2' checkin script has vs. a 20' checkin script or a 60' script. 'Nuff said.
In any case, this post about Visual Studio 2010 profiler tools shows some fabulously productive stuff. And all with Visual Studio usability, rather than what it feels like to use some of the more arcane tools (that are admittedly very well suited to automated scenarios, we'll always grant them that).
Anyway, read up and enjoy!
One other twist on the last slicing stylesheet. Let's say that we didn't want to hard-code the number of items in a group, but instead we wanted to be able to control this separately. We can use an xsl:param on the stylesheet to control this externally and provide a default as well.
Here is the touched up stylesheet, with the changes highlighted.
<xsl:stylesheet <xsl:output <xsl:param2</xsl:param> <!--[position() < $itemcount]' /> </xsl:apply-templates> </xsl:template> <!-- Match to root, and put everything under a single element. --> <xsl:template <root> <!-- Grab every second item to create a new group. --> <xsl:apply-templates </root> </xsl:template></xsl:stylesheet>
By the way, if you haven't already, check out the comments on the first post for a more efficient variation of the stylesheet.
I spent a little bit of time with this the other day, and I thought I'd pass the learnings on, in hopes it helps someone.
This is the layout what I was trying to accomplish with WPF. In a section of my window, I wanted a bit of text at the top, and then the rest filled with items. The items in this case were bits of XML with an item template that created a nice representation, but for this post we'll just use buttons, which have the same effect.
My initial XAML looked like this. You can try pasting these into XAMLPad to follow along (and add more buttons or resize the window so all buttons won't fit in the view).
<Grid xmlns=""><StackPanel> <ItemsControl> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <!-- ... --> </ItemsControl></StackPanel></Grid>
This is all well and good, but some of the Buttons are just clipped from the window and you can't get to them. This is because the ItemsControl doesn't have the built-in ability to scroll its contents, so I decided to go ahead an add a wrapping ScrollViewer.
<Grid xmlns=""><StackPanel> <ScrollViewer> <ItemsControl> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <!-- ... --> </ItemsControl> </ScrollViewer></StackPanel></Grid>
This produces a very confusing situation, in which the scroll viewer is present, but the scroll bar is disabled and goes off the window.
After looking at this for a while, I realized that the problem is that the StackPanel doesn't constrain the size of its children. So if the scroll viewer wants to be huge so it doesn't have to, the StackPanel will arrange it so, even if it clips.
The solution then was to switch to something that did constrain its children. In particular, a DockPanel is great, as it will size the last child to occupy all remaining space.
<Grid xmlns=""><DockPanel> <ScrollViewer> <ItemsControl> <Button>Button</Button> <Button>Button</Button> <Button>Button</Button> <!-- ... --> </ItemsControl> </ScrollViewer></DockPanel></Grid>
Now I have a scroll viewer with an enabled scroll bar, which allows me to get to all the buttons.
Aaron published an MSDN article on using Velocity that is very much worth checking out.
Some of the highlights:
One of the things I remember from DevConnections is how ridiculously popular it is to use this from ASP.NET, and how easy it is to improve the performance of your ASP.NET applications with the integrated support.
This is something that I've been asked more than once, and so here goes an answer that might help if you run into this.
Let's say that you create a new project and borrow code or do something of the sort, and suddenly start getting an error message such as this one
xmllite.h(49) : error C2146: syntax error : missing ';' before identifier 'IXmlReader'
This typically points to a missing macro. You can fix this by adding this to your include headers:
#include "objbase.h"
If you're using Visual C++-style projects, this may already be included via stdafx.h including the Windows headers for you.
To continue on my previous example on slicing (I made the term up, by the way), today we'll do something a little different.
Let's say that instead of just inserting the slice elements and a few items, we want to copy the whole tree n times (where n is the number of slices), each time with a different slice of items. That includes elements beyond the things we're currently slicing.
So let's say we have this document, similar to the previous one.
<group groupattribute='1'> <repeat-me>each time</repeat-me> <item item='1'>1 <sub>text</sub> </item> <item item='2'>2 <sub>text</sub> </item> <item item='3'>3 <sub>text</sub> </item> <item item='4'>4 <sub>text</sub> </item> <item item='5'>5 <sub>text</sub> </item></group>
And we want to get this effect.
<root> <group groupattribute="1"> <repeat-me>each time</repeat-me> <item item="1">1 <sub>text</sub></item> <item item="2">2 <sub>text</sub></item> </group> <group groupattribute="1"> <repeat-me>each time</repeat-me> <item item="3">3 <sub>text</sub></item> <item item="4">4 <sub>text</sub></item> </group> <group groupattribute="1"> <repeat-me>each time</repeat-me> <item item="5">5 <sub>text</sub></item> </group></root>
Here is a stylesheet that can accomplish this, using parameters to pass around the replacements nodes for each copy of the tree. As always, variations in the comments are welcome.
<xsl:stylesheet <xsl:output <!--[1]' /> </xsl:apply-templates> </xsl:template> <!-- Match to root, and put everything under a single element. --> <xsl:template <root> <!-- Grab every second item to create a new group. --> <xsl:apply-templates </root> </xsl:template></xsl:stylesheet>
I'm very, very pleased about today's announcement on LINQ to XSD being available on CodePlex.
The functionality available should be esentially the same as what was released in the last Alpha Preview, so if you were already using this, it should be a smooth transition.
The community of developers interested in LINQ to XSD will now be able to include this in their applications, as it's being released under the Ms-PL license.
First, let me start with a disclaimer: I'm not an XSLT guru. I know folks that can truly do amazing things with it. Every now and then, though, I can help someone, and I thought I'd share a solution I came up with recently. I'll be happy to see alternate solutions posted in the comments.
So, let's say you have an XML document such as this one:
<group> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item></group>
You'd like to create "slices" of the items in the group, such that you get them reparented in twos (could be three, four or whatever - we'll go with two items per slice). Any remainder try to fill up as much as possible of the last slice, so the transformed document should look like this.
<group> <slice> <item>1</item> <item>2</item> </slice> <slice> <item>3</item> <item>4</item> </slice> <slice> <item>5</item> </slice></group>
My solution has three templates: one for processing each item (I do some simple content copying "by hand"), one to process each slice (which has a the current context the first item in the slice), and one to process the whole document. The trick is to use the mod function to pick the beginning item of each slice, and to use the following-sibling axis to grab the ones that come right after.
Here's the XSLT for the solution that produces the desired result.
<xsl:stylesheet <xsl:output <!-- Template for a single item in a slice. --> <xsl:template <item><xsl:value-of</item> </xsl:template> <!-- Template for each slice. --> <xsl:template <slice> <xsl:apply-templates <xsl:apply-templates <!-- "grow" the slice by adding more of these, but change the 'mod' below: <xsl:apply-templates --> </slice> </xsl:template> <xsl:template <group> <!-- Grab every second item to create a slice. --> <xsl:apply-templates </group> </xsl:template> </xsl:stylesheet>
One of my popular past entries is Working around invalid characters in XML. I don't know if folks actually search for this, but it's certainly something that I point them to when I want to help them understand the space a bit better.
If you've downloaded the Visual Studio Beta, you'll notice that the .NET Framework beta has a new method in XmlConvert (among a few others): IsXmlChar. This allows you to look at a character and decide whether it's valid or not. Some of the other new methods include checking for valid surrogate pairs or complete strings.
Debugging is hard. There are many things we do to make it easier on ourselves..
Beth Massi shows off how you can use XML literals in VB.NET to do some very, very powerful stuff in a very, very straightforward way.
Following.
Trademarks |
Privacy Statement | http://blogs.msdn.com/marcelolr/default.aspx | crawl-002 | refinedweb | 1,683 | 70.63 |
Good afternoon,
I am trying to split a file name and shorten it. They are .tif files. The code I am using is:
import arcpy
from arcpy import env
env.workspace = "C:\GIS_Projects\VA_1Meter_DEMs\Working_Shapefiles"
in_data = arcpy.ListRasters()
print in_data
for raster in in_data:
part = raster.split("_")
print part
out_data = part[0] + "_" + part[1] + "_" + part[3] + ".tif"
arcpy.Rename_management(in_data, out_data)
I am receiving this error:
Traceback (most recent call last):
File "C:/GIS_Projects/Pyth_Code/RenameDem.py", line 12, in <module>
arcpy.Rename_management(in_data, out_data)
File "C:\Program Files (x86)\ArcGIS\Desktop10.7\ArcPy\arcpy\management.py", line 4524, in Rename
raise e
RuntimeError: Object: Error in executing tool
The code does print out the raster list in the directory, and also prints out the first raster in the list split, so I know that part is working. I am stumped where it is supposed to execute the name change though.
I should have caught this earlier, you are passing the wrong object to Rename. Your current code is passing a list of rasters, not a single raster. The line should read: | https://community.esri.com/thread/257847-using-python-to-split-and-rename-file | CC-MAIN-2020-40 | refinedweb | 185 | 59.09 |
SPAlertCollection.GetUniqueUsers Method
SharePoint 2010
Returns a string array that lists all the users of a site, without listing them more than once, who receive alerts for list items.
Namespace: Microsoft.SharePointNamespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
The following code example shows how to return and display a list of all users who have alerts on a site.
This example requires using directives (Imports in Visual Basic) for the Microsoft.SharePoint and Microsoft.SharePoint.Utilities namespaces.
The example assumes the existence of an .aspx page that contains a label control named Label1.
Show: | https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spalertcollection.getuniqueusers(v=office.14).aspx | CC-MAIN-2016-50 | refinedweb | 106 | 50.73 |
Maven - Frequently Asked Questions
Contents
- 1 What does the pom version mean?
- 2 How is the imagej version determined (<version>${imagej1.version}</version>) ?
- 3 What does this message mean? Property 'imagej.app.directory' unset; Skipping copy-jars
- 4 During run an imagej jar from ~/.m2.... is started, is this only for test/debug? How to use my own imagej?
- 5 My software is dependent from other plugins, such as Particle8_ from Gabriel Landini's Morphology, can/is this incorporated in the imagej maven repository?
- 6 In my ant script I'm using a call to svnversion, in order to place the latest build number and date in the about box. Can this be done with Maven?
- 7 Why isn't my plugin in src-plugins compiled by Build.sh?
- 8 How do I make my modifications to one subproject available to a depending subproject using maven?
- 9 Where can I find more information about Maven?
What does the pom version mean?
The pom.xml of minimal-ij1-plugin inherits from a parent called pom-scijava. This parent POM defines and configures many things so that the POMs of individual plugin projects are shorter (i.e., so they don't have to repeat things).
The version of pom-scijava (1.27 as of this writing) indicates the version of that parent POM. We occasionally improve the parent POM, adding and tweaking it. When we do so, its version increases. I suggest leaving the version that same as what's in minimal-ij1-plugin, since that refers to the latest version. Future 1.x versions will be backwards compatible, so if you later notice that we have updated minimal-ij1-plugin to e.g. 1.43, you can (optionally) update your plugin to that version as well.
The version of minimal-ij1-plugin itself (1.0.0 as of this writing) is the version of your plugin. This string is appended to the JAR file name (e.g., minimal-ij1-plugin-1.0.0.jar), so that you can differentiate between multiple versions of your plugin. Use whatever versioning scheme you want.
However, once you become more comfortable with Maven, I suggest using a SNAPSHOT version during development, and a release (i.e., non-SNAPSHOT) version when distributing your plugin. The reason is to avoid two different JAR files both called my-plugin-1.2.3 but with different contents. (This is part of what Maven calls *build reproducibility*.) Maven will not like it too much if you change the sources of the final 1.0.0 version without advancing the version in the pom.xml file.
How is the imagej version determined (<version>${imagej1.version}</version>) ?
The string ${imagej1.version} is a property that gets replaced with the actual value. This value is defined in the pom-scijava parent configuration. Currently the value is [1.45s,) which means the latest release version you can find equal to or greater than 1.45s.
Browse the latest pom-scijava here.
Browse the available versions of ImageJ 1.x here.
As of this writing, 1.47h is the latest available version, so that's the one Maven will use with your plugin.
If you require an ImageJ 1.x version newer than 1.45s (e.g. due to the use of a method or class that was only introduced in a later version) you probably want to override the setting in your pom.xml file's <properties> section:
<properties> ... <imagej1.version>[1.47b,)</imagej1.version> ... </properties>
What does this message mean? Property 'imagej.app.directory' unset; Skipping copy-jars
This is part of the imagej-maven-plugin (enabled for you by pom-scijava). As you suspected, it copies your plugin's .jar file to your ImageJ plugins folder. But you have to specify where:
mvn -Dimagej.app.directory=/Applications/ImageJ.app
One way to do that in NetBeans is to right-click your project, select Custom>Goals... which brings up the Run Maven dialog box. Then specify install for the Goals and -Dimagej.app.directory=/Applications/ImageJ.app for the Properties.
During run an imagej jar from ~/.m2.... is started, is this only for test/debug? How to use my own imagej?
This is only used to compile your .jar file. If you set the imagej.app.directory property properly, it will actually be copied into the jars/ subdirectory of the location you pointed the property to.
My software is dependent from other plugins, such as Particle8_ from Gabriel Landini's Morphology, can/is this incorporated in the imagej maven repository?
The easiest way to do that would probably to install it locally for the moment. Please see Maven's console log for details how to do that after specifying a dependency, e.g.
<dependency> <groupId>uk.ac.bham.dentistry</groupId> <artifactId>Particles8_</artifactId> <version>1.6</version> </dependency>
It is advisable to look for the version number on the web site, as it was done here, and to construct the groupId from the web site, too.
Note that you will need to wrap the .class files in a .jar file like so:
jar cvf Particles8_.jar Particles8_.class
Then you can install that .jar file locally with a command like:
mvn install:install-file \ -Dfile=/path/to/Particles8_.jar \ -DgroupId=uk.ac.bham.dentistry -DartifactId=Particles8_ -Dversion=1.6 \ -Dpackaging=jar -DgeneratePom=true
In my ant script I'm using a call to svnversion, in order to place the latest build number and date in the about box. Can this be done with Maven?
In general, you can call any needed Ant functionality using the maven-antrun-plugin. However, for your requirement here, you won't need it.
The pom-scijava parent uses the buildnumber-maven-plugin to embed the SCM revision and date in the JAR manifest. You can enable this behavior by adding the following lines to your POM:
<plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>buildnumber-maven-plugin</artifactId> </plugin> </plugins>
Then, your About dialog box can access the information from the .jar file's manifest using the java.util.jar.Manifest class of ImageJ2.
You would need to add a dependency on ij-core like this:
<dependencies> <dependency> <groupId>${imagej.groupId}</groupId> <artifactId>ij-core</artifactId> <version>${imagej.version}</version> </dependency> </dependencies>
and then add code like this:
import imagej.util.Manifest; ... Manifest manifest = Manifest.getManifest(MyBeautifulPlugin.class); String version = manifest.getImplementationBuild();
Why isn't my plugin in src-plugins compiled by Build.sh?
Make sure you have a correctly formatted pom.xml, and that the artifactId for your plugin has been added as a module in the modules section of src-plugins/pom.xml
Make sure that you do not have any circular dependencies. In other words, if your plugin is Plugin_A which depends on Plugin_B, be sure that Plugin_B does not depend on Plugin_A, or any other package that depends on Plugin_A
How do I make my modifications to one subproject available to a depending subproject using maven?
For example, suppose you have made changes to TrakEM2 that you want to take advantage of in a plugin. Compiling with mvn may result in errors indicating that your modifications do not exist. In this case, run "mvn install" in the modules/TrakEM2 directory. This should install the relevant, fresh TrakEM2 jars into the correct locations. | https://imagej.net/index.php?title=Maven_-_Frequently_Asked_Questions&oldid=7162 | CC-MAIN-2019-43 | refinedweb | 1,218 | 52.15 |
Hi, I have alot of confusion with a program I am supposed to write. The GUI App is supposed to take information from the user, that information is: Number of days on trip, amount of airfare, amount of car rental fees, amount of miles driven if only driven in private car, amount of parking fees, amount of taxi charges, conference or seminar registration fees, and lodging charges.
Now the companies reimbursement policy is as follows:
37$ per day for meals
up to 10$ dollars a day for parking fees
up to 20 $ a day for taxi charges
up to 95$ dollars a day for lodging
and .27$ per mile driven.
Now here is what I am supposed to calculate:
Total expenses by the business person
total allowable expenses for the trip(what the company will reimburse for trip depending on how many days it was)
the excess amount that must be paid by business person if there is any
the amount saved by business person if the expenses are under the total amount allowed
The first problems I am having is getting a label on the JTextField components so the user knows where to enter each specified information.
The Second problem I have is actually executing all of the calculations i need to do. My teacher has not gone over any of this in the form of performing the calculations, just the basics on how to set up a basic GUI APP.
Here is what i have so far:
package Travel_Expenses;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Expenses extends JFrame {
private JTextField days;
private JLabel messageLabel;
private JTextField airfare;
private JTextField fees;
private JTextField miles;
private JTextField parkfees;
private JTextField taxi;
private JTextField regfees;
private JTextField lodg;
private JPanel panel;
public static void main(String[] args) {
JFrame frame = new Expenses();
}
public Expenses(){
// call set methods to customize frame
setTitle( "Expenses");
setSize( 400, 200);
setLocation( 500, 300 );
setDefaultCloseOperation(EXIT_ON_CLOSE);
// call buildPanel() method and add panel to frame
buildPanel();
add(panel);
// display the frame
setVisible( true );
}
private void buildPanel() {
// Instantiate panel and GUI Components
panel = new JPanel();
messageLabel=new JLabel("How Many days was the trip");
days = new JTextField(10);
airfare = new JTextField(10);
fees= new JTextField(10);
miles = new JTextField(10);
parkfees = new JTextField(10);
taxi = new JTextField(10);
regfees = new JTextField(10);
lodg = new JTextField(10);
panel.add(messageLabel);
panel.add( days );
panel.add( airfare);
panel.add( fees );
panel.add( miles );
panel.add( parkfees );
panel.add( taxi );
panel.add( regfees );
panel.add( lodg );
}
} | http://www.javaprogrammingforums.com/awt-java-swing/11305-gui-application-problem-help-please.html | CC-MAIN-2014-15 | refinedweb | 419 | 55.17 |
gle.3gle man page
gle — an introduction to the GLE Tubing & Extrusions Library
Synopsis
#include <GL/gle.h>
Description
The).
The library also includes a set of utility routines for drawing some of the more common extruded shapes: a polycylinder, a polycone, a generalized torus (circle swept along a helical path), a "helix" (arbitrary contour swept along a helical path) and a "lathe" (arbitrary contour swept along a helical path, with torsion used to keep the contour aligned).
The most general extrusion supported by this library allows an arbitrary 2D contour to be swept around an arbitrary 3D path. A set of normal vectors can be specified to go along with the contour; the normal vectors determine the appearance of the contour when lighting is turned on. A set of colors and affine matrices can be specified to go along with the 3D path. The colors are used to color along the path. The affine matrices are used to operate on the contour as it is swept along. If no affine matrices are specified, the contour is extruded using the mathematical concept of "parallel translation" or "Gaussian translation". That is, the contour is moved (and drawn) along the extrusion path in a "straight" manner. If there are affine matrices, they are applied to the contour at each extrusion segment before the segment is drawn.
The affine matrices allow work in a quasi translation allows the appearance of shearing in real space; that is, taking a contour and displacing it, without otherwise bending it. Note that the affines are 2x3 matrices, not 3x4 matrices, since they apply to the 2D contour as it is being extruded.
Web Site
See Also
Author
Linas Vepstas (linas@linas.org) | https://www.mankier.com/3/gle.3gle | CC-MAIN-2018-09 | refinedweb | 285 | 59.64 |
Issue Type: New Feature Created: 2012-03-20T00:03:49.000+0000 Last Updated: 2012-03-22T00:19:48.000+0000 Status: Open Fix version(s): Reporter: Bruno Thiago Leite Agutoli (btlagutoli) Assignee: Thomas Weidner (thomas) Tags: -
Related issues: Attachments:
Hello, recently I made a filter called "CharConverter" doing a job of converting special characters to another similar character.
Below is an example of implementation;
h3. Examples
<pre class="highlight"> $filter1 = new Zag_Filter_CharConvert(array( 'replaceWhiteSpace' => '-', 'locale' => 'en_US', 'charset'=> 'UTF-8' )); echo $filter1->filter('ééé ááá 90');//eee-aaa-90 echo $filter1->filter('óóó 10aáééé');//ooo-10aaeee <pre class="highlight"> $filter2 = new Zag_Filter_CharConvert('UTF-8', 'en_US', '-'); echo $filter2->filter('éééé ááááá 90');//eeee-aaaaa-90 <pre class="highlight"> $filter3 = new Zag_Filter_CharConvert(); echo $filter3->filter('éééé ááááá 90');//eeee aaaaa 90
With this filter is very easy to convert text into friendly url for example.
well, that's it, I do not know if this is in accordance with the Zend but if you would like to help in the development.
Note: The plugin was not implemented with namespaces (Zend\Filter), they still did it to version 1.11.10, but I can adapt easily to the ZF2
thanks!
Posted by Frank Brückner (frosch) on 2012-03-20T08:35:36.000+0000
Code tags added.
Posted by Frank Brückner (frosch) on 2012-03-20T08:38:55.000+0000
Hi Bruno, nice idea! :-)
Posted by Bruno Thiago Leite Agutoli (btlagutoli) on 2012-03-22T00:19:48.000+0000
Hi, I climbed up the project in "github"… | https://framework.zend.com/issues/browse/ZF-12107 | CC-MAIN-2017-22 | refinedweb | 253 | 57.37 |
With such a long and promising title, this series of posts better be a good one – you’ll be the judge of it. However, the real reason for this long title is rather simple. All these “big” words simply represent different aspects of the execution model. There are a few things that you need to know if you want to maximize your user’s experience. This post explains the Windows Phone (WP) application execution model by taking you step-by-step through the different aspects of launching, running, and closing a Silverlight application. Note that for XNA games the terms and ideas remain the same with some minor implementation differences. In following posts we’ll cover deactivation, reactivation, and how launchers and choosers work with tombstoning.
With the latest Beta release of the Windows Phone developer tools, applications running on WP employ an updated execution model. Now, when your application is removed from the phone foreground (a different application occupies the phone foreground like incoming phone call, or the lock screen being activated), it is actually being terminated (more on this later). In earlier version of the WP tools, you could get into all kinds of strange scenarios if you went from one application to another. That is because in the previous version of the tools, the WP operating system didn’t terminate your application, it “parked” it. However that led to some issues regarding launching a new instance of your application vs. navigating back to the instance on the back stack. Adding to the confusion, the events and API were less than perfect. I guess that is one of the reasons we have technical previews—to test and fix such “issues.”
A Few Ground Rules
Just to make sure we are all on the same page, by now you probably already know that the WP operating system doesn’t allow any 3rd party applications to run in the background. To be more specific, there can be only one application running in the foreground at any given time, and if your application is not running in the foreground, it means that your application is NOT RUNNING. The main reasons for not allowing 3rd party applications to run in the background are to preserve battery life (see Push Notification post) and to ensure a responsive and consistent user experience.
All WP devices feature a hardware Back button. This button allows the user to navigate back in a given application and even between applications. This is a rather cool feature, mainly because unlike other phones, you can navigate from your application to the browser or to another application, and then press Back to seamlessly return to your application. This yields a much more consistent user experience across different applications, whether they are 3rd party applications or part of the phone’s built-in application suite. This also implies that WP operating system is maintaining a journal of you navigation actions to support the Back button functionality. This is also known as the back-stack.
The Basics – Launching, Running, and Closing Applications
It is time to jump into the Windows Phone execution model, and the best way to do this is to start looking at some code. Simply start a new Windows Phone application and look at the auto-generated code of a new WP Silverlight application template, and you will find four new methods in the App.xaml.cs file that are directly related to the execution model:
- Application_Launching
- Application_Activated
- Application_Deactivated
- Application_Closing
As a side note, all these events (the functions are the event handlers) are members of the PhoneApplicationService class in the Microsoft.Phone.Shell namespace.
I think the names of these methods are rather self-explanatory, but just to be on the safe side, let’s review them. We’ll address the Activated and Deactivated methods later; for now, let’s focus on the simple events: Launching and Closing. I’ve added a single line of code to each method:
// Step 1 - Util is helper class for loggingUtil.Trace("***** in MainPage CTORtt ( " + DateTime.Now.Ticks + " *****)");
Util is a simple helper class that we’ll use to help us with debugging. The text in each method changes according to the event but you get the idea. I log the time of each event in order to prove a point later when we talk about Activated and Deactivated events.
Running the application in its current state yields the expected result. Upon launching your application the “Launching” method is called. As expected, after that event, your application runs. Press the Back button (not the Windows button) and your application terminates and the “Closing” event is raised, as you can see in the following image (copy of the output window from Visual Studio).
As we said, by pressing the hardware Back button, the navigation model allows the user to “step back,” or navigate backwards through the application pages, and even across applications. However once you reach to the application’s first page (the first page, and its first instance) pressing the Back button raises the Closing event and terminates your application. You can see that from the above image, where it clearly states that the “program” exited. If you are following this post while coding in Visual Studio you will also note that the emulator exits your application and returns to the Start window.
Understanding Activated and Deactivated Events and Tombstone
So far so good, I mean there is nothing new here. However, let’s try the following trick. From Visual Studio, start your application in debug mode (so we can see the traces). As expected, your application starts and you should see the Application Launching trace in the log. Now, instead of pressing the Back button (which if you do, will terminate your application), press the Windows button (the middle button).
You should notice the following:
- The emulator returned to the Start screen and your application doesn’t occupy the phone’s foreground, which means it is no longer running!
- The debugging session in Visual Studio was terminated. This means that Visual Studio is not debugging your application, which makes sense since the application is no longer running.
Note: At the end, your application gets terminated. That is super easy to see in the Visual Studio Output window, as the last line in the Output windows states, “The program ‘[220921918] taskhost.exe: Managed’ has exited with code 0 (0x0).” No worries, this is by design. However, unlike our previous example, this time the event that followed the Launching event is “Deactivated,” and NOT Closing. But in both cases your application gets terminated (at the end). So what is going here? What is the difference between Closing and Deactivated and more important, why?
- Application Closing is simply the outcome of the user pressing the hardware Back button enough times to navigate backwards through the pages of your application, past the application’s first page. Currently, this is the ONLY way for a user to exit your application. Once your application is closed, its process is terminated, and the operating system removes any trace of that application from its memory (RAM).
- Application Deactivated occurs when a different application takes control of the foreground – for example, an incoming phone call, launching a chooser, or the user pressing the Windows button. In both cases, your application will be deactivated (not closed). Before we step into the subtleties of the Deactivated event, let’s make sure we all understand that upon Deactivation, your application gets terminated (at the end). It’s that simple; your code can’t run in the background, therefore your application gets terminated. However, unlike an application that is closed, a deactivated application gets tombstoned. Don’t get confused, a tombstoned application’s process still gets terminated. But unlike a closed application, where the WP operating system removes any trace of the application, when an application is deactivated, the WP operating system stores a record (a tombstone) of the application’s state. Basically, the WP operating system keeps a tombstone of the application that becomes part of the phone’s application back-stack, which is a journal that enables the use of the hardware Back button to enhance navigation functionality.
There are several ways in which applications can become tombstoned. An application will be tombstoned and deactivated if:
- The user presses the Windows button (as you just did)
- The device timeout causes the lock screen to be engaged (again, a different application takes control of the foreground)
- The user invokes a Launcher or a Chooser – which we will cover later
In any of these cases, the running application will be deactivated, the Deactivated event is raised, and your application gets terminated shortly afterwards.
At this point in the application life cycle (while your application is tombstoned), a few things can happen. The user might return to a tombstoned application. This can happen if the user completes the chooser or launcher activity and returns to the application, or if the user presses the Back button enough times to return to the tombstoned application. Regardless of how users return to the tombstone application, the application will be reactivated (raising the Activated event) and magically show the last page viewed by the user before the deactivation.
You don’t believe me, let’s try it together. I’ve added a second page to the basic WP Silverlight application, and added a trace to both constructor pages. Next, I added a button to the first page that navigates to the second page.
In Visual Studio, start debugging your application and click the button to navigate to the second page. From the second page, press the Windows button. As expected, your application is deactivated and then terminated, as you can see from the following screen capture of the Visual Studio Output window.
Note the sequence of the trace (and the corresponding time-code). First your application launches, then the main page constructor is called, and after pressing the button on page one, the application navigates to the second page (DetailsPage), after which you press the Windows button raising the Deactivated event, which indicates that your application is tombstoned.
In the next post you’ll learn about returning to a tombstoned application and managing your state between tombstoning.
You can download the code for the code samples.
Windows Phone 7 Training Kit for Developers includes a full lab dedicated to the Windows Phone Application Lifecycle.
MSDN documentation includes a topic – Execution Model Overview for Windows Phone
Blog edited by Barbara E. Alban
Join the conversation | http://blogs.windows.com/buildingapps/2010/07/15/understanding-the-windows-phone-application-execution-model-tombstoning-launcher-and-choosers-and-few-more-things-that-are-on-the-way-part-1/ | CC-MAIN-2015-18 | refinedweb | 1,754 | 51.78 |
In ne2000_receive(), we try to assign size_ to size which converts from size_t to integer. This will cause troubles when size_ is greater INT_MAX, this will lead a negative value in size and it can then pass the check of size < MIN_BUF_SIZE which may lead out of bound access of for both buf and buf1. Fixing by converting the type of size to size_t. CC: address@hidden Reported-by: Daniel Shapira <address@hidden> Signed-off-by: Jason Wang <address@hidden> --- hw/net/ne2000.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hw/net/ne2000.c b/hw/net/ne2000.c index 07d79e317f..869518ee06 100644 --- a/hw/net/ne2000.c +++ b/hw/net/ne2000.c @@ -174,7 +174,7 @@ static int ne2000_buffer_full(NE2000State *s) ssize_t ne2000_receive(NetClientState *nc, const uint8_t *buf, size_t size_) { NE2000State *s = qemu_get_nic_opaque(nc); - int size = size_; + size_t size = size_; uint8_t *p; unsigned int total_len, next, avail, len, index, mcast_idx; uint8_t buf1[60]; @@ -182,7 +182,7 @@ ssize_t ne2000_receive(NetClientState *nc, const uint8_t *buf, size_t size_) { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; #if defined(DEBUG_NE2000) - printf("NE2000: received len=%d\n", size); + printf("NE2000: received len=%zu\n", size); #endif if (s->cmd & E8390_STOP || ne2000_buffer_full(s)) -- 2.17.1 | https://lists.gnu.org/archive/html/qemu-devel/2018-09/msg02993.html | CC-MAIN-2021-43 | refinedweb | 205 | 68.2 |
51649/command-to-copy-file-from-desktop-to-hdfs
You can use either of the below commands to copy files from your local to hdfs,
hadoop fs -put /path/in/linux /hdfs/path
or
hadoop fs -copyFromLocal /path/in/linux /hdfs/path
The distributed copy command, distcp, is a ...READ MORE
There are two possible ways to copy ...READ MORE
Please refer to the below code:
import org.apache.hadoop.conf.Configuration
import ...READ MORE
Hi@akhtar,
You can copy files from your local ...READ MORE
du command is used for to see ...READ MORE
Hadoop put & appendToFile only reads standard ...READ MORE
You can use dfsadmin which runs a ...READ MORE
hdfs dfsadmin -report
This command tells fs ...READ MORE
Just use the FileSystem's copyFromLocalFile method. If the source Path ...READ MORE
hadoop fs -cat /example2/doc1 | wc -l
READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/51649/command-to-copy-file-from-desktop-to-hdfs | CC-MAIN-2022-21 | refinedweb | 167 | 66.64 |
Talk:Wiki userboxes
Contents
Delete. Use category instead
This page has doesn't serve any purpose a category of userboxes couldn't, and the category would be easier to maintain. Also, non-OSM related content like this shouldn't be in the main namespace. I've proposed deletion, and if no-one objects I'll label for deletion in a week. Jonathan Bennett 23:47, 24 November 2011 (UTC)
- you can specify the category of the article. after all, somewhere must be articles describing the construction and design of the wiki. no need to remove--dr&mx 10:44, 26 November 2011 (UTC)
- I find this page helpfull, the wiki is a good middle for communication too. So I can find this information here. No need to remove. --WhitePlume 13:33, 28 November 2012 (UTC)
- The purpose it does serve, over and above Category:Userbox, is to be able visually see all the different Userboxes available, and what their icon looks like. The page could be improved to make it more useful. See following suggestions -- Harry Wood (talk)
- Ok done all the suggestions, so hopefully the page appears more purposeful now. -- Harry Wood (talk) 23:15, 15 June 2016 (UTC)
Move from 'Userboxes'
It might make sense to rename this page from 'Userboxes' to 'Wiki userboxes', to make it clearer that it's a wiki thing rather than something else related to OpenStreetMap users. -- Harry Wood (talk) 13:05, 17 November 2015 (UTC)
- Just DONE the move -- Harry Wood (talk) 23:15, 15 June 2016 (UTC)
Split into sections
This page could be split into sections with headings. Maybe "Countries", "Software preferences", "Hobbies and interests", "Languages", "Other". -- Harry Wood (talk) 12:57, 17 November 2015 (UTC)
- DONE
- Some of the headings might need adjusting. e.g. I made a heading called "Other software" but it only has one userbox in there (so far)
- -- Harry Wood (talk) 23:15, 15 June 2016 (UTC)
Template name and linkify
There's column on the left giving a name to each userbox, but it would be clearer and more useful if it just repeated the actual name of the wiki template, and linked to it. In some cases they match, but in others not I notice. -- Harry Wood (talk) 12:57, 17 November 2015 (UTC)
- In my opinion all your proposed changes are good.--Jojo4u (talk) 17:53, 17 November 2015 (UTC)
- DONE - Column on the left now links to templates. It might be adjusted to be even better by giving a syntax example, while at the same time being a link. But linking is the main thing actually because each userbox template would ideally have template documentation which gives a syntax example. -- Harry Wood (talk) 23:15, 15 June 2016 (UTC) | http://wiki.openstreetmap.org/wiki/Talk:Wiki_userboxes | CC-MAIN-2017-04 | refinedweb | 458 | 60.85 |
. Only first row is exported, help to export all the
View Tutorial By: Achyut at 2014-12-18 04:26:26
2. How can i download the comm.API .
pls tel
View Tutorial By: Sajeer kc at 2015-01-16 04:12:28
3. Pl provide me code to send sms using USB modems.
View Tutorial By: Prayag Singh at 2010-09-27 22:50:34
4. You have stretch it more then enough even then the
View Tutorial By: Chirag at 2012-12-04 16:15:13
5. for the guys who is facing problems
just c
View Tutorial By: Elie at 2010-05-03 12:12:48
6. How can you print this using recursion?
View Tutorial By: Menon at 2011-09-08 07:16:02
7. Please don't use DataInputStream to read text. Unf
View Tutorial By: Peter Lawrey at 2013-01-30 23:46:47
8. public class Overload2 {
View Tutorial By: ITMIT at 2011-06-05 19:16:46
9. Hi, You can use a javascript array. Which means wh
View Tutorial By: Mashoud at 2008-05-04 02:54:38
10. I need a sample jsp(using Struts html tags) in thr
View Tutorial By: Anil Kumar at 2008-10-23 04:14:51 | https://java-samples.com/showcomment.php?commentid=39452 | CC-MAIN-2019-43 | refinedweb | 211 | 85.49 |
Chapter 4. Introducing Python Object Types
This chapter begins our tour of the Python language. In an informal sense, in Python, we do things with stuff. ,.
Why Use Built-in Types? still.
Python’s Core Data Types
Table 4-1 previews Python’s built-in object types and some of the syntax used to code their literals—that is, the expressions that generate these objects.[11] Some of these types will probably seem familiar if you’ve used other languages; for instance, numbers and strings represent numeric and textual values, respectively, and files provide an interface for processing files stored on your modules, and they have behavior all their own.
We call the object types in Table 4-1 core data types because they are effectively built into the Python language—that is, there is specific syntax for generating most of them. For instance, when you run the following code:
>>>>>>
'spam'
you are, technically speaking, running a literal expression, which.
Besides expressions, there are a handful of useful numeric modules that ship with Python:
>>>>>>
import math>>>
math.pi3])1.
Strings>>
len(S)# Length 4 >>> 'm' >>>
S[-2]# The second to last item from the end 'a'
Formally, a negative index is simply added to the string’s size,Spam' >>>-Specific
−1 if it
is not present), and the string
replace method performs global searches and
replacements:
>>>>>>
S.find('pa')# Find the offset of a substring 1 >>>
S'Spam' >>>
S.replace('pa', 'XYZ')# Replace occurrences of a substring with another 'SXYZm' >>>
S'Spam' = line.rstrip( )# Remove whitespace characters on the right side >>>
line'aaa implementation generally
better to ask about a specific method, as we did above.
For more details, you can also consult Python’s standard library
reference manual, or commercially published reference books, but
dir and
help are the first line of documentation in
Python. = 'A\nB\tC'# \n is end-of-line, \t is tab >>>
len(S)# Each stands for just one character 5 >>>
ord('\n')# \n is a byte with the binary value 10 in ASCII 10 >>>
S = 'A\0B\0C'# \0, the binary zero byte, does not terminate the string >>>'
Python also supports a “raw” string literal that turns off the backslash escape mechanism . position 123 >>>
L[:-1]# Slicing a list returns a new list [123, 'spam'] >>>
L + [4, 5, 6]# Concatenation makes a new list too [123, 'spam', 1.23, 4, 5, 6] >>>
L# We're not changing the original list [123, 'spam', 1.23]
Type-Specific × 6
The first operation here fetches the entire second row, and the second grabs the third item within that row—stringing together index operations takes us deeper and deeper into our nested-object structure.[12]
List Comprehensions can be used to iterate over any iterable object—here, for instance,
we’ll'].
Dictionaries: they may be changed in-place, and can grow and shrink on demand, like lists.
Mapping Operations{'food': 'Spam', 'color': 'pink', 'quantity'::
>>>>>>.
Nesting Revisited'}, 'job': ['dev', 'mgr'], 'age':'}}
Notice how the last operation here expands the nested job list—because the job.[13]:
>>>>>>:
>>>>>>
Ks = D.keys( )# Unordered keys list >>>
Ks['a', 'c', 'b'] >>>
Ks.sort( )# Sorted keys list >>>
Ks['a', 'b', 'c'] >>>
for key in Ks:# Iterate though sorted keys
print key, '=>',{'a': 1, 'c': 3, 'b': 2} >>>
for key in sorted(D):
print key, '=>', D[key]a => 1 b => 2 c => 3
This case serves as an excuse 'spam': and the
profile module. You’ll find more on these
later in this book, and in the Python manuals.
Missing Keys: if Tests
One other note about dictionaries before we move on. Although we can assign to a new key to expand a dictionary, fetching a nonexistent key is still a mistake:
>>>>>>
D{'a': 1, 'c': 3, 'b': 2} >>>
D['e'] = 99# Assigning new keys grows dictionaries >>>
D{'a': 1, 'c': 3, 'b': 2, 'e': 99} >>>
D['f']# Referencing one('f')False >>>
if not D.has_key('f'): print 'missing: 'tuple'
'w' processing mode string to write
data:
>>>>>>
f = open('data.txt', 'w')# Make a new file in output mode >>>
f.write('Hello\n')# Write strings of bytes to it >>>
f.write('world\n')>>>('data.txt')# 'r' is the default processing mode >>>
bytes = f.read( )# Read entire file into a string >>>
bytes'Hello\nworld\n' >>>
print bytes# Print interprets control characters Hello world >>>
bytes.split( )# File content is always a string ['Hello', 'world'] methods later in this book, but if you want a quick
preview now, run a
dir call on the word
file (the name of the file data type),
and a
help on any of the names that
come back:
>>>>>>
dir('spam')>>>
Y = set(['h', 'a', 'm'])# Make 2 sets out of sequences >>>
X, Y(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm'])) >>>
X & Y# Intersection set(['a', 'm']) >>>
X | Y# Union set(['a', 'p', 's', 'h', 'm']) >>>
X - Y# Difference set(['p', 's'])
In addition, Python recently added decimal numbers (fixed-precision
floating-point numbers) and Booleans (with predefined
True and
False objects that are essentially just the
integers 1 and 0 with custom display logic), and it has long supported a
special placeholder object called
None:
>>>>>>
import decimal# Decimals >>>
d = decimal.Decimal('3.141')>>>
d + 1Decimal("4.141") >>>
1 > 2, 1 < 2# Booleans (False, True) >>>
bool('spam')True >>>
X = None# None placeholder >>>
print XNone >>>
L = [None] * 100# Initialize a list of 100 Nones >>>
L[None, None, None, None, None, None, None, None, None, None, None, None, None,
...a list of 100 Nones...] >>>
type(L)# Types <type 'list'> >>>
type(type(L))# Even types are objects <type 'type'>-Defined('Bob Smith', 50000)# Make two instances >>>
sue = Worker('Sue Jones', 60000)# Each has name and pay >>>.
[11] *).
[12] *.
[13] * One footnote here: keep in mind
that the
rec record we just
created really could be a database record, when we employ Python’s
object persistence system—an easy way to store
native Python objects in files or access-by-key databases. We won’t
go into more details here; see Python’s
pickle and
shelve modules for more details.
Get Learning Python, 3rd Edition now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers. | https://www.oreilly.com/library/view/learning-python-3rd/9780596513986/ch04.html | CC-MAIN-2020-29 | refinedweb | 1,031 | 57.1 |
SSL mutual authentication in Talend ESB
To beef up security, some web services may require you to use SSL mutual authentication.
This article shows you how to set up mutual (2-way) SSL when invoking a REST web service from a Talend Route, using self-signed certificates.
What is mutual authentication?
Mutual authentication, also known as 2-way SSL, is when a client and server both authenticate themselves to each other.
This method is often used when a server wants to assure the client’s identity. This is especially useful in web services, when a server may want to make a web service available to trusted clients only.
2-way SSL is achieved using certificates on both sides. In a traditional SSL exchange, only the server presents a certificate. But in 2-way SSL, both client and server present their certificates to each other.
This gives rise to a sequence of events like this:
- A client sends a request to a server.
- The server identifies itself to the client by sending its certificate.
- The client receives the server’s certificate and verifies it.
- The client identifies itself to the server by sending its certificate.
- The server receives the client’s certificate and verifies it.
- If all steps are successful, the server grants access.
In this article, you will use Java’s keytool utility to generate your private key and send it to your external partner for signing. You’ll add the signed certificate into a keystore and configure the Talend Route to use this certificate when invoking a web service.
SSL mutual authentication setup
This part of the process is not unique to Talend, but for completeness I’ve included it in this tutorial.
Step 1: Generating a certificate and getting it signed
First, generate a private key. You use this to generate a certificate signing request, which you send to the other party. The other party signs this request and returns a file back to you.
Follow these steps to generate a private key and certificate signing request:
Check you have openSSL installed:
- Mac users: openSSL is already installed. You can access it from Terminal.
- Windows users: I recommend Cygwin, the Linux environment for Windows. Or you can use an openSSL build for Windows.
Drop to a Terminal, Cygwin or command line.
Generate a private key and certificate signing request using
openssl req -newkey rsa:2048 -keyout mykey.key -out mykey.req
You will be prompted for various properties, such as location, key name, etc.
When prompted, enter a PEM pass phrase. You must remember this as you will need it below.
Ignore the option to supply a challenge password or company name.
Send only the generated
mykey.reqfile to the other party to be signed. Do not send the private key (
mykey.key) file.
The other party should sign using their certificate and return a
.pem file. This is your signed certificate file.
Step 2: Add your private key and signed certificate into a new local keystore
Now you need to add your private key and the signed certificate into a local keystore so that Java can use it. You should keep this file in a secure location where few people can access it. Usually this is in
JAVA_HOME/jre/lib/security.
To add your key and certificate to a new local keystore:
Ensure you have the private key (
.key) file you generated, and the matching certificate (
.pem) signed by the other party.
Drop to a Terminal, Cygwin or command line.
Create a bundle file containing both your key and certificate – from this you will create your keystore:
openssl pkcs12 -export -in mykey.pem -inkey mykey.key -certfile mykey.pem -name "mykey" -out mykeystore.p12
You will be prompted for a pass phrase for the private key (this is the PEM passphrase you chose earlier).
You will be prompted for an export password. Remember the password; you will need it below when importing the keystore.
When openssl has finished, it will create your new bundle file,
mykeystore.p12.
Copy the new bundle file to
$JAVA_HOME/jre/lib/security.
Use Java’s keytool (it’s in
$JAVA_HOME/bin) to create a keystore using the bundle file just created. From your
$JAVA_HOME/jre/lib/securityfolder:
../../bin/keytool -importkeystore -srckeystore mykeystore.p12 -srcstoretype pkcs12 -destkeystore client-keystore.jks -deststoretype JKS
When prompted, give a destination password. Choose a secure password, as it gives access to your private key!
When prompted, give the source password that you chose in step 5, above.
When openssl has finished, you can verify that the private key is added using:
../../bin/keytool -list -v keystore client-keystore.jks
Enter your password when prompted. This will print all items in your keystore – both your private key and certificate.
Step 3: Add the remote CA to your trust store
You now need to add the other party’s root certificate to your trust store. This tells Java to trust the certificate, and any others signed by it.
Ensure you have the root certificate (
.pem) supplied by the other party.
Use Java’s keytool to add the root certificate to the trust store
../../bin/keytool -importcert -keystore client-truststore.jks -file otherparty.pem
When prompted, choose a password for the trust store.
When prompted whether to trust the certificate, answer yes.
Configuring the Route
From this point, configuring the Talend Route to use 2-way SSL is fairly straightforward.
SSL configuration is done by using a bean of a certain class,
SSLContextParameters. You instantiate a bean, use its setter methods to add your SSL parameters, and then pass this bean to an HTTP component. This approach is documented on Camel’s configuration utilities page.
In this tutorial I use the HTTP4 component to invoke a REST service. It’s not available as a drag-and-drop component out of the box in Talend Studio, but it’s easy to set up using a cMessagingEndpoint.
Step 4: Add SSL configuration into your Talend Route (Camel)
The configuration bean,
SSLContextParameters, needs to be created and registered in the camel context. The HTTP4 component uses this bean to determine what SSL configuration to use when making the connection to the web service.
- Add 5 context variables to the Route and configure for each environment:
- keyStorePath (e.g.
C:/Program Files/Java/jdk1.7.0_51/jre/lib/security/client-keystore.jks)
- keyStorePassword (e.g.
changeit)
- keyPassword (e.g.
changeit)
- trustStorePath (e.g.
C:/Program Files/Java/jdk1.7.0_51/jre/lib/security/client-truststore.jks)
- trustStorePassword (e.g.
changeit)
- Add a cBeanRegister component with the following details:
- Id:
"sslContextParameters"
- Select the Customised option, then:
Add the following class imports:
import org.apache.camel.util.jsse.SSLContextParameters; import org.apache.camel.util.jsse.KeyStoreParameters; import org.apache.camel.util.jsse.KeyManagersParameters; import org.apache.camel.util.jsse.TrustManagersParameters;
Add the following code:
KeyStoreParameters kspKeys = new KeyStoreParameters(); kspKeys.setResource(context.keyStorePath); kspKeys.setPassword(context.keyStorePassword); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(kspKeys); kmp.setKeyPassword(context.keyPassword); KeyStoreParameters kspTrust = new KeyStoreParameters(); kspTrust.setResource(context.trustStorePath); kspTrust.setPassword(context.trustStorePassword); TrustManagersParameters tmp = new TrustManagersParameters(); tmp.setKeyStore(kspTrust); beanInstance = new SSLContextParameters(); ((SSLContextParameters) beanInstance).setKeyManagers(kmp); ((SSLContextParameters) beanInstance).setTrustManagers(tmp);
Step 5: Invoke the remote web service
To invoke the web service, I use the camel-http4 component (based on Apache HttpClient 4.x). It’s not included as a standard drag-and-drop component, so you have to use a cMessagingEndpoint to add it. It’s a little bit easier to configure for SSL than the standard cHttp (which is based on HttpClient 3.x):
- Add a cSetHeader component to the Route. Set the following properties:
- Name:
org.apache.camel.Exchange.CONTENT_TYPE
- Language: Constant
- Value:
"text/xml"
- Wire the cSetHeader to a cMessagingEndpoint component. Set the following properties:
- URI:
"https4://HOSTNAME:PORT/path/to/service?sslContextParametersRef=sslContextParameters"
- On the Advanced settings tab, add a dependency for http4.
When finished, your Route should look something like the diagram below. Note that I’ve added the following extra components:
- a cTimer, to start the route for testing purposes
- a cSetBody, so I can set a test payload to invoke the web service with
- a cLog, so that I can log the response from the web service
Pro tip: To aid debugging or troubleshooting, add the following JVM startup parameter (from the Run window) to see SSL debug output in the Console:
-Djavax.net.debug=ssl:handshake
If you’re accessing web services from behind a proxy, you should add the following to the end of your URI:
&proxyAuthHost=PROXY_HOST&proxyAuthPort=PROXY_PORT&proxyAuthScheme=http4
What do you think? You can use Markdown in your comment.
To write code, indent each line with 4 spaces. Or, to paste a lot of code, you can put it in pastebin.com and share the link in your comment. | https://tomd.xyz/talend-rest-mutual-ssl/ | CC-MAIN-2022-40 | refinedweb | 1,464 | 51.04 |
sir,
I need a program for "accepting the voice from user and comparision of voice" in java
Sir, How to find the prime number at 10001st position.
Java is my interested program to learn now.pls put and carry me along.
i want to learn java.......
i want to learn swing....plz discussed with me.....reply me
java interview questions
i want creat gui application by java coreso i need coding nand notes regarding it
plz help me
thanks alot
how to make a program in binary like any to any...
how to access strings in java programs
i want to learn the tutorial.
please give the information with the example
I am Now Studying java language so give important notes of java.
thanks...
Post your Comment
Master java in a week
;
Class Declaration:
Class is the building block in Java...;
The main method is the entry point in the Java program
and java program can't run... is always first thing that is executed in a java program.
Here is the main method
Week calculate start from friday
in May. 1st may is Saturday, it can not be considered the 1srt week of may, because the week starts on Friday.
Can anyone help me,...PLEASE? (Java...Week calculate start from friday My problem is to calculate how many
Find the Day of the Week
Find the Day of the Week
... of a week from calendar.
The Calendar class is an abstract base class
that extends... time zone, locale
and current time.
The fields used:
DAY_OF_WEEK
Get first day of week
; week in Java. As we know that GregorianCalendar provides the
current date, month..._package>java FirstDayOfWeek
Day of week: 7
Sunday...
Get first day of week
Master Java In A Week
Master Java In A Week
Master Java Programming Language in a week. This tutorial is good for
beginners in Java and it will teach you the basics... for making you perfect in Java
programming language in a week
Tutorial of the week
Tutorial of the week
Welcome to our Tutorials of the week section. We... the mapping xml file(hbm.xml)
for the week of Feb 1, 20010
In this tutorial we... of hibernate mapping xml files (.hbm.xml)
Ajax Tutorial
for the week of Jan
MySQL By Week
MySQL By Week
In this section, you will learn about the MySQL By Week. If you want to get some weekly reports of the table data you will use the sql
week() function.
Week
Change Week Days Format
Change Week Days Format
This Example shows you how to change week days format. In the code given below we are change week days
format.
Methods used
Week Days Format Example
Week Days Format Example
This example shows how to format week days using Format class. In this program we use a pattern of special characters to format week day
PHP convert week number to days or month - PHP
PHP convert week number to days or month Small, simple and easy code that can do following task:
1.Convert Week Numbers to Month
2.Convert Week to Date
Generally, we use the date time object in PHP to convert the date
PHP Date add 1 week
The PHP Date add 1 week example code. In the the following example code we will show you how to add one week to any date object in the PHP program.
<?php
//Example to add 1 week to a date object
$currentDate = date
Find Day of Month
; finds the day of a month and the day of a
week by using get(field_name) method... used:
WEEK_OF_MONTH: This field is used to get and set the week indicating the week number within the current month.
DAY_OF_WEEK:
This field gets and set
Determining the Day-of-Week for a Particular Date
Determining the Day-of-Week for a Particular Date
... in word i.e.
the Day of Week for a particular date. Here,
you can learn about the way.... This program gets the day of the week using Calendar.DAY_OF_WEEK
i.e.
Butterfly Week Tour of Kerala
Butterfly Week Tour of Kerala
Destinations Covered: Cochin-Thattekkad-Munnar... Tour
On the beginning of your butterfly week tour you will land at the Kochi...
During your Butterfly Week Tour, you will be taken to a trip to Chinnar
Kerala
how can i display the dates of one week by selecting the date randomly from the calendar?
how can i display the dates of one week by selecting the date randomly from the calendar? I am facing a problem in my application,Here i should display the calendar, simultaneously i want to display the list of seven dates from
SWT
of week. The class GridLayout
provides the configuration of GridData... the day and the days of week.
SWT TextEditor... the temperature.
Rotate Text in Java
java
java write a program in java to print day of a week with with respect to its number .for the illustration,if you give a number 4, it will print"wednesday" in this program,switch-case statement is expected to use
java
java write a java program in to create a class Worker and derive... the week pay of every worker. a Daily worker ia paid on the basis of the number of days s/he works. the salaried worker gets paid the wage for 40 hours a week
Sql Date and Time Functions
;
The Tutorial illustrate a function to
extract the day of week, name of month, name of day, day of year, number of
week.
Understand with Example...'.
Query (DAYOFWEEK) :-Here is the
query for extracting the day of week
Open Source Router
this week, with the goal of becoming the networking equivalent of Linux or Firefox... Java applet that let's students peer inside a modular graphical router and see how
java program22
java program22 Write a java program to display day of week like monday,tuesday etc. using JAVA calendar class
import java.util....[cal.get(Calendar.DAY_OF_WEEK) - 1];
System.out.println("Today is: " + today
java - Java Beginners
);
int weekday=d.get(Calendar.DAY_OF_WEEK);
int FirstDayOfWeek...++;
d.add(Calendar.DAY_OF_MONTH,-1);
weekday=d.get(Calendar.DAY_OF_WEEK..._OF_MONTH,1);
weekday=d.get(Calendar.DAY_OF_WEEK);
}
while
Java get Next Day
Java get Next Day
In this section, you will study how to get the next day in java... DateFormatSymbols in
order to get the names of the days of the week. The method getWeekdays
How many hours a day/a week do you work?
How many hours a day/a week do you work?
Avoid being too specific on this answer. If you give a low figure, the company will view it as inadequate. If you commit
Java for beginners
for beginners
Learn Java in a day
Master Java in a week
All Java tutorials...Java for beginners Java for beginners
Which is the best resource to learn Java programming lanuage? Which is the best resource for learning Java
java code - Java Beginners
java code
Sir
Ineed one code for Matrix
"Take a 2D array and display all elements in matrix form using only one loop "
request
this question i asked last one week back but Your people send me one answer
Java Program - Java Beginners
Java Program Code an application using a GUI called Week Four Program that provides 3 menu options:
1: List Entries
2: Add Entries
3: Exit
Prompt for an option
If the user selects the first menu option
Java Program - Java Beginners
Java Program Code an application called Week Four Program that provides 3 menu options:
1: List Entries
2: Add Entries
3: Exit
Prompt for an option
If the user selects the first menu option
recognition of voiceashok vardhan April 19, 2011 at 5:32 PM
sir, I need a program for "accepting the voice from user and comparision of voice" in java
Want to ask a question.yatendra kumar June 19, 2011 at 9:08 AM
Sir, How to find the prime number at 10001st position.
ProgrammerAminu mu'azu m June 30, 2011 at 10:25 AM
Java is my interested program to learn now.pls put and carry me along.
java program.ahmed riyas July 11, 2011 at 7:35 PM
i want to learn java.......
swingvijay tuteja August 31, 2011 at 2:01 AM
i want to learn swing....plz discussed with me.....reply me
javachandu February 12, 2013 at 7:29 PM
java interview questions
java corerashmi` October 13, 2011 at 7:32 PM
i want creat gui application by java coreso i need coding nand notes regarding it plz help me
JAVA PROGRAMMINGsanthu May 28, 2012 at 5:47 PM
thanks alot
java programming 1Darwin September 3, 2012 at 4:41 PM
how to make a program in binary like any to any...
stringskamila September 8, 2012 at 12:52 PM
how to access strings in java programs
javaashebir dohe December 5, 2012 at 11:03 AM
i want to learn the tutorial.
javasubelal November 19, 2013 at 3:47 PM
please give the information with the example
sir,i hava need a program of calculatorSudhir Shivlal Rathod February 16, 2014 at 5:55 PM
I am Now Studying java language so give important notes of java. thanks...
Post your Comment | http://roseindia.net/discussion/19994-Master-Java-In-A-Week.html | CC-MAIN-2014-15 | refinedweb | 1,540 | 61.87 |
olapo SekoniCourses Plus Student 1,431 Points
help with product
kindly show me what am doing wrong
def product(num1,num2): print(num1 * num2) return(num1 * num2)
1 Answer
Alex KoumparosPython Development Techdegree Student 36,861 Points
Hi Dolapo
In your function you are printing the result of multiplying num and num2. The challenge wants you to return the result.
In your next line you are trying to return a value but you are not in the function so return is invalid and num1 and num2 are out of scope. If you wanted your return statement to be part of the function then you would need to have it indented to the same level as your print statement. | https://teamtreehouse.com/community/help-with-product | CC-MAIN-2021-43 | refinedweb | 118 | 59.98 |
XUL Tutorial:Introduction to RDF
From MDC
In this section, we'll look at RDF (Resource Description Framework).
[edit] Resource Description Framework
We can use the tree elements to display a set of data, such as bookmarks or mail messages. However, it would be inconvenient to do so by entering the data directly into the XUL file. It would make it very difficult to modify the bookmarks if they were directly in the XUL file. The way to solve this is by using RDF datasources.
RDF (Resource Description Framework) is a format that can be used to store resources such as bookmarks or mail. Alternatively, data in other formats can be used and code written that will read the file and create RDF data from it. This is how Mozilla works when it reads data such as bookmarks, the history or mail messages. Mozilla provides datasources for this common data so that you can easily use them.
You can use any of the provided RDF datasources to populate trees with data or you can point to an RDF file stored in XML which contains the data. This makes it very convenient to display trees with lots of rows in them. RDF can also populate other XUL elements as well such as listboxes and menus. We'll see this in the next section.
A very brief overview of RDF will be provided here. For a more detailed guide to RDF, read Introduction to the RDF Model, at XULPlanet. It is recommended that you read this guide if you are new to RDF.
For more information about RDF, see the RDF specification.
[edit] RDF/XML
RDF consists of a model, which is a graph representation of data. RDF/XML is an XML language which can be used to represent RDF data. It contains a fairly simple set of elements. The sample below shows a simple RDF template.
<?xml version="1.0"?> <RDF:RDF xmlns: ... </RDF:RDF>
This has some similarities to the XUL header. Instead of the
window element, the
RDF element is used. You can see the namespace for RDF was declared so that the RDF elements are recognized properly. Inside, the
RDF element, you will place the data. To see some example RDF/XML files, look at those provided with Mozilla. They have the extension rdf.
[edit] RDF database
Let's take the example of a bookmarks list generated from RDF. A bookmarks list contains a set of records, each with a set of data associated with it, such as a URL, a bookmark title and a visited date.
Think of the bookmarks as a database, which is stored as a large table with numerous fields. In the case of RDF however, the lists may be hierarchical as well. This is necessary so that we can have folders or categories of bookmarks. Each of the fields in an RDF database is a resource, each with a name associated with it. The name is described by a URI.
For example, a selection of the fields in the Mozilla bookmark list is described by the URIs below:
These are generated by taking a namespace name and appending the field name. In the next section, we'll look at how we can use these to fill in the field values automatically. Note that the last visited date has a slightly different namespace than the other three.
[edit] RDF/XML file example
Below, a sample RDF/XML file is shown, listing a table with three records and three fields.
<RDF:RDF xmlns: <RDF:Seq <RDF:li> <RDF:Description <ANIMALS:name>Lion</ANIMALS:name> <ANIMALS:species>Panthera leo</ANIMALS:species> <ANIMALS:class>Mammal</ANIMALS:class> </RDF:Description> </RDF:li> <RDF:li> <RDF:Description <ANIMALS:name>Tarantula</ANIMALS:name> <ANIMALS:species>Avicularia avicularia</ANIMALS:species> <ANIMALS:class>Arachnid</ANIMALS:class> </RDF:Description> </RDF:li> <RDF:li> <RDF:Description <ANIMALS:name>Hippopotamus</ANIMALS:name> <ANIMALS:species>Hippopotamus amphibius</ANIMALS:species> <ANIMALS:class>Mammal</ANIMALS:class> </RDF:Description> </RDF:li> </RDF:Seq> </RDF:RDF>
Here, three records have been described, one for each animal. Each
RDF:Description tag describes a single record. Within each record, three fields are described,
name,
species and
class. It isn't necessary for all records to have the same fields but it makes more sense to have them all the same.
Each of three fields have been given a namespace of
ANIMALS, the URL of which has been declared on the
RDF tag. The name was selected because it has meaning in this case, but we could have selected something else. The namespace feature is useful because the
class field might conflict with that used for styles.
The
Seq and
li elements are used to specify that the records are in a list. This is much like how HTML lists are declared. The
Seq element is used to indicate that the elements are ordered, or in sequence. Instead of the
Seq element, you can also use
Bag to indicate unordered data, and
Alt to indicate data where each record specifies alternative values (such as mirror URLs).
The resources can be referred to in a XUL file by combining the namespace URL followed by the field name. In the example above, the following URIs are generated which can be used to refer to the specific fields:
Next, we'll see how we can use RDF to populate XUL elements. | http://developer.mozilla.org/en/docs/XUL_Tutorial:Introduction_to_RDF | crawl-001 | refinedweb | 895 | 63.49 |
Compositing functions for Scala filter predicates
When you get past the beginner level of Scala programming, you might feel like
filter() is a very basic function that you always know how to use. And then you’re sure to run into situations where it’s just not working and you can’t figure out why.
That happens to me. I try to do something with
filter() that looks like it should work, but it doesn’t. After some dead ends and digressions, I figure out what the problem is, and forget about it.
After the third or fourth time going through this, I thought maybe I should write down what the problem is and how I solved it.
The classic example for
filter() is to filter out odd numbers from a list of integers. Filtering out even numbers is also very easy.
scala> (1 to 50).filter(_ % 2 == 1)
res0: IndexedSeq[Int] = Vector(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49)
In general, it’s better to get odd or even numbers by means other than filtering. If we wanted to filter by primality, that would make for a more worthwhile use
filter().
I don’t think Scala has any built-in primality functions, but it’s easy enough to make one.
@scala.annotation.tailrec
def isPrime(number: Int): Boolean = number match {
case n if n < 0 => isPrime(-n)
case 0 => false
case 1 => false
case n => !((2 until n - 1) exists (n % _ == 0))
}
This may not be the most elegant or the most efficient, but it should work just fine for integers close to 0. We can use it to filter out positive integers less than 100 that are not prime.
scala> (1 to 100).filter(isPrime(_))
res1: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
If we copy and paste the result into Sloane’s OEIS, entry A40, the prime numbers, should come up as the very first search result. We don’t even have to use the wildcard
_:
scala> (1 to 100).filter(isPrime)
res2: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
So far, so good.
Now let’s say we want to know which integers stay or become primes when we reverse their digits (for example, 14 is composite but 41 is prime). It’s very easy in Scala to write a digit reversal function:
def reverseDigits(n: Int): Int =
Integer.parseInt(n.toString.reverse)
We don’t even have to worry about the fact that
java.lang.String doesn’t actually have
reverse(), it’s taken care of for us through an implicit conversion from
String to
scala.collection.StringOps.
It should be very easy to filter integers that have prime digit reversals, right? Yeah, but only if you have exactly the right syntax.
scala> (1 to 100).filter(isPrime(reverseDigits))
^
error: missing argument list for method reverseDigits
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `reverseDigits _` or `reverseDigits(_)` instead of `reverseDigits`.
Exact same error message on Scastie. So yeah, let’s go ahead and do that “explicit conversion” thing. No good…
scala> (1 to 100).filter(isPrime(reverseDigits _))
^
error: type mismatch;
found : Int => Int
required: Intscala> (1 to 100).filter(isPrime(reverseDigits(_)))
^
error: type mismatch;
found : Int => Int
required: Int
Once again, we get the same error messages on Scastie as on the local Scala REPL. Maybe we need to use a temporary variable instead of the wildcard? Still doesn’t work…
scala> (1 to 100).filter(n: Int => isPrime(reverseDigits(n)))
^
error: ')' expected but '(' found.
^
error: ';' expected but ')' found.
At about this point, I’m getting very frustrated, I start thinking that maybe IntelliJ can help me figure out what it is that I’m doing wrong. So let’s fire up IntelliJ IDEA (presumably you already have the Scala plugin).
Okay, so IntelliJ’s telling me that it “cannot resolve overloaded method
filter.” Then I go down a rabbit hole: the Scala documentation for
Range lists
filter() twice, first as one of the “value members” and second as a “shadowed implicit value member.”
If I’m understanding the documentation correctly, the
filter() from
TraversableOnce[A] is being shadowed by the
filter() from
Range. So maybe I need to help the Scala compiler figure out which one is which.
((1 to 100): Range).filter(isPrime(reverseDigits(_))
IntelliJ still gives me the error message that it can’t resolve
filter(). In hindsight it seems obvious to me now this was a bad idea, but at least I tried it. So how about
TraversableOnce[Int]?
((1 to 100): TraversableOnce[Int]).filter(isPrime(reverseDigits(_))
Turns out
TraversableOnce[A] is now deprecated. But if it works, it works, right? Except it doesn’t. And IntelliJ is showing me “
: Int => Int” in gray and underlining it in red near the end of the line.
How about defining a separate named function to wrap the composited function into a single function and pass that to
filter()?
scala> def digitsReverseToPrime(n: Int): Boolean =
isPrime(reverseDigits(n))
digitsReverseToPrime: (n: Int)Booleanscala> (1 to 100).filter(digitsReverseToPrime)
res6: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 14, 16, 17, 20, 30, 31, 32, 34, 35, 37, 38, 50, 70, 71, 73, 74, 76, 79, 91, 92, 95, 97, 98)
It works, but why should we have to create a new named function we might never use again? There’s got to be a better way. Surely this sort of thing would work in Java if Java had higher order functions…
Maybe now’s the time to look it up in Google. As expected, a lot of results are for Stack Overflow. And as usual, in many of the Stack Overflow answers, it turns out that the problem is caused by something that does not apply to my situation.
So maybe I should ask my own question on Stack Overflow. I start to type it up. They like it if you show that you tried everything you can think of.
I already tried using a temporary local variable without indicating its type, right? It should fail now just like it failed before.
scala> (1 to 100).filter(n => isPrime(reverseDigits(n)))
res7: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 14, 16, 17, 20, 30, 31, 32, 34, 35, 37, 38, 50, 70, 71, 73, 74, 76, 79, 91, 92, 95, 97, 98)
Well, what do you know? It works! It also works in Scastie. I guess I actually hadn’t tried it before.
I don’t know why the wildcard doesn’t work with the composited function. Maybe someone will explain in the comments.
For now, though, I just want to be sure to write down the solution so that the next time I run into this sort of thing, I can just refer back to this.
I don’t want anyone to walk away with the impression that this kind of thing is unique to Scala. All programming languages have traps for the unwary. Though I think Scala has fewer such traps than languages like C or JavaScript. | https://alonso-delarte.medium.com/compositing-functions-for-scala-filter-predicates-9c8fcd45cebb | CC-MAIN-2021-21 | refinedweb | 1,250 | 72.56 |
Getting started
Page Templates are a web page generation tool. In this part, we'll go through their basics and show how to use them in your web site to create dynamic web pages easily. a valid HTML/XHTML page. Since HTML is highly structured, and WYSIWYG editors carefully preserve this structure, there are strict limits on the ways in which the programmer can change a page and still respect the first principle.
Although Page Templates are suited for programmers and designers who need to work together to create dynamic web pages, they form the basis for most of Plone's pages, so you should learn them a bit at least, if you need to customize the Plone look or layout. Moreover, they can be simpler to use and understand than the alternative, DTML.
Why Yet Another Template Language?
There are plenty of template systems out there, some of them quite popular, such as ASP, JSP, and PHP. Since the beginning, Zope has come with a template language called DTML. Why invent another?
First, none of these template systems are aimed at HTML designers. Once a page has been converted into a template, it is invalid HTML, making it difficult to work with outside of the application. Each of them violates the first or second principle of Zope Page Templates to one degree or another. Programmers should not "hijack" the work of the designers and turn HTML into software. XMLC, part of the Enhydra project, shares our.
Applying The Principles
Page Templates use the Template Attribute Language (TAL). TAL consists of special tag attributes. For example, a dynamic page title might look like this:
<title tal:Page Title</title>
The
tal:content attribute is a TAL statement. Since it
has an XML namespace (the
tal:
content of the
title tag, and the value "context/title" is an
expression providing the text to insert into the tag.
To the HTML designer using a WYSIWYG tool, this is perfectly valid HTML, and shows up in the editor looking the way a title should look. The designer, not caring about the application details of TAL, only sees a mockup of the dynamic template, complete with dummy values like "Page Title" for the title of the document.
When this template is saved in Zope and viewed by a user, Zope turns this static content into dynamic content and replaces "Page Title" with whatever "context/title" resolves to. In this case, "context/title" resolves to the title of the object to which to the template is applied. This substitution is done dynamically, when the template is viewed.
This example also demonstrates the second principle. When you view the template in an editor, the title text will act as a placeholder for the dynamic title text. The template provides an example of how generated documents will look.
There are template commands for replacing entire tags, their contents, or just some of their attributes. You can repeat a tag several times or omit it entirely. You can join parts of several templates together, and specify simple error handling. All of these capabilities are used to generate document structures. You can't create subroutines or classes, write loops or multi-way tests, or easily express complex algorithms. For these tasks, you should use Python.
The.
Creating a Page Template
If you design pages, you will probably use FTP or WebDAV instead of the Zope Management Interface (ZMI) to create and edit Page Templates, or you will be developing templates on the filesystem for later installation. If you're not the Zope site owner, ask your Zope administrator for instructions. For the very small examples in this article, it is much easier to use the ZMI. For more information on using FTP or WebDAV with Zope, see The Zope Book or Jeffrey Shell's WebDAV article.
You may also use Emacs, cadaver, or some other client, but if you are a Zope administrator or a programmer, you will probably use the ZMI anyway at least occasionally. See the Zope Book for instructions on setting up Zope to to work with various clients.
Use your web browser to log into the Zope management interface as
you normally would with Zope. Choose a Folder (the root is fine)
and pick "Page Template" from the drop-down add list. Type
"simple_page" in the add form's
Id field, then push the "Add and
Edit" button.
You should now see the main editing page for the new Page
Template. The title is blank, the content-type is
text/html,
and the default template text is in the editing area.
Now you will create a very simple dynamic page. Type the words "a
Simple Page" in the
Title field. Then, edit the template's body text
to look like this:
This is <b tal:the Title</b>.
Now push the "Save Changes" button. The edit page should show a
message confirming that your changes have been saved. If an error message appears above the code area, or some
text starting with
<-- Page Template Diagnostics is added to
the template, then check to make sure you typed the example
correctly and save it again. You don't need to erase the error
comment: once the error is corrected it will go away.
Click on the
Test tab. You should see a mostly blank page with
"This is a Simple Page." at the top.
Back up, then click on the "Browse HTML source" link under the content-type field. This will show you the unrendered source of the template. You should see "This is the Title." Back up again, so that you are ready to edit the example further.
Simple Expressions
The text "template/title" in your simple Page Template is a
path expression. This the most commonly used of the
expression types defined by the TAL Expression Syntax
(TALES). It fetches the
title property of the template.
Here are some other common path expressions:
request/URL: The URL of the current web request.
user/getUserName: The authenticated user's login name.
container/objectIds: A list of Ids of the objects in the same Folder as the template.
Every path starts with a variable name. If the variable contains
the value you want, you stop there. Otherwise, you add a slash
(
/) and the name of a sub-object or property. You may need to
work your way through several sub-objects to get to the value
you're looking for.
There is a small built in set of variables, such as
request and
user, that will be listed and described later. You will also
learn how to define your own variables.
Inserting Text
In your "simple_page" template, you used the
tal:replace
statement on a bold tag. When you tested it, it replaced the
entire tag with the title of the template. When you browsed the
source, instead, you saw the template text in bold. We used a bold tag in
order to highlight the difference.
In order to place dynamic text inside of other text, you typically
use
tal:replace on a
span tag. Add the following lines to
your example:
<br> The URL is <span tal:URL</span>.
The
span tag is structural, not visual, so this looks like "The
URL is URL." when you view the source in an editor or browser.
When you view the rendered version, it may look something like:
<br> The URL is.
Remember to take care when editing not to destroy the
span or
place formatting tags such as
b or
font inside of it, since
they would also be replaced.
If you want to insert text into a tag but leave the tag itself
alone, you use
tal:content. To set the title of your example
page to the template's title property, add the following lines
above the other text:
<head> <title tal:The Title</title> </head>
If you open the "Test" tab in a new window, the window's title will be "a Simple Page".
Repeating Structures
Now you will add some context to your page, in the form of a list of the objects that are in the same Folder. You will make a table that has a numbered row for each object, and columns for the id, meta-type, and title. Add these lines to the bottom of your example template:
<table border="1" width="100%"> <tr> <th>#</th><th>Id</th><th>Meta-Type</th><th>Title</th> </tr> <tr tal: <td tal:#</td> <td tal:Id</td> <td tal:Meta-Type</td> <td tal:Title</td> </tr> </table>
The
tal:repeat statement on the table row means
"repeat this row for each item in my container's list of
object values". The repeat statement puts the objects from
the list into the
item variable one at a time, and
makes a copy of the row using that variable. The value
of "item/id" in each row is the Id of the object for that row.
You can use any name you like for the "item" variable, as long as
it starts with a letter and contains only letters, numbers, and
underscores (
_). It only exists in the <tr> tag; If you
tried to use it above or below that tag you would get an error.
You also use the
tal:repeat variable name to get
information about the current repetition. By placing it
after the builtin variable
repeat in a path, you can access
the repetition count starting from zero (
index), from one (
number),
from "A" (
Letter), and in several other ways. So, the
expression
repeat/item/number is
1 in the first row,
2
in the second row, and so on.
Since one
tal:repeat loop can be placed inside of another, more
than one can be active at the same time. This is why you
must write
repeat/item/number instead of just
repeat/number. You must specify which loop you are interested in by
including the loop name.
Conditional Elements
View the template, and you'll notice that the table is very dull looking. Let's improve it by shading alternate rows. Copy the second row of the table, then edit the code so that it looks like this:
<table border="1" width="100%"> <tr> <th>#</th><th>Id</th><th>Meta-Type</th><th>Title</th> </tr> <tbody tal: <tr bgcolor="#EEEEEE" tal: <td tal:#</td> <td tal:Id</td> <td tal:Meta-Type</td> <td tal:Title</td> </tr> <tr tal: <td tal:#</td> <td tal:Id</td> <td tal:Meta-Type</td> <td tal:Title</td> </tr> </tbody> </table>
The
tal:repeat has not changed, you have just moved it onto
the new
tbody tag. This is a standard HTML tag meant to
group together the body rows of a table, which is how you are
using it. There are two rows in the body, with identical
columns, and one has a grey background.
View the template's source, and you see both rows. If you
had not added the
tal:condition statements to the rows,
then the template would generate both rows for every item,
which is not what you want. The
tal:condition statement
on the first row ensures that it is only included on even-indexed repetitions, while the second row's condition only
lets it appear in odd-indexed repetitions.
A
tal:condition statement does nothing if its expression
has a true value, but removes the entire statement tag,
including its contents, if the value is false. The
odd and
even properties of
repeat/item are either zero or one.
The number zero, a blank string, an empty list, and the
builtin variable
nothing are all false values. Nearly
every other value is true, including non-zero numbers, and
strings with anything in them (even spaces!).
Defining Variables
Your template will always show at least one row, since
the template itself is one of the objects listed. In other
circumstances, you might want to account for the possibility
that the table will be empty. Suppose you want to simply
omit the entire table in this case. You can do this by
adding a
tal:condition to the table:
<table border="1" width="100%" tal:
Now, when there are no objects, no part of the table will be included in the output. When there are objects, though, the expression "container/objectValues" will be evaluated twice, which is mildly inefficient. Also, if you wanted to change the expression, you would have to change it in both places.
To avoid these problems, you can define a variable to hold
the list, and then use it in both the
tal:condition and the
tal:repeat. Change the first few lines of the table to
look like this:
<table border="1" width="100%" tal: <tr> <th>#</th><th>Id</th><th>Meta-Type</th><th>Title</th> </tr> <tbody tal:
The
tal:define statement creates the variable
items, and you
can use it anywhere in the table tag. Notice also how you can
have two TAL attributes on the same
table tag. You can, in
fact, have as many as you want. In this case, they are evaluated
in order. The first assigns the variable
items and the second
uses
items in a condition to see whether or not it is false (in
this case, an empty sequence) or true.
Now, suppose that instead of simply leaving the table out when there are no items, you want to show a message. To do this, you place the following above the table:
<h4 tal:There Are No Items</h4>
You can't use your
items variable here, because it isn't defined
yet. If you move the definition to the
h4 tag, you can't use it
in the
table tag any more, because it becomes a local variable
of the
h4 tag. You could place the definition on some tag that
enclosed both the
h4 and the
table, but there is a simpler
solution. By placing the keyword
global in front of the
variable name, you can make the definition last from the
h4 tag
to the bottom of the template:
<h4 tal:There Are No Items</h4> <table border="1" width="100%" tal:
The
not: in the first
tal:condition is an expression type
prefix that can be placed in front of any expression. If the
expression is true,
not: is false, and vice versa.
Changing Attributes
Most, if not all, of the objects listed by your template have an
icon property, that contains the path to the icon for that kind
of object. In order to show this icon in the meta-type column,
you will need to insert this path into the
src attribute of an
img tag, by editing the meta-type column in both rows to look
like this:
<td> <img src="/misc_/OFSP/Folder_icon.gif" tal: <span tal:Meta-Type</span> </td>
The
tal:attributes statement replaces the
src attribute of the
image with the value of
item/icon. The value of
src in the
template acts as a placeholder, so that the image is not broken,
and is the correct size.
Since the
tal:content attribute on the table cell would have
replaced the entire contents of the cell, including the image,
with the meta-type text, it had to be removed. Instead, you
insert the meta-type inline in the same fashion as the URL at the
top of the page.
Based on the Zope Book, © Zope Corporation
Unexpected behavior...
<tr bgcolor="#EEEEEE" tal:
and
<tr tal:
made even numbered lines white, and odd numbered lines grey...which doesn't appear to be what we "want" with our code.
to get it to work as I expected, I took this as a little quick lesson and came up with something that DID work,
which makes me wonder what "repeat/item/odd" and "repeat/item/even" actually do, and if they're backwards:
<tr bgcolor="#EEEEEE" tal:
and
<tr tal:
We all know that ( x % 2 == 0 ) means "even" ... so why would it be different then using the "even" built-in condition?
--Brian | http://plone.org/documentation/tutorial/zpt/getting-started | crawl-002 | refinedweb | 2,684 | 69.62 |
Hey guys. Bare with me because I am new to Java and am in a class, yet I would love to be great at it at some point. Any advice regarding style, etc. would be great. In this program, I had to make a game where the user bets dollars and guesses if 2 coins land on heads or tails. Everything works, except that in my loop, I want the player to choose whether or not to play again. The program immediately skips to the next part where the player enters his/her guess. Here is the source code and a screen shot of what happens. If you can help me find the issue (which I covered in bold), that would be very helpful as I have been stuck for a while now.
import java.util.Scanner;
import java.util.Random;
public class FlipACoinGame {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Random generator = new Random();
int coin1, coin2, //two coins
dollars, //initial number of dollars(input)
count, //number of tosses to reach depletion
maxDollars, //maximum amount held by the gambler
countAtMax, //count when the maximum is achieved
coin1Guess, coin2Guess; //Player's guess of heads (1) or tails(2)
//Initialize variables
countAtMax = 0;
count = 0;
maxDollars = 0;
//Request the input
System.out.print("How many dollars do you have? ");
dollars = reader.nextInt();
//Loop until the money is gone.
while (dollars > 0){
count++;
String playAgain; //Player inputs yes or no for another round
//Have player input "YES" or "NO" and prediction of heads (1) or tails (2) for each coin.
System.out.print("Thank you for playing \"Flip A Coin.\" Are you sure you still want to gamble?");
playAgain = reader.nextLine();
if (playAgain == "NO"){
break;
}
System.out.print("\nEnter your guess for coin 1 (enter 1 for heads or 2 for tails)");
coin1Guess = reader.nextInt();
System.out.print("\nEnter your guess for coin 2 (enter 1 for heads or 2 for tails)");
coin2Guess = reader.nextInt();
//Flip coins
coin1 = generator.nextInt (2) + 1; //1(heads) or 2(tails)
coin2 = generator.nextInt (2) + 1; //1 (heads) or 2(tails)
//Calculate winnings and/or losses
if (coin1 == coin1Guess||coin2 ==coin2Guess){
dollars += 1;
System.out.println("ONE MATCH! You win 1 dollar! Your new total is " + dollars + ".");
}
else if (coin1 == coin1Guess && coin2 == coin2Guess){
dollars += 4;
System.out.println("TWO MATCHES! You win 4 dollars! Your new total is " + dollars + ".");
}
else {
dollars -= 1;
System.out.println("Sorry, no match. You lose 1 dollar. Your new total is " + dollars + ".");
}
//If this is the new maximum, remember it
if (dollars > maxDollars){
maxDollars = dollars;
countAtMax = count;
}
}
//Display results
System.out.println
("You are broke after " + count + " rounds.\n" +
"You should have quit after " + countAtMax +
" rolls when you had $" + maxDollars + ".");
}
}
FlipACoinGame.jpg | https://www.javaprogrammingforums.com/whats-wrong-my-code/33425-my-program-skips-if-statement-i-want-include-my-loop-dont-know-why.html | CC-MAIN-2020-50 | refinedweb | 456 | 67.65 |
Felix, I'd like to see people respond to the original challenge to produce a Python solution to the given problem (once the homework aspect has passed). Meanwhile, I will use your question as a soap box. I wouldn't have thought to work out a FORTRAN solution, as Bieber did, and I am grateful that he provided that. The first program that I ever managed to have executed by a computer was written in FORTRAN (release 1! Boy, talk about bugs) around May of 1958. But I haven't done much with it in a long time. Here's a little more for those wanting a comparative view of the Fortran solution to the simple text-analysis problem: ANATOMY OF A LITTLE FORTRAN STRUCTURE The statements numbered 10, 20, and 30 are null statements. They are being used by Bieber as place-holders for statement numbers. It is part of his programming style for this example. The original use for FORTRAN's "continue" was to have a place at the end of an iteration body that you could break (actually, branch) to in order to continue with the next iteration cycle without performing any further action in the current iteration. The non-null "continue" statement in C Language has similar purpose with a cleaner approach. If you moved the first continue before the first read statement, the duplicate read statement before "goto 10" can be eliminated. Bieber has shown Python-like indentation in his version, which helps somewhat to make the structure clear. There are other details stemming from FORTRAN's origin in an era of only 48 character codes (no separate [ and ] so ( and ) serve for all brackets) and punched-card input organization. The first six columns of a line have special rules (the "X" in column 6 on the line below the elsif statement is FORTRAN's way of introducing a continuation line) and white space outside of strings is *ignored* to the right of column 6 of any line. In FORTRAN, statement numbers were required for introduction of non-sequential control flow. Block-structured languages (using bracketing instead of labeling) and structured programming hadn't been invented yet. Over the years, counterparts of standard program structures have been blended into the language, and Bieber uses some of those (such as the if ... then ... else ... endif structure). Without getting too far into it, you should be able to discern that the procedural structure of this and a Python solution are very close. The details, idiosyncrasies, and common idioms are different, but at this basic level of computational method, there is not much different. There are more syntactic irregularities in FORTRAN, although it can feel that way using Python too, until you get the principles down. In FORTRAN, you don't want to know the principle, which is pretty much an exposure of the implementation of the original parser, devised before we learned to specify grammars for programming languages and then produce grammar-based parsers. SOME LESSONS HERE 1. I want to acknowledge something that Bieber and these exchanges demonstrate, and that is outstanding about the use of Python. One of the first thing I notice about Python is that snippets, using modern e-mail technology, are easily exchanged, discussed and actually tried out. I was struck by that the moment I subscribed to this list, less than two months ago. I say that is a *very* big deal. FORTRAN was the first production programming language that allowed that kind of collegiality, along with the introduction of definable functions and subroutines in FORTRAN II. I always admired it for that achievement. The Algol community perpetuated that idea, and a body of algorithms and practical computational methods was developed by collaborative refinement over many years. Young students like Donald Knuth and Niklaus Wirth published their solutions and other people provided alternatives, translations, and corrections. That was a lively and energetic time, dependent on the willingness of people to publish their methods and allow them to be debugged in public. Today's open-source movement provides a counterpart of that approach, though most problems and solutions are now much larger and not the kind of thing that one should use for study and practice, perhaps. The Python libraries and discussions seem to have provided a forum that revives what was best about that, and we have the Internet to support us now. 2. It is easy to forget how much had to be invented, and how much difference some simple inventions and refinements have provided. The subroutine, (i.e., def of anything) that could be reused multiple times, and a way to code that in machine language, was an invention. Then there were the interesting issues about providing different parameters to different executions, and then accommodation of the impact of recursion and re-entrance on that, etc., etc. None of these things stepped out of the waves in complete purity and completeness of form. And the lessons and experiences played out in the work of individuals as well as communities. Young John Backus worked on the 1950's FORTRAN team (it was at least his second language development). He then saw a better way to specify language grammars when people were working on Algol 58 as an international community solution for the problem domain that FORTRAN already lived in. This inspired the syntactic specification of ALGOL 60, which led to syntax-oriented parsing and compiling. Later, John worked out FP, his approach to functional programming introduced to the world in his Turing Award lecture. Functional programming was older than that, but John's particular approach to it provided a lot to think about. The idea of functions that deliver (derived) functions (or closures) as first-class results is still not well established. Python barely allows it at all. 3. There is a big difference in the programming styles that are cleanly supported by post-ALGOL languages. What we learned about clean styles and use of inspectable invariants through Spartan control structures can be honored by *practice* using FORTRAN, but it isn't something that there is natural support for in the design of the language itself. An even bigger difference in the trans-ALGOL languages and in the parallel-evolved LISP languages is in regard to what is "first class" and what the richness of objects and types can be. Those contributions are simply beyond FORTRAN's conceptual reach, not that people won't hack some of it into the language anyhow. Nevertheless, FORTRAN has provided a stable platform for the collegial development and preservation of high-performance numerical software for almost 50 years. That's pretty remarkable. 4. It is also the case that for the toy problem that began this thread, an archaic programming language works about as well as any other. It's not so smooth looking, because FORTRAN doesn't have the smooth kind of free-form syntax that we are now accustomed to. But since the problem deals with immutable scalar values and simple kinds of vectors, lists, and strings, there is not too much stress on FORTRAN's sweet spot. It is the case that the programming languages that have wide currency today, however new, also manage to preserve the simple usages and structures that were all that the original programming languages had to offer. Languages that use descriptive paradigms often lose this, and become too inaccessible to existing practitioners and neophytes both. It can be important to let people build on what they already know or find easy to comprehend. The Von Neumann style of programming may have its limitations, but one advantage is that people have some familiarity with it in everyday "computational" chores. There may be a time to kick over the ladder and ascend to the next level another way. But leave the ladder down there for the next guy. -- Dennis -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Felix Thibault Sent: Friday, March 24, 2000 23:15 To: python-list at python.org; python-list at python.org Subject: Re: HELP Newbie solve this Problem Are 10, 20, and 30 continuations ? At 21:10 3/23/00 -0800, Dennis Lee Bieber wrote: >On Fri, 24 Mar 2000 03:43:38 GMT, race9047 at my-deja.com declaimed the >following in comp.lang.python: > I must be from a different world then... The second part is what >I'd find easy... even in FORTRAN (maybe too easy in FORTRAN) > > integer counts(26) / 26 * 0 / ! or is it 0 * 26? > character line*132 ! set for the longest line the > ! the data file can contain > open(10, file="data", status="old") > read(10, '(a132)', iostat=ios) line > 10 continue > if (ios .eq. 0) then > do 20 i=1, 132 ! or the line length max > if (line(i:i) .ge. 'a' .and. line(i:i) .le. 'z') then > inx = ichar(line(i:i)) - ichar('a') + 1 > counts(inx) = counts(inx) + 1 > elseif (line(i:i) .ge. 'A' .and. line(i:i) .le. 'Z') > x then > inx = ichar(line(i:i)) - ichar('A') + 1 > counts(inx) = counts(inx) + 1 > else > continue ! just my style > endif > 20 continue > read(10, '(a132)', iostat=ios) line > goto 10 > endif > close(10) > do 30 i=1, 26 > print *, char(i), ' ', counts(i) > 30 continue > stop > > > It would look much cleaner in Python, and I'd use case >conversion modules rather than the duplicates in the IF statements... > > >-- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Bestiaria Home Page: < > > Home Page: < >-- > > > -- | https://mail.python.org/pipermail/python-list/2000-March/055310.html | CC-MAIN-2016-36 | refinedweb | 1,602 | 61.56 |
FizzBuzz is a game I learned long ago in
elementary-school French class, as a way to practice counting in that
language. The players take turns counting, starting with one and
going up. The rules are simple: when your turn arrives, you say the
next number. However, if that number is a multiple of five, you
should say the word "fizz"
(preferably with a French accent) instead. If the number is a
multiple of seven, you should say
"buzz." And if it is a multiple of
both, you should say "fizzbuzz." If
you mess up, you're out, and the game continues
without you.
Example 1-2 is a Java program named
FizzBuzz that plays a version of the game.
Actually, it isn't a very interesting version of the
game because the computer plays by itself, and it
doesn't count in French! What is interesting to us
is the Java code that goes into this example. It demonstrates the use
of a for loop to count from 1 to 100 and the use
of if/else statements to decide whether to output
the number or one of the words
"fizz",
"buzz", or
"fizzbuzz". (In this case, the
if/else statement is used as an
if/elseif/elseif/else statement, as
we'll discuss shortly.)
This program introduces System.out.print( ). This
method is just like System.out.println( ), except
that it doesn't terminate the line of output.
Whatever is output next appears on the same line.
The example also shows another style for comments. Anything, on any
number of lines, between the characters /* and the
characters */ is a comment in Java and ignored by
the compiler. When one of these comments begins with
/**, as the one in this example does, then it is
additionally a doc comment, which means its
contents are used by the javadoc program that
automatically generates API documentation from Java source code.
package je3.basics;
/**
* This program plays the game "Fizzbuzz". It counts to 100, replacing each
* multiple of 5 with the word "fizz", each multiple of 7 with the word "buzz",
* and each multiple of both with the word "fizzbuzz". It uses the modulo
* operator (%) to determine if a number is divisible by another.
**/
public class FizzBuzz { // Everything in Java is a class
public static void main(String[ ] args) { // Every program must have main( )
for(int i = 1; i <= 100; i++) { // count from 1 to 100
if (((i % 5) == 0) && ((i % 7) == 0)) // Is it a multiple of 5 & 7?
System.out.print("fizzbuzz");
else if ((i % 5) == 0) // Is it a multiple of 5?
System.out.print("fizz");
else if ((i % 7) == 0) // Is it a multiple of 7?
System.out.print("buzz");
else System.out.print(i); // Not a multiple of 5 or 7
System.out.print(" ");
}
System.out.println( );
}
}
The
for and if/else statements may
require a bit of explanation for programmers who have not encountered
them before. A for statement sets up a loop, so
that some code can be executed multiple times. The
for keyword is followed by three Java expressions
that specify the parameters of the loop. The syntax is:
for(initialize ; test ; update)
body
The initialize
expression does any necessary initialization. It is run once, before
the loop starts. Usually, it sets an initial value for a loop counter
variable. Often, as in this example, the loop counter is used only
within the loop, so the initialize
expression also declares the variable.
The test
expression checks whether the loop should continue. It is evaluated
before each execution of the loop body. If it evaluates to
true, the loop is executed. When it evaluates to
false, however, the loop body is not executed, and
the loop terminates.
The update
expression is evaluated at the end of each iteration of the loop; it
does anything necessary to set up the loop for the next iteration.
Usually, it simply increments or decrements the loop counter
variable.
Finally, the
body is the Java code that is run each
time through the loop. It can be a single Java statement or a whole
block of Java code, enclosed by curly braces.
This explanation should make it clear that the for
loop in Example 1-2 counts from 1 to 100.
The
if/else statement is simpler than the
for statement. Its syntax is:
if (expression)
statement1
else
statement2
When Java encounters an if statement, it evaluates
the specified expression. If the
expression evaluates to true,
statement1 is executed. Otherwise,
statement2 is evaluated. That is all
if/else does; there is no looping involved, so the
program continues with the next statement following
if/else. The else clause and
statement2 that follows it are entirely
optional. If they are omitted, and the
expression evaluates to
false, the if statement does
nothing. The statements following the if and
else clauses can be either single Java statements
or entire blocks of Java code, contained within curly braces.
The thing to note about the
if/else statement (and the for
statement, for that matter) is that it can contain other statements,
including other if/else statements. This is how
the statement was used in Example 1-2, where we saw
what looked like an if/elseif/elseif/else
statement. In fact, this is simply an if/else
statement within an if/else statement within an
if/else statement. This structure becomes clearer
if the code is rewritten to use curly braces:
if (((i % 5) == 0)&& ((i % 7) == 0))
System.out.print("fizzbuzz");
else {
if ((i % 5) == 0)
System.out.print("fizz");
else {
if ((i % 7) == 0)
System.out.print("buzz");
else
System.out.print(i);
}
}
Note, however, that this sort of nested if/else
logic is not typically written out with a full set of curly braces in
this way. The else if programming construct is a
commonly used idiom that you will quickly become accustomed to. You
may have also noticed that I use a compact coding style that keeps
everything on a single line wherever possible. Thus,
you'll often see:
if (expression) statement
I do this so that the code remains compact and manageable, and
therefore easier to study in the printed form in which it appears
here. You may prefer to use a more highly structured, less compact
style in your own code. | http://books.gigatux.nl/mirror/javaexamples/0596006209_jenut3-chp-1-sect-2.html | CC-MAIN-2019-13 | refinedweb | 1,054 | 64 |
ADD THIS METHOD:
public boolean equals (IntSet otherSet)
-returns true or false as this set and otherSet contain the same elements or not
Can someone explain to me what to do here? I don't even know where to start. Professor says I should pass IntSet, but shouldn't it be the ArrayList I created instead? Someone help me please!
Here is what I have so far:
import java.util.*; public class IntSet { private ArrayList<Integer> list; public IntSet() { list = new ArrayList<Integer>(); } public boolean in(int e) { int i = list.indexOf(e); if(i >= 0) { return true; } else { return false; } } public void insert(int e) { list.add(e); } public void remove(int e) { list.remove(e); } public IntSet compare (IntSet otherSet) { } }
This post has been edited by mattlyons: 26 September 2009 - 08:27 PM | http://www.dreamincode.net/forums/topic/128343-comparing-arraylists/ | CC-MAIN-2017-22 | refinedweb | 135 | 75 |
...why bother changing it? The fact is most users never leave their "home" directory, and if they are so bold to do so, to manipulate their system outside of that operating system's standard method of application installation and updating, then they will take the time to learn and try and understand the file system layout.
Mac OS X users are perfectly happy seeing "Applications", "Home" and little else. It's the hacks like myself who love digging down into the underlying guts and mucking around down there, replacing finder, moving my home directory to another disk, etc.
Most people understand this:
My Documents
My Music
My Video
My Pictures
And that is about all they care about... that and email and web browsing.
---
Edit: Don't get me wrong, I understand the benefits of a truly standardized file system layout, but I don't see any real pressure to treat this as tho' it were extremely important.
Edited 2009-05-28 19:39 UTC
Are you going to try and tell me that is because of the file system?
Is the layout of a file system so inspiring to people, to creativity, to life on a computer?
I am a software engineer, and even to me file system layout is not really a subject that causes me to wax on about standards and the pain and suffering caused by a lack thereof..
Transparency, clarity, and simplicity across the board are beneficial to the computer industry. The file system is part of that.
Well I can't argue with that.
Maybe I am too entrenched in the operating system and programming worlds to really see the forest for the trees, or the other way around maybe.
I guess I've just worked on so many different Operating Systems with a variety of file systems that I am just able to figure it all out fairly quickly.
Simplicity is always better..
Welcome to the Macho club. This club exists at all levels - file systems, programming languages, application development, etc, etc. I describe it as the "I made it up the hill, now it's your turn" syndrome. This syndrome also applies to math - "How symbolic can we make, they'll never figure out our shorthand". Even in religion it is done. I get physically nauseous when I hear some Christians banter around theological terms designed to keep out the uninitiated. I call PHOOEY on all of it.
[deep breath]
I feel better now. I hope you `cat my_comment | grep useful` , Okay?
Welcome to the Macho club. This club exists at all levels - file systems, programming languages, application development, etc, etc. I describe it as the "I made it up the hill, now it's your turn" syndrome.
This is so sadly true, and also apparent quite often here at this site even. I would go further to suggest that many geeks and techies just lack the comprehension that other users simply view computing differently. Let's face it, there is a lot of unwarranted arrogance by people who simply look down at non-techies as either lazy, ignorant, or stupid.
Users could care less, or give a damn, about the logic or reasons behind etc, var, usr, opt, etc..On the other hand;
Programs
Users
System
Files
Mount
Depot
This is what a system should look like for end-users, or better put "the public". I think we can all agree that POSIX FHS was NOT designed for end users in mind. Windows got it right with putting the OS in "Windows", programs in "Programs Files", and profiles in "Documents and Settings". For any user, this is not just logical but easily understandable.
Go find 100 random people on the street, show them two pieces of paper with the directory listing. Should we be surprised that 99% would pick GoboLinux's over any other?
For geeks, computing is a hobby and toy, but for non geeks it is a tool meant for easing certain tasks. When you complicate the task at hand, you defeat the whole purpose of having a computer. Maybe in 2009 some can figure out that a FHS designed decades ago for non public use should be evolved some. Otherwise, with such mentality, expectations should be lowered to realistic levels about adoption.
To begin with, non-geeks categorically won't be poking around the filesystem, on Windows, Linux, or (insert OS here), simply because there is NOTHING productive to be gained from it - all they care about is their Desktop, their home directory, and their installed programs. The parent post mentions Windows, which is an excellent example of end user-apathy: despite the 'simplified' root filesystem, none of the non-geeks that I can know can navigate it any better than they could the traditional *nix filesystem, nor should they need to.
The Windows model also provides a glimmer of the hurdles provided by 'simplified' interfaces: every library or binary which is installed system-wide is placed in X:\Windows\System32, which results in an even more bloated primary resource directory than on *NIX. This monolithic layout also prevents the traditional *NIX concept of mounting additional remote resources to a standardized location (/usr) atop a the bare minimum required for local maintenance (/). Whether or not this model is valid any longer is up for debate, but the fact of the matter is that the FHS was not designed in order to create a 'macho club' as you are inclined to suggest.
All in all, while filesystem revisions sound like a good idea to the unresearched geeks suggesting the alterations, the end users could care less, and those 'initiated' geeks understand the historical and practical considerations of how such layouts came to be. Even GoboLinux maintains a traditional FHS shim under the trappings of a new root filesystem.
Edited 2009-05-28 21:12 UTC
To begin with, non-geeks categorically won't be poking around the filesystem, on Windows, Linux, or (insert OS here), simply because there is NOTHING productive to be gained from it - all they care about is their Desktop, their home directory, and their installed programs.
Non-geeks shouldn't care about it, no, and most often they don't.. but is that a good reason for not creating a better standard? IMHO there is ALWAYS room for improvement, even if it helps only a select bunch of people. And in this case it'd help developers, sysadmins and most likely packagers too!
I f.ex. am annoyed by the fact that there's atleast three different "bin" locations: /bin, /usr/bin and /usr/local/bin. Why not just make two locations instead: /Executable/CLI and /Executable/GUI? The same for libraries: /Shared/Libraries/32bit and /Shared/Libraries/64bit..
"On the other hand;
Programs
Users
System
Files
Mount
Depot
This is what a system should look like for end-users, or better put "the public"."
Er, why?
I have no idea what the hell that layout means. What goes where? What's the difference between "Files" and "Depot"? What actually goes in "Files"? How do you distinguish between "Programs" and "System", exactly?
Generally, can people who've never done any serious work on an operating system *please* quit proposing filesystem layouts as if it were something any idiot could jot on a bar mat after a couple of pints? It just isn't.
Did you have any idea what '/etc' was for the very first time you laid eyes upon it? Probably not. No file system hierarchy is completely understandable just by the names, but the GoboLinux documentation explains what each is for very well.
There IS a method to their madness.
Don't fall into the trap of thinking you represent "most users" and what you're arguing for would make it easier for all. Maybe if you show 100 PC _users_ the Microsoft layout vs. FHS you would get agreement that the MS way was easier. Then go talk to a different audience - how easy is it to use a networked FS to share common parts of the systems for thin-client applications? Different answer.
I know its an obtuse point - my point, though, is that the FHS has been designed to suit more use-cases than just desktop users, and there are reasons why many things are done the way they are. No, it's not necessarily easy to understand for an end-user, but then that is not the bee-all and end-all of metrics to measure the success (or otherwise) of a file-system layout.
egads - claiming that it's "the macho club" in incredibly macho. and also ignorant, or at least disrespectful of the non-idiots who brought us to this point. sure, whether it's /usr or /User is a bit silly, not unlike creat()/create(), but who really cares? the idea (of segregating kinds of files) is worth preserving, even if a casual user is puzzled.
I'm guessing gobo is just based on ignorance of history, perhaps wilful. also, if they were serious, they'd include something like environment modules, rather than the fairly awful Current pointer.
Mathematicians don't make things symbolic to confuse anyone (they wouldn't be very good mathematicians if they did!). It's not a symptom of making other people pay their dues. The fact of the matter is that it makes communicating mathematics simple for deep concepts; no one is deliberately trying to obfuscate anything or "keep out the uninitiated".
I'd argue that most every subject has its own jargon so that everyone can stay on the same page without having to work from first principles every time they wish to start a dialog.
But they don't care to understand... so many people don't understand the difference between the OS, the word proccesor, the browser and the search engine, and when you explain it to them, you can see that empty look when they try to _pretend_ that they are trying to _understand_.
But as long as the... er... 'stuff' does it's... er... 'thingie' or whatever, they're 'okay'...
Why do you think users intersted in learning more are not able to comprehend the FHS? Compared to other things in the computer field it's straight forward and actually documented.
I don't think we need to treat users as total idiots who are incapable of comprehending something like the FHS.
The FHS is clearly documented and it is the way it is for good reasons.
The problem with your theory is human stupidity. If you make the filesystem more "friendly looking" then a larger number of people are going to be more likely to start poking around in places they shouldn't and hose their system.
"I accidentally..the whole drive" isn't exactly covered under the manufacturer's warranty, either.
For the average user, "My Documents" or "/home"is a fine place to stay. Leave the inner workings to people that understand it.
Don't confuse stupidity with a lack of knowledge. Sooner or later, we all "poke around" places we shouldn't and screw things up. If that sort of behavior makes someone stupid, then we're all taking the short bus from now on.
Also, you're arguing here in favor of the principle known as "security through obscurity." Sometimes it actually works -- but I wouldn't count on it.
Because that's where the things that interest them are?
Look at it like you look at cars: sure you can open the hood and poke around if you like, and it'd be easier if everything were laid out for simplicity, but in the end only a small subset of people want to. Most are content to drive from place to place without ever worrying about anything more serious than putting gas in and checking their oil.
What's interesting is that Mac OS X is a hybrid of the two..
Mac OS X gets it's Filesystem layout from NeXTSTEP. GoboLinux is a copy of it.
Apple has the best way to do it on "Unix"!
Have a virtual file system (Like they used to have in Gnome) and then if you want to go to the command line and muck around you can.
Normal day to day users don't want to open the hard drive and freak out or get confused. People just want to see the basics.
Yet still on the Mac I can turn on the root account and see everything I need to see. Most of the time even as an advanced user I don't need to see all the folders in the Linux file system!
Or NeXT before them....
...
Yeah your right about that but same Steve Jobs though.
Remember Mac OS came from Nextstep / Openstep after Jobs came back and sold NeXT to Apple.
The 'My' in 'My this', 'My that' is superfluous. I am glad recent Linux distributions (e.g. Ubuntu Jaunty, Mandriva Spring 2009.1) did the sensible thing and by default put folders like 'Documents', 'Videos', 'Pictures' in the /home/user/ directory.
What remains is to pick those as default locations for document saving in certain applications, e.g. OpenOffice Write saves in 'Documents', Digikam saves in 'Pictures' etc. could be some distributions already do that though?
Personally I am very glad with the attention that is being given by the Linux community to big usability issues as well as smaller details like these.
Also, there is nothing really wrong with the layout of everything outside of /home/.
And if distributions follow the LSB, then it will be much easier to obtain Linux skills with distribution X and equally apply them in Linux distribution Y. I suppose directory names could still be made more human-readable, but I guess the idea in the olden days was that they should be short, e.g. 'srv' and not 'myspankingbrandnewserverdirectory'.
As for /home/ , if it's easy enough for end-users, admins should be able to figure it out as well...
debian has always been my favorite distro. and, its strengths are heavily acknowledged by the fact that so many other distros are based off of it.
i would be interested in seeing what could be accomplished if GoBoLinux were used as a sort of 'starting point' distribution, as well.
could be fun.
edit: fixed typo
Edited 2009-05-28 19:45 UTC
It seems to me that most users really do not need access to the internals of the OS, or anything outside of their home directory. OS X does include the FHS, but its hidden from users unless they go looking for it.
This is for good reason too, a user who doesn't know any better could inadvertantly delete, move, rename, or alter a file that the OS needs to operate correctly.
It is all well and good to say that computers should be simple enough for everyone to understand, but the reality of the matter is that computers and operating systems are complicated, and it takes a lot of special training to understand what is going on and why. I really don't think that's "macho", its just reality. Can the FHS be improved? Sure, but do 100 random people off of the street really need to be mucking about with system files? Probably not.
So, the real question is not "What should the file system look like?", it's "What should the file system look like to the user?"
I think that's an interesting question, but ultimately why should there be a disparity between the two?
For the most part on Mac OS X, all applications written for Aqua stay within the boundaries of the visible directories and as an administrator you could still do great damage going into /System/Library and deleting some small part...
Heck, how many users know the difference between /System/Library/, /Library/ and ~/Library/?
/System/Library - everything the system needs
/Library - everything the system needs but it's not critical
~/Library - everything your user account needs
Even if it's not apparent at first, the users won't freak out when they see /System/Library. But if they see /etc they do freak out.
If I am a non-technical user, upon seeing "Library" I'd think "I don't need to read books on this computer, I just want to surf the Internet" and press the Delete button.
Naming system directories like this is nice but I don't think it helps as much as people here claim it does.
Edited 2009-05-29 11:46 UTC
That has to be the most retarded thing I've EVER heard. Millions of non-experienced users use the Mac, which has numerous Library directories. How many of them have deleted it because they thought it had to do with books?
Jesus dude, get out more
Edited 2009-05-29 11:52 UTC
Retarded huh? I've heard of at least several people who delete everything on their system that they didn't create themselves and isn't called "Drivers". A friend of mine hides his work in a directory called "Windows System Drivers" because otherwise his dad will delete the stuff without looking.
The FHS is forcing us into "spray-on usability" where a simple-looking GUI obscures complex internals when we should probably be working on real usability: making the system internally simple and understandable.
People have opposed every cross-cutting usability improvement (udev, HAL, D-Bus, NetworkManager, PulseAudio, X on tty1 (!), compositing, kernel modesetting, etc.) yet they were eventually made, so there is some hope of fixing FHS. I suspect it would take a strong leader to push it through.
Perhaps if they were real usability enhancements, then people wouldn't complain.
udev, hal, and d-bus all use weird, esoteric, bizarre config file formats that no sane person can understand. XML for a human-editable config file? Seriously?
networkmanager keeps a completely separate configuration database from the OS config files, leading to two separate (more in the case of wireless) places to configure things. Perhaps on RedHat systems, where /etc/sysconfig/ is a horrible mess, this is an improvement, but on Debian system with /etc/network/interfaces, it's not. Then you add in all the different GUIs for it, and it's most certainly not a usability enhancement.
pulseaudio is yet another layer on top of a broken audio foundation. Adding layers does not make things better, it just hides it a little longer.
Having X on tty1 is not hard. Just edit /etc/ttys to disable all the virtual consoles except 1. Done. I do this all the time, to only have 4 virtual consoles, and X on tty4 (ALT+F5).
Compositing has some uses, and can be helpful for accessibility, but not sure how that can be a usability enhancement.
kernel modesetting may be a good thing, so long as the X side of it is done in a portable way (ie don't make the modesetting/using API Linux-specific, there's more to the free Unix-alike world than just Linux), and Xorg doesn't become locked into only working on Linux. If that happens, I'd call it anything but a useability enhancement.
Why do you care? Do you need to edit the config files? For me udev, HAL and D-Bus just work, as they should.
Next up: "Computers are weird, esoteric and bizarre. They operate in base 2 instead of base 10? Seriously?".
All this complaining about HAL, udev and D-Bus are only from people who for some reason think that poking in /etc is cool.
Why do you care? Do you need to edit the config files? For me udev, HAL and D-Bus just work, as they should. "
Yes, actually I do need to edit the config files, especially for HAL and udev. udev has a horrible habit of locking in interface names to MAC addresses, and depending on the kernel version will re-order the interfaces at boot. Very annoying on our servers with a 10/100 and 2 10/100/1000 NICs ... udev keeps flipping which one is eth0. It's really annoying when you have to replace NICs in systems as well. When there's only 1 NIC in the system, it should always be eth0, not eth0 one boot, eth1 the next, and so on. If you're going to use generic interface names like ethX, then don't rename things behind my back.? "
What do you do when it breaks? What do you do when you can't get into the GUI and need network access? What do you do when you have to boot to single-user/safe mode and need network access?
There's nothing wrong with having a GUI to configure/manage the network setup ... so long as it doesn't break the non-GUI tools that do the same.
Look at apt-get, aptitude, synaptic, adept, and PackageKit for how this can be done right. NetworkManager is just plain wrong.. "
Which is fine ... but don't break the non-GUI tools in the process. Why is it so hard to grasp that?
Would it really have been so hard to have the GUI write out the config to the normal text files?
People like you are part of the problem. Your answer to a broken system is to say "Paper over it with a simple GUI!" Simple GUIs are great, but a simple system is essential.
What if something breaks and the GUI no longer works? If the underlying system is hard to understand, the barrier to fixing is high. "So what! Normal users call tech support!" I hear this all the time. Where does the mythical tech support guy learn how to fix it? Shouldn't we make his life easier, too?
Using a simple GUI that papers over complexity is fine for an end user... but what about a third party developer? Making the underlying system complex maks writing software for it complex and bug-prone. The 'simple' GUI is not simple to write or maintain if it has to work to overcome the complexity of the system. Sure it *can*, but if the system can be improved it would make maintaining the simple GUI easier, freeing developers to write other useful things, reducing bugs that users encounter while using the simple GUI, improving life on earth.
A better question for you and people of your ilk is "If the user doesn't need to see it or understand it, why can't we change it"? You say that it's fine because the simple GUI works. OK! We'll leave the simple GUI in place. Now that the children and end users have left the conversation satisfied, can the adults talk? How do we make the system better for the people who have to deal with it.
A benefit to a system that is simple to understand is that more people will learn it and come to understand how the things they use work. Education of this nature is never a bad thing. Keeping things that could be simple complicated creates a priesthood of the enlightened. It's far better to make enlightenment so easy that anyone can attain it, freeing the masses from a potential oppressive authority.
One of the big problems with Windows is that some parts of it cannot be understood by average geeks, much less by average users. It remains a mystery. This gives people the false impression that they're stupid, that computers are magic, that some things cannot be known. None of this is good! Yes we could operate Linux this way, but why would we want to?
EDIT: s/ave/have/
Edited 2009-05-31 13:18 UTC
I think you all need to take a step back and get a grip on reality. Its not macho manhood that leads me to believe that most people shouldnt be mucking around in their filesystem. Its based on pure experience. Hell, look at dos. That was about as simple as you could get. And people still screwed it up. You seem to forget that under Windows there is a whole slew of crap that doesn't make any sense to the common user either. Its not meant for them. Just like anything outside /home is not meant for the user.
Also, do you really think that if GoboLinux became a mainstream linux that people wouldn't start putting things in different places? The only way to enforce a standard is take away the freedom to change it. That kind of goes against the whole idea of free software. As it is, a standard is just a suggestion. And most creators chose not to stick strictly with FHS. Why would they stick to Gobo?
From
Do you want to change the standard?...
Well, you could say that the W3C recommendations are just suggestions, but you won't make many friends among web developers. Wouldn't it be nice if there was no standard data format? Then again, perhaps you really like the thought of being locked to a single program/vendor.
I could go on, but I'm pretty sure you got the point. Hey, even standards like the FHS might seem futile, but it got a goal : increase productivity and interoperability. If developers were respecting it (and the standard itself was more up-to-date), you wouldn't have to waste your time finding paths in different Unix-based/Unix-like systems. While learning to do the same thing in many ways develop your learning skills, your capacity to adapt to different situations and even your intelligence, there are times when it's just stupid.
Again, just think about it. Imagine having to use 4 or 5 different browsers, just because there was no HTML standard... Perhaps that isn't what you meant to say; that's why you have to be careful when stating such bold claims.
Edited 2009-05-28 23:20 UTC
I was not implying that having a standard is a bad thing. There are many places where it is beneficial and makes things work. With the FHS, its a standard that is loosely followed by almost every distro. I don't think it would work being strict as Thom advocates. As for the end user, I think they are the last reason to make changes as the average user should not be mucking around.
I understand where Thom is going with the idea though. And that goal is more user friendly computing. Well, that will happen when the computer becomes an appliance. Like a Tivo. A Tivo runs linux yet it doesn't expose it to the end user. Now the good thing about that is ease of use. The down side is that it only does what it was designed to do from the beginning. People right now are used to being able to download what ever crap they want off the internet and expect their PC's to run it. They will not want to give up that power even though it causes them problems every single time. But eventually most people will end up using a thin client like device that just does the basics and is free from malware and viruses. Except for us geeks, we will always have the high end workstations sitting under the desks.
I agree with the article. And I think GoboLinux is one of the best under-rated distros out there.
However there is one issue I have with the directory layout -- Capitalization. Personally, I prefer all lowercase. I don't mind capitalization as a visual style, but I don't want to have to bother distinguishing between the two for the computer's sake. Here again I think there is a divide between computer geeks and regular people. If you're Grandmother sees a folder called "mom's stuff" and later sees one called "Mom's Stuff", she isn't going to be thinking like a UNIX guru that they are different. She's going to naturally think they are the same.
The only way a new and improved FHS will come about is if Ubuntu, Debian and perhaps a few other big players get together to make it happen. That would be great, but I'm not holding my breath. More likely a new operating system will come along to supplant Linux altogether that will have a better structure from the get go. (AROS?)
Debian wont do it. They are far too stodgy (and that's a good thing!). Ubuntu might, in the name of friendlinss, but they might not in the name of compatibility.
A new distro could do it. The best bet would be a company like Red Hat creating a secondary distribution just to experiment with the idea; sort of like a research paper done as an OS release. RH has the pedigree to get some notice and attention, the resources to make it happen, the experience to not make so many of Gobo's mistakes.
It would take years and would never fully replace the traditional FH, no matter what the improvement. Eventually through the grand tradition of 'if it works better it wins' the sheer usefulness of an improved FH would gain it devotees, mindshare and eventually dominance--at least among workstation and desktop users.
"A new distro could do it. The best bet would be a company like Red Hat creating a secondary distribution just to experiment with the idea; sort of like a research paper done as an OS release."
AFAIK no-one at Red Hat has the slightest interest in this. Someone posted a similar Grand Proposal to fedora-devel lately to little enthusiasm. RH developers interested in improving Linux as a desktop operating system (and we have a lot) are generally more interested in doing things that are really useful in obvious and concrete ways than re-organizing the entire filesystem because someone thinks it'd be more 'elegant'.
From a previous article I wrote:
--- [1],.
[1]
I'll try to be diplomatic in my response to this, because I actually agree with you on the fundamentals (i.e. FS layout can be improved) - but what you say here literally makes the hair on the back of my neck stand up...
I'm a developer - I don't do OS work, but I know enough to appreciate the issues involved. Developers do NOT build layers to hide ugliness - they build layers to allow for change. Its called abstraction, and it is a GOOD thing. You layer abstraction upon abstraction so that, hopefully, if you did things just right and foresaw all the corner cases and your fingers were crossed just so, then you can change/improve one of those layers without bringing the whole thing down on your head.
Developers don't set out to build unwieldy monsters, but they almost inevitably do. Any non-trivial piece of software that is designed to satisfy an active user base will eventually become a monster - that isn't opinion, its fact. As a developer, learning to accept that is wisdom. Sometimes its admittedly poor design choices, but most of the time it is simply the act of extending something in ways you did not intend to. Developers can not see the future, although people expect them to be able to.
The point is the only way to construct a file system that is both simple to end users AND logical and functional for a developer AND can withstand changes over time is to build an abstraction, either for the end user or for the developer, preferably both OSX tries to do this admirably I might add - and you dismiss it as a mess.
Trying to "hardwire" a simple design that will serve both audiences and that will stand the test of time is an exercise in futility. Read that again and remember it in 10 years when you nod your head and agree with me.
As the previous poster stated, software developers don't make layered code just for the hell of it. What happened to hardwired computers? The were replaced by programmable ones because it wasn't practical to rebuild the entire thing just to change the algorithm it performed. Layered code isn't always about hiding the uglyness: Jokes aside, it's a feature, not a bug.
And you can spend as much time as you want designing the perfect system, making sure it's as simple as possible, but when you finally give the design documents to a software developer, he will most likely implement it with several layers of abstraction. That way, when you find a mess up in your design, there's a chance of fixing it without breaking stuff on userland. That's the big difference between design and implementation.
Regarding FSH, yes, it could be improved quite a bit. But is it really worth the massive effort for something the user shouldn't be messing with in the first place? The fact that sometimes he/she has to do it is a different matter: Blame the userland tool in any case. The fact that network-manager will revert some of my settings (made through the gui) after some time is ridiculous, yes, but it's network-manager's fault, not FSH's. The tool isn't performing the task it's supposed to perform.
But yes, we agree, there are quite a few cases when extra layers of cruft are added just to hide the uglyness of the lower layers. PulseAudio being a prime example.
On the other hand, oversimplifying things can lead to painful situations in the future.
Edit: I forgot. Sometimes, developers are accused of reinventing the wheel because, at some point of the development, they decide to rewrite the codebase. And that's unfair: Most of the times, that's done just to adapt the code to the new requirements, because the users are always demanding new features / tweaks which the original codebase wasn't designed to support. And that's fine, software needs are always changing, but it's just impossible to come up with the perfect design, specially when the requirements change once the design got implemented.
Edited 2009-05-29 04:30 UTC
BTW, from reading the Gobo author's stuff, he's clearly thought carefully about the issues, understands most of them, and knows what he's doing. Which is fine. One of the benefits of Linux is flexibility, after all. Personally I think the Gobo system requires rather a lot of effort for not much (if any) gain, and I'd rather spend that effort improving other things, but hey - maybe we'll all agree with them in the end.
What I get tired of is people who jump in without knowing what the hell they're talking about. Like the type the Gobo author specifically identifies himself:
."
I do believe Mac OS 9 and earlier (the classic Mac OS) got the filesystem structure aspect mostly right.
ROFLMAO
2 words: RESOURCE FORK
"WTF, I can not even begin to count how many times I have to open up the Software Management in Yast to see where the f**k some god damn program installed files. Then I get the joy of having to go through numerous directories to get a job done that would be much simplified if it was installed in "Programs"."
What job? What exactly is it you want to do? I can't really think of many cases where our typical under-informed end user would care where a program's files went, or would have anything in particular he needed to do to them. What's your use case?
"On Windows, if I install just about anything, I know to go to Program Files if I need to look at a readme, make changes, etc.. THAT is intuitive thinking. Again, pretty damn easy to figure out "Programs" are located in "Program Files"."
...except for the bits they have to install to \Windows\System32, which as someone else already noted, is a godawful mess. Or the configuration data that gets installed within your personal profile directory (Users and Settings or some such, they keep moving it around), or possibly to the registry.
Hey, starting to sound a bit like that *other* filesystem layout now, isn't it?
In every major distro, documentation files that are meant to be accessed outside of the app itself get installed to /usr/share/doc . That's a perfectly sane system.. "
Don't forget Local Settings\ also in the user's directory. One of the two (App Data/Local Settings) is a hidden directory as well.
Ultimately, these issues will never be resolved as long as file systems are organized in a hierarchy. The primary disadvantage of hierarchies is that they are only capable of sorting data based on a single factor.
People that prefer the typical UNIX layout like their files sorted by type while those that prefer the Windows/OSX layout want their files sorted into logical groups based on the owning application/library.
Both are valuable views on our file systems, yet we are forced to choose one.
If file systems were to use some sort of relational database instead, we could easily ask for specific views; for example, a list of all the files used by the application "Firefox" or a list of all local configuration files.
We wouldn't even have to abandon the FHS, because we could provide "smart folders" based on queries into the database. So /usr/local/etc would simply refer to the list of all local configuration files referenced above. Similarly, something like /apps/firefox could refer to all files used by Firefox.
I realize something like this is unlikely to happen, but if it did, it would be a killer feature for me, and would make it really difficult to resist switching to Linux full time on my desktop.
The GoboLinux approach is somewhat clever, but "more or less handled" by a ton of fragile symlinks is not really interesting to me.
Plus, it only addresses the two specific scenarios I mentioned, and completely disregards the possibility of custom queries on the file system.
You should probably check out the excellent metadata capabilities of the BeFS. In history, and in the sucessor platforms, mind ... *sniff*
Oh for the days when my music library was just a folder in Tracker and not some massive fragile thing iTunes tries to keep in memory ...
Sorry, where was I? Oh right, posix extended attributes might help you get most of the way there, too, if anyone started using them for anything much.
The file system style and/or locations of files doesn't seem that important. The thing that always is a struggle for me is "How am I going to configure this application?" When I used MS Dos and Win 3.1, I had to page through the .ini files. In Win 95 and up, it was the registry and system32 directories. In Linux it's the /etc directory... As a full time Linux person, I have adapted to /etc for configuration of programs... But it's very unfriendly... many config files are not human readable and have little to no easy documentation. In comes xml... just one more step, use the web browser for easy to configure applications. Use Nautilus... Add another frame or something that shows an application's configuration options... MUCH more useful then changing the file system style or locations or names of directories... AND MUCH less confusing for developers..
It's not worth quibbling over such a distinction. No matter what name you choose, there will be exceptions unless you just want to call it 'stuff'. 'bin' is short, concise and easy to type..!
It's actually 40 YEARS OF ACCUMULATED WISDOM.
I can purge my system of locally compiled software by
simply deleting /usr/local whilst simultaneously causing
no damage whatsoever to the packaged software.
Your statement is pure, concentrated ignorance.
On Windows, if you think for one second that you can rid
yourself of all traces of software by using "Add/Remove"
AND/OR deleting its folder in "Program Files,"
that is just more fantastic ignorance.
You may be right - it's those darn developers -
they should immediately start thinking like
lawyers, prostitutes and/or carpenters!
On second thought, wouldn't computing be better off if
we just eliminated those pesky developers altogether?
All of my Linux systems have both.
And I actually use both on a daily basis.
I have and enjoy the best of both worlds, so what's the big problem?
Please, what is so broken that needs fixing?
I'm going to go ahead and assume that ACCUMULATED WISDOM is not the same thing as accumulated wisdom, since you put in the effort to mash the shift key long enough to differentiate them.
simply deleting /usr/local whilst simultaneously causing
no damage whatsoever to the packaged software.
Yes! Everyone I know has just been dying to locally compile a huge collection of software and then purge it all in one fell swoop. Thanks.
I heard that the expulsion of "pure, concentrated ignorance" is a symptom of swine flu.
On Windows, if you think for one second that you can rid
yourself of all traces of software by using "Add/Remove"
AND/OR deleting its folder in "Program Files,"
that is just more fantastic ignorance.
I searched and searched, but for the life of me, I cannot figure out what you are referring to in my post. I'm fairly certain I didn't mention Windows at all. Perhaps, through the miracle of the internet, you have contracted my swine flu and are expelling some pure, concentrated stuff of your own.
You may be right - it's those darn developers -
they should immediately start thinking like
lawyers, prostitutes and/or carpenters!
On second thought, wouldn't computing be better off if
we just eliminated those pesky developers altogether?
Prostitutes? What?
And I actually use both on a daily basis.
I have and enjoy the best of both worlds, so what's the big problem?
This is an example of the problem:
It is absolute madness and is the direct result of trying to shoehorn a modern graphics system into an architecture that was in no way designed to support it.
Please, what is so broken that needs fixing?
According to some fraction of the 1% of desktop Linux users, everything is hunky dory. With numbers like that, it must be perfect.
"This is an example of the problem:
It is absolute madness and is the direct result of trying to shoehorn a modern graphics system into an architecture that was in no way designed to support it.".
Adam, I'd say it's a pretty remarkable feat of engineering, and I did not, in any way, intend to denigrate the work that these developers are doing. My point is that they shouldn't have to jump through these hoops and my contention is that they are forced to do so because there are people who are unwilling to admit even the possibility that some bits of UNIX may be in need of modification or retirement, at least in the context of a modern desktop.
The X developers are smart guys and they aren't ideologically wedded to the X framework. Hell, they already broke from XFree86. If they really felt it was necessary to break things more radically, that would've been the perfect place to do it. They didn't. That should tell you something.
(apologies for any typos, I'm a lil drunk.)
Market Share Trolling - That's Nice!!
Ahh, statistics pulled right out of the arse -
always the last refuge of logical fallacy....
Anyway, back to the grown-up discussion:
I fully enjoy the use of hardware accelerated graphics
AND network transparency every, single day -
all on a filesystem that is *gasp* FHS-based.
What is broken here that needs fixing?
I seriously think that the traditional unix file system for desktop computer operating systems needs some serious rethinking.
Take a look at the bigger picture.
What does the FHS file system revolve around? Programers. Only software programers. Matter of fact, every stitch of logic in an FHS file system comes from coder / programmer centric thinking.
A better generalized name for this type of file system is a "programer's tree".
I think so far what I have written is pretty impartial.
IMHO, a "programer's tree" is a useless layout except to those who code. It is a coder's file system meant for coding purposes. Desktop orientated computer users have little to nothing to gain from it. A "programer's tree" doesn't concern them, because it wasn't made for them, and that's a real problem in a desktop oriented system.
It's a case of mismatched identity, the system trying to pretend on the surface it's one thing (a user centric desktop system) when in reality it's simply a coders workstation, hacked, and wearing a desktop coat.
The underlying issue is... why should a desktop oriented computer have a "programer's tree" in the first place? Why didn't more people ask this question from the get go when GNU/linux went to the desktop? Probably because the majority of them were coders, and (like most humans) don't shift their perspective right way when the situation calls for a new one.
A user centric desktop file system should be built around and logically extend at least partially from a user-centric point of view. IMHO, this means, among other things, that as a whole it should represent the organization of data on physical devices first and foremost.
IE make the top level directories the physical devices. Windows already does this (albeit in an archaik fassion with letters A: and C:), and MAC OS X does it almost perfectly; ie everything starts with Hard Drive, CD-ROM, Flash Drive, etc. Non-coders (ie most users) can grasp their hard drive far more intuitively since folder names are not heaps of abbreviated coder terms, but a smaller set of simplistic, well-organized folder names which anyone can appreciate... Applications, Libraries, Users, System etc...
Making the top level directory / in a desktop computer is completely non-applicable logic. While useful in non-desktop oriented workstations and servers, orienting programer centric folders with a top level / in a desktop oriented computer computer is a unintuitive misfit of an implementation, taken from an entirely different scenario of usefulness and placed in an environment where it just doesn't belong in the first place.
Edited 2009-05-29 00:53 UTC
I am not really sure what you are getting at. The user's files are not the topic of this discussion; the system and program files are.
Every modern desktop environment (Windows, OS X, Gnome, KDE, XFCE) shows the home folder (well, My Documents in Windows, but, close enough), a list of devices (with the minor difference that they have drive letters in parens like "(F:)" after them in Windows), and the contents of the user's desktop as the most directly accessible files/folders. That sounds like what you are asking for -- and it is already there.
... and geeks still talk about directory names.
Something must have gone terribly wrong at some point.
I actually wonder whether there is a real need for a hierarchy of "files" at all (not to talk about "programs" with their stupid names and brands, "windows", "mouse pointers" and all the unbelievably unnatural and, after all, inconsistent metaphors to "talk to" a computer).
I don't want to troll and I don't have solutions, I'm just asking myself why on Earth I'm after those ridiculously retro devices everybody owns these days.
I do recognize the hard work and brillant ideas people have had, but I really can't stand the smell of idiosyncrasies and rhetoric arguments, which in many cases are only useful to make the whole thing even more confusing, as an advantage to "specialized" workers/companies.
Some people do earn from other people's ignorance, open source or not, you better keep it in your mind!
Just see how the work and ideas of many people these days gets constantly and arbitrarily ridiculed on so many levels: from Gobolinux to Syllable and Plan 9 just to talk about OSes, or the Archy ZUI, Netsukuku or database-like "file systems"... stuff that could really put an end to parts of this whole huge mess IMO.
What we have is really the best we can do? I highly doubt it.
Maybe we need something like an Hippocratic Oath for the IT industry, and/or an artistic/handicraft approach to technology development, rather than new flashy standards talking about the same old crap each and every time.
As a side note, to be less OT, I do prefer the Gobolinux approach, or even better, a sensible default and the opportunity for the user to change the file system structure as he/she likes most without breaking software.
Computers still only understand binary bits... EVERYTHING an OS actually does is extremely difficult for any human to follow... So what does it matter whether the root folder/directory/location is called / or "beginning of file system"... What is important is that the file system and/or OS become easier for the average end user to install and configure programs. Changing the names of every important location involved in a Linux based OS will break many programs and take years of code revisions. It's really not worth it... As pointed out MacOSX does a really decent job of obscuring the "actual" underling filesystem from the average user. An average user could install a similarly obscured Linux distro... no real need to change what's not really broken so that it is really broken... and... without a meaningful programmer centric file system Linux would suck to develop apps for... and.. programmers make the modern age possible...
I'm mostly with cb_osn, prime107, and even - oddly - daste, who've all nailed it (although in daste's case he doesn't quite realize it).
For a lot of people, it seems like they're attacking the filesystem to solve a problem, except adjusting the filesystem layout isn't really the way to solve it. If you found your cellphone hard to use for some reason, would you bash the directory layout? Probably not - even though it probably *has* one, at some level, and it's likely a mess. Why? You don't really interact with it.
Ultimately, everyone designing operating systems today is trying to avoid typical use cases having to interact with the filesystem directly. It's not necessary, and if we can really properly achieve it, *that* will be a significant benefit to usability. Trying to rearrange a static filesystem into some kind of perfection that works for everyone is, as cb_osn pointed out, essentially a futile effort. It makes sense to say that what we have now works well enough and serves its purposes well enough that time spent trying to refine it without redefining it is mostly wasted. Work on far more radical changes, which daste mentions in part, is actually more useful. And daste, you're wrong to suggest that people ridicule things like Plan9 - most developers understand that it's good to have people who spend time thinking, on a not-currently-practical level, about how we could make fundamental changes to how we design software, to eventually produce big improvements. I suspect that the future of desktop operating systems (as long as they continue to have a future...) will be that the layer you interact with for most purposes really doesn't come into much contact with the underlying filesystem, just like it doesn't on your cellphone. And then it won't matter much how the filesystem's laid out.
would you listen to yourself? rearranging the file system is futile? we're in a GOBO LINUX THREAD. GOBO LINUX. the distro that reorganized the file system successfully. hello???
you guys are saying that FHS is complicated, therefore it is hard for normal people to use, therefore fixing FHS is not worth fixing because file systems are hard to use. holy crap. talk about the the cart in front of the horse.
IT IS POSSIBLE FOR THE FILE SYSTEM TO BE EASY TO USE. THAT TRAIT IS VALUABLE TO USERS.
Have you ever changed the engine in your car? Have your ever changed the oil in your car? The tires? Filled up the brake fluid? Filled up the engine oil? The gas tank?
Some of those are easy enough for normal people to do. Some of them are easy enough for nerds to do. The more easy they become, the more value more people get from the product in question.
Have you ever fixed a vacuum cleaner hose with duct tape? Have you ever glued a broken toy back together? Taken apart a pair of headphones to fix them? Tried to take apart a complicated pair of headphones and been UNABLE to fix them?
There is no reason why products should be complicated when they can be fixed to be NOT complicated. Understand yet? Do I need to explain more for you?
It reorganized the filesystem. Fine. What did it achieve? What do Gobolinux users achieve that users of other distros can't?
Generally when distros do something really useful...they become very popular and you hear a lot about them. Gobo hasn't. All I ever hear about it is that it reorganized the filesystem. Well, er, good. I don't hear much about how, in concrete terms, that's helped people do things better.
The achieve a HUGE improvement in one part of the overall UNIX design.
Really? This is how you think it works? Then Windows must do something really useful...
If it's not apparent to you, go read their documents.
They demonstrate how things get done better with the reorganization.
But even a simple 1% simplification, generalization and elegantization of the overall design is worth it...
I have yet to find ANY non developer type person who has complained about the file system needing to be more transparent to them. From Microsoft users to "new" Linux users (like your 152 year old grandmother), there are very few complaints like... I need a more transparent file system... it's more like this... I click here and I see a picture from my camera... or... I click here and I can "get to" the internet (whatever that means, I never touch the stuff myself)... The fact is Nautilus or whatever is installed in X Windows hides most of this stuff already... and look at the Debian installation guide under partitioning (almost entirely the home directory)... Seriously, anyone who "needs" more transparency in the file system is computer savvy enough NOT to "need" more transparency... It's interesting to note in the comparison of OS and cars that as a car gets "easier" to use it gets more complicated "under the hood"... Ever try to diagnose an emissions problem on a 2008 model car with only a wrench... good luck! A carburetor is a rather simple device that works well and is fixable with basic knowledge... a fuel injection system is rather complex incorporating thermodynamic calculations with intake airflow and temperature and engine speed and many other factors being performed instantly and continuously... Complex systems under the hood hidden by a "layer" or "layers" of abstraction is the standard solution to the creation of extremely useful systems...
Then you do not know enough people. Get out of your server room more.
Heck, even do a simple google search for complaints of CASUAL users of trying to install or uninstall or edit this or that thing and needing access to some files in the filesystem, but being unable to find them.
Like, "where's this foo.ini file the documentation talks about" etc.
Being able to make something more coherent and re-design an 30 year old legacy design to be simpler and more efficient and remove legacy accumulated craft and not doing it IS A CRIME AGAINST COMPUTING..
Sheepish adherence to backwards compatibility (and historical craft) is what made Windows an ad-hoc mess, and what keeps UNUX/Linux an adhoc mess..
It can't possibly be because people need to use those features that have been built in and refined over the years, can it? Of course not, there is absolutely nothing that computers have been used for over the last 40 years that they are still used for today. No, in the world of "tomorrow, Today" they only need to look pretty and check facebook, right?
To Hell with those 1000's of deployments out there with /usr, /etc, and /home seamlessly mounted over the network!!
To Hell with those 100's of commercial vendors, 1000's of System Administrators, 10000's of certified professionals, 100000's of package maintainers, and 1000000's of developers!!
You know better than all of them, right?
Who cares if it screws up compatibility for embedded hospital equipment, assembly line machinery, and the power grid??
Damnit! We must make it easier for
Grandma to grep the filesystem, right?
The FHS is the only filesystem layout design which is sane for now. The main problem about it is the bad developper practice.
The idea of FHS was to have layout where the command ´rm -r $PREFIX/bin/$i $PREFIX/lib/*$i* $PREFIX/usr/*/$i´ will help You getting rid of the software package You don need, and adding ´$PREFIX/etc/$irc /home/*/.$irc´ will purge the package entirely. Everything got worse when four things arrived:
1. the ´/opt´ directory, which is the internal inconsistancy of FHS;
2. the advanced GUIs, where all the GUI software respects its own rules (~/.gconf/*);
3. the nobrainer configuration files layouts (~/.config/*);
4. conflicting convensions (eg. /etc/foobarrc, /etc/foobar.conf and /etc/foobar.d/*).
All these problems have there solutions:
1. get rid of '/opt';
2. add special exception for GUI (like the KDE´s '/usr/kde');
3. get rid of nobrainers;
4. deal the one convension (eg. /etc/foobarrc || /etc/foobarrc/* + /home/.foobarrc || /home/.foobarrc/*).
P.S.: It isn't reasonable at all to have a human-readable filesystem layout, because the main (and in many cases the only) reader for this layout is computer. The user reads his home directory.
You have your head on straight.
I would quibble about your "nobrainer" bit.
I would support a ~/.config/ as the root for all other config in the user's home directory, especially if it were named ~/.etc/ or whatever the global configuration root is named. This to me makes sense, if for no other reason then I get tired of having to use find(1) to cp all of my config data recursively. cp -a -R ~/.* oops...
Also, while standardizing on .conf or a -rc suffix would be great, you cannot throw out .d directories. They serve a different purpose, you see, and replacing one with the other would be losing functionality. the conf.d/ style of directory is one of the few real, useful innovations to have emerged recently.
I would also say that the GUIs don't really need their own directory structure rules, as you allow. This, to me, is a cop-out of the sort that brought us /usr/X11/, which is at long last finally dead. Better to say that if the GUIs want something that cannot be provided consistently with the existing system, let's amend the system as slightly as possible to add it (without arbitrary exceptions! They have a way of becoming the norm). I suspect few GUIs actually *need* their special structures.
As to your postscript: It *is* reasonable to have a human readable filesystem layout to a certain extent, because the computer after all does not actually care what something is called. Thus, /cfg/ is no diffferent from /etc/ except that it is more human readable. FSH revisions which make things less computer readable are questionable, but ones which improve human interaction and do not interfere with the computer's ability to use them are fine by me.
1. Running "ls -d /etc/*.d" on my Ubuntu installation shows, that no special idea is included here. And I don have any "conf.d" as I had in Gentoo (I was always amused to see there some loosy configuration files that almost instantly either reffered to oother config (as /etc/conf.d/sshd) or simply replaced some foorc's. So what is the sacred sense of these foo.d's?
2. the ~/.config/ directory could happen to have sence if three factors happened to be in place:
* ~/.config/ was a convension - this is not happening;
* the configuration files really needed to be persistant - effectively about half of the setups are irrelevant when switching from one environement to another;
* the configuration files of different versions of software were compartible - not the case.
As a matter of case, You need only some of these, when You migrate, and You really need to get rid of most of them if You want to avoid the bloat.
3. Changing the human-unreadable "/etc" to human-readable "/cfg" (as in every other case with FHS) is completely useless - the user, that know nothing about the content of these direcories shouldn´t be even entering them. Furthermore, it is even handy to have cryptic directory structure to make the human reader aware of the fact that he should get some info before he does anything with his system. Renaming the problem doesn´t solve it.
4. The last thing: I really doubt, that a user can´t understand FHS with its ridiculous mnemonic load, if he understands how to get to the file browser. And even if I´m wrong, I believe nowdays at least half of linux users don´t really know, that thay even have the "/etc", "/bin", and atc. directories in there system.
May I presume you are familiar with Apache2? At least as it is configured under Debian. The idea of conf.d directories (and here I use conf as a variable) is that when there may be multiple configuration files or scripts to process that might be added and removed independently of any central authority. Another Debian example would be under /etc/network/if-up.d/, scripts run when an interface comes up. I expect most distributions should have a pam.d, and of course nearly everyone has an init.d or rc.d. The nomenclature is a bit obscure and rather misleading, but it is distinctive.
With regards to ~/.config/, I don't propose it for any of the reasons you imply. Preserving config data between environments is not very useful and is doable now (see dual booters who mount the same home partition as an example). I'm not sure why configuration for different versions makes a difference here. Does ~/.config/.emacsrc imply a cross version compatibility that ~/.emacsrc does not?
What I want primarily is the non-practical benefit of orderliness. I hate having a zillion directories and files in ~/ that I do not maintain manually. Yes, most of them are 'hidden', but they're there. And I've noticed a disturbing tendency for some programs, notably *step related ones, to litter non-hidden directories all over my $HOME.
My other desire is for backup purposes, which I mentioned before.
I can propose scenarios in which you tell a user "Just don't mess with ~/.config/", which is easier than saying "Don't mess with dotfiles. You know, files starting with a dot?" or, on a support forum, "mv ~/.config /tmp/config.backup" as a way of testing whether something is a configuration error.
We disagree here. You say the ignorant should not proceede, I say the ignorant should learn. You say the name is irrelevant, so keeping /etc is fine. I say the name is irrelevant, so changing to /cfg is fine. There may be no practical benefit, but I believe in the existence of some fringe benefits.
No more do Windows users know they have a \windows\ or a \system volume information\. I don't care about those people and I am not interested in helping them. The fewer people are aware of the underlying structure the easier it is to improve, with fewer negatives, and the more reason there is to do it.
If you can't see a use to renaming e.g. /etc, then can you cite a down side? Obviously familiarity will be lost, but that is not much. Standards compliance goes out the window, but that was always a given. Most programs don't hard code /etc/ path references, AFAIK, most users (as you say) don't even know /etc/ exists now. What is *worse* for those who know and use /etc/ right now to having a new name? If it is not much worse for them then all I have to do is show that it is much better for *someone*, *anyone* and the change is justified.
OK, may be we could have a choice here?
I have read the above posts and gone to the GoboLinux site to read a bit more there. As I understand it, (and I'm an intermediate-level user not a developer or expert) is that a massive change is being proposed to "fix" the Linux file system. Perhaps my understanding is deficient, but what I have not seen is a demonstration that the file system is broken. Why fix something that is not broken? The Gobo developer's remarks (which someone linked above) did not seem to be a call to for a file system revolution, either. Those with the need to muck around in /etc, /usr/local /boot or whatever should take the trouble to learn what is where, and why. If not... well, c'est la vie.
Someone who is really interested will take the time and make the effort to learn. I knew 0.000 about Linux, BSD or any other any 'nix till I was 52 (7 yrs back), but learned enough to function comfortably in Linux and semi-comfortably in FreeBSD -once I made the effort.
The idea that ordinary users would learn more about their "confusers" if only the O/S file system layouts were revolutionized seems implausible. As others have pointed out above, most folks just want the damn box to function predictably-just like their toasters, and have no more interest in O/S internals than toaster internals. I have a friend who is a reasonably proficient Windows user, who has reformatted a hard drive and reinstalled Windows + drivers more or less from scratch (have even 1 in 100 Windows users done this?), but did not know how to delete a file without it going to the Recycle Bin first. That is an above average user.
Interesting idea, but the point really escapes me. Putting xorg.conf .xinitrc or menu.lst in a directory with a different, longer name just makes for a lot more typing if I'm at a command prompt.
Fails for me. YMMV.
People do not respect the history of computers anymore?
More than anything else, this proposition would be a change because of change. Sadly, the new mantra of usability is used to promote even this nonsense.
Let's replace punching assembly code in cards with abstract languages and keyboards while at it.
(What do you gain by respecting the history of UNIX? [other than making old people feel secure.])
Please do some reading before responding.
Joel: Why are the Microsoft Office file formats so complicated?
Joel: Things you should never do part 1: start over:
Both carefully explain the value inherent in old, complicated, successful software.
More than anything else, this proposition would be
a change because of change. Sadly, the new mantra
of usability is used to promote even this nonsense.
Let's replace "cp" with "copy" and "ls" with "list" while at it.
+1 !!!!!
"Those who don't understand UNIX are condemned to reinvent it,
poorly." ~ Henry Spencer
OSX uses FHS, but from my understanding, applications are usually installed in a specific application folder rather than having individual parts of it moved to the FHS directory of choice.
I don't see any reason why we can't just append the FHS to include an applications folder (/apps) than is for things like GUI applications like /apps/firefox/ and let things like CLI binaries remain in the current FHS location.
I hate trying to track down bits and pieces of an installed application especially when I stray from using the standard package manager to install said applicatiuon and I am not able to check the package manager database for it. This would help solve that.
For the people that are saying people "don't need to know" where anything outside of /home is, please consider that most people fall somewhere in the middle of the spectrum, not at the ends.
I have yet to meet a single Linux user that never tried to dig deeper than files in /home, so for the sake of sanity could we please stop generalizing the mythical "user" in this way?.
Agreed on Linux users and the general wealth of computer savvy people who brave the Linux world... However, let's get to the generic computer user... Most of the installed base of the world's desktop computer users are Microsoft Windows users. During the DOS days Microsoft users were savvy computer people. Now Microsoft users generally know nothing about computers. I have many friends who use computers to play Freecell, write documents, view pictures and videos, and use the internet. They don't care about ANYTHING else. They think I'm a computer GOD because I can install a new application on a Windows computer. They would NEVER EVER attempt such a tremendously complicated task... I really am not joking. And so, if GNU/Linux really wants to break out of the developer world, application developers need to realize that the APPLICATION needs to present the user with a friendly "intuitive" interface and lead that user "by the hand" to where the user accessible data is stored... The FS need not be changed, nor muddled with at all... IF the FS was broken, then invest portions of the limited programmer resources to fix it...
Example... A few months ago someone at work sent around an email to everyone indicating that if you go into the preferences in Internet Explorer you can actually delete the temporary files that have gobbled up all your hard drive space... Is this problem an FS problem with Windows, a user problem, or an application problem? It's an APPLICATION problem... the application developer did not inform the user of where the data was and how the stored data could affect system operation.... The example also shows the technical level of the average installed base of computer users.
Edited 2009-05-29 05:42 UTC
Your comment only further reinforces my point. You state that the windows users you know are idiots that never do anything outside of basic tasks. What you overlooked was the fact that they are not Linux users, you are.
Most the people who install and evaluate Linux but decide to keep booting Windows are far more like you and me then the people that view us as guru's.
I think there is a large number of hobbyists out there who more accurately fit the profile of a potential Linux user than the windows users you described.
I have met /thousands/ of semi technical users IRL who are not just clueless morons who have installed/used/evaluated Linux at some point but decided to keep booting windows for varying reasons.
Maybe your experiences are different, but the majority of the people I know who regularly use a computer are also able to point and click through a windows software install.
If you are designing a Linux distro with idiots in mind that cant click next > next > finish in a windows software install and ignoring hobbyists you are doing it wrong. It is that simple. For the love of god, can we drop the idea that Linux users don't need to explore outside of /home?
For home computing, user = administrator. Your "admin" installs applications on your home desktop for you like your dentist brushes your teeth for you every morning.
Agreed.
To put it more bluntly: the constant aim to lure these imagined idiot users will lead to idiotic decisions, which will eventually lead to idiot system that can no longer be used for tasks it used to do well.
That is essentially my (admittedly overblown) fear about these crazy ideas that are thrown because of the perceived problems with usability. Changing the FHS is a prime example of this.
Does anyone remember the car designed by Homer Simpson?
There is a clear rational behind Gobo's reorganization of the file system. Could it be done better? Probably, open to discussion.
"Idiotic decision" is not an engineering term, however, and you do not provide any technical arguments.
What is a fact, and not open to discussion, though is that the UNIX FS organization is a legacy, 40 year old system, and that it was designed with constraints and concerns in mind that do not exist today and/or are not suitable for a desktop system. From shortening the names of folders, to mixing programs in the same directory (/usr/bin) with no concern for namespace separation.
Even the creators of the original UNIX did one better with Plan 9 and fs namespaces. And there are 40 years of FS and usability academic advancements and practical implementations that HAVE NOT BEEN introduced to the legacy unix fs standard.
And again you provide no argument (technical argument) why it is "a prime example".
HUGE FAIL..
I never stated that Windows users are idiots... It's you that have given those people who find computers in general confusing the title... I know PhDs who are afraid of "breaking" a computer and thus will not install an application or update a computer (click on the gold thing in the task bar) without massive amounts of assistance... These users are not idiots. They simply don't understand, don't want to understand, and are generally afraid of the risks of performing tasks on a computer. My position is is the following:
1. The GNU/Linux file system works very well, especially when APPLICATION developers follow the rules for file placement.
2. Anyone who is a Linux hobbyist or Linux developer does not "need" greater transparency in the FS than is already present since the technical knowledge needed to locate "hard to find" files is already well developed.
3. Wasting valuable limited resources tackling a perceived problem versus a real problem is harmful to the overall achievement of real world progress and adoption of GNU/Linux as a general computer user Desktop Platform.
4. The point of changing the FS is muted because there is no way to enforce general adoption of the current rules within the current FS let alone a new FS with "simpler" nomenclature.
5. Stick with the current FS, and develop apps like mad so that GNU/Linux will continue to be better and badder with each release of each distro.
OK, I GUI ham radio app. where does FHS say I put it?
For a locally installed application, compiled from source: /usr/local/bin, libraries in /usr/local/lib, data files in /usr/share/appname/; for a distribution package /usr/ and ditto. It's simple enough for any developer to understand, and the user doesn't need to know.
Hi,
If you have to install things outside your package manager (and please do try to avoid doing that
there are packages to help you do that sanely. One I happen to recall the name of is GNU stow, which will create a folder in /usr/local/stow for each application that you use it to install with all of that application's files.
This is just a mechanism for using the --prefix option of various tools. The bsd ports systems do this as well, which is why apache is in /usr/local/apache on eg FreeBSD (or was last I looked
hth,
adric
If we're going to go down this path we might as well go the whole hog and have app bundles and fat binaries like Mac OS X. I know I'll be shouted down, moderated down and have lies spread about app bundles - people claiming that it 'duplicates' libraries when it does no such thing, or uses static linking when it does no such thing.
The problem with programmers is they took Linux and shoe horned it into a UNIX way of doing thing; I've never heard Linus ever say, "take my kernel and implement it in a UNIX way of doing things". It is the surrounding projects who have made this grasp that UNIX is the ultimate and perfect way instead of standing back and saying, "hey, there are some limitations of UNIX, lets be pragmatic".
Sure, keep the low level directory structure like how Mac OS X has done with the UNIX side of it, but use something better for the user visible portion; user installed applications going in the Applications directory for starters. I'm not surprised if in 10 years time we're still having the same debate because of intertia and programmers who seem to have the brain of 50 year olds with, "back in the good old days we had UNIX, we don't need any of this new fandangled ideas".
new things get into Linux all the time. heck, half the people complain about how stuff is 'always getting rewritten' - PulseAudio, DeviceKit, whatever. doesn't anyone notice the two complaints are completely contradictory? obviously there's an appetite among developers for shiny new stuff - yet only one minority distribution decided to redesign the entire filesystem.?
I don't know a single person here who has complained about DeviceKit once they realised how much of a clusterf*ck HAL is when compared to how DeviceKit is going to be designed. PulseAudio simply left a bad taste in peoples mouths because it was rammed into distributions riddled from top to bottom with bugs with little being asked as to the merit of it when compared to possible alternatives.?
shackles? more of this language of constraint...
Where is the limitation? What is it that Unix systems can't do
because of FHS? - that would be a "shackle"
Are you living under a rock?
Linux is not a "me too" Unix clone -
Linux is THE UNIX CLONE!!
Server dominance plus constantly gaining ground on the Deskop -
The French National Police and the Governments of Cuba,
Brazil, Russia, China, Vietnam and Korea are not just
"sticking with Windows" on the desktop and are not
switching to Mac. Duh - they're switching to GNU/Linux!
CP/M style Drive Letters are almost as old as Unix.
"Will Windows 7 finally throw off the shackles of the Drive Letters?"
ROFLMAO - Give Me a Break.
AdamW, this is what a decent, self-contained application management system with a decent filesystem layout would look like:
There is no system currently available that allows for such simplicity and power at the same time.
The Linux kernel, eh?
So it implements UNIX signals.
So it defaults to a UNIX compliant filesystem.
So it uses UNIX file permissions.
So it launches /sbin/init as Process #1.
"If it walks like a Duck ..."
What are these "limitations of UNIX," seriously??
You need to prove that there is something Unix can't do
because of FHS - that would be a "limitation."
Mac OS X is a broken ENVIRONMENT, period..
The point of view expressed above is so strikingly opposite mine that frankly, just trying to understand the value system behind it comes close to putting me on the verge of seizures. I don’t even kind of relate to whatever leads him to such an utterly alien opinion. Please don’t take any offense; it's just like stumbling across some guy bitching about physical relations with women because he prefers cats. I mean, what the hell do you even tell the guy?
Personally, I’ve liked the apple applications folder for some time. It’s not what I grew up using; I mostly used windows until I eventually started using GNU/linux in my early twenties, several years before I ever tried OS X. So at least I can safely say I have no "initial bias".
On a desktop, why deal with directories and nested executables, when your applications themselves can be self-contained packages which serve as folders, executables, and icon-launchers simultaneously. It removes so many needless abstractions. Installation and uninstallation is a simple matter of dragging them to and from your hard drive; it works the same way you deal with mp3s or jpgs. That’s exactly what I want with a desktop computer.
That being the case, what on earth am I supposed to say to an individual who comes along and complains that the applications are not further sub-divided into individual executables, menu launchers, and generic folders and then scattered across the entire file system? That approach involves too many abstractive layers and offers nothing much in return that’s of any value to a simple desktop operating system.
Sure, it really does make sense in certain operating environments where coders desire coder-centric means of organizing every bit and byte according to file type, exclusive of any other ideal. But what, really, is FHS doing in a desktop environment, where its key strengths are not even needed, and where it sacrifices the kind of desktop orientation it ought to be focused on having from the moment of it’s inception?
I think there is a very real need for traditional *nix, which is based upon otherwise solid concepts (such as FHS) that originated entirely in non-GUI desktop territory, to part ways in a graceful manner with desktop oriented computing entirely. I don’t think that the overarching strengths of these two philosophies overlap well with each other. This, I believe, is where the intense double-sided frustration comes from, when software finds that it simply cannot successfully subscribe to both schools of thought at the same time.
To use a simple analogy, treat traditional *nix like an orange. There’s nothing wrong with oranges, they are tasteful and worthwhile for what they are. However, if you find yourself surrounded by orange trees, and discover that what you really have a craving for is apples, then what exactly is the best choice? Attempt to genetically modify oranges into apples? Or consider planting an apple tree? Does an immense history or knowledge of orange tree cultivation play a role in this decision?
Food for thought...
Quick little anecdote on this topic - yesterday I downloaded Handbrake for Fedora. I noticed the download page had only source or Ubuntu packages, and it wasn't packaged in the Fedora repos already. I also noticed the Ubuntu binary packages were much, much larger than the source - that's odd, I thought..
Yep. Had the same experience. Handbrake is sort of a like a mini Gentoo.....
Perhaps you should look for one damn thing in your 4 paragraph rant that is of concern to -anyone- but coders obsessed with avoiding code duplication. Any one thing whatsoever. It would certainly help all those uninitiated types who download handbrake know what a big mistake they're making.
The -only- ideal you seem to adhere to is avoiding code duplication across the board. Which is why you ended up with an awful 4-paragraph experience. This in turn doesn't benefit most people in any real way. You could instead simply drag handbrake to your applications folder, and be done with it.
Give me a 5mb hard drive and I'll stick with your route. Avoiding code duplication at the cost of everything else might make sense in that sort of situation.
Now consider this. My applications folder contains 55 items. It takes up ~0.01532615 of my total hard drive space (even taking into account the actual binary disc space and not advertised disc space). Roughly one and a half percent of the total. When actual software doesn't even make a substantial impact on your hard drive in the first place, what does it even matter? Next time I install an app, I'm not going to lose any sleep over what code may have been duplicated.
Edited 2009-06-01 00:03 UTC
The point of avoiding duplication has nothing to do with hard disk space. There are two major reasons:
1) So that, when you fix a bug in some code, it's fixed for _every app that uses that code_. This is even more important when the bug is in fact in a security issue. If every damn app on your system had a private copy of libpng, every single one would have to be patched when a vulnerability was discovered in libpng. How does that make any sense?
2) Saves on _memory_. Not hard disk space. Memory. Far more important. If every app has its own private libraries, then even if all ten apps you're running use the same, say, ten libraries, you'll get ten copies of each library loaded into memory. Owch. If they all use the system copies, you'll have only _one_ copy of each library loaded into memory.
This is why shared resources are important. And that's why you can't just forget about them and make every application its own little bundle.
Unix distributions have package managers. They are a fairly effective way to hide the complexity of the directory structure. If the package manager does a pretty good job of maintaining the files for you, what's the point in trying to make it simpler? Don't fix it if it ain't broke.
The genius of GoboLinux is to make the file system itself a package manager. This significantly reduces the complexity of the entire system. You don't need cache files and several layers of programs to manage the files in the file system. When using such a tightly controlled file system, the user feels a solid control over all the pieces of software on his or her computer. (Indeed, there are other approaches to GoboLinux's use of symbolic links, like using a UnionFS-based package manager, which I have written about here:...)
So I ask a simple question:
?"
and again I get handwaving.
kaiwai: ?"
Stirring rhetoric - no analysis. There's no point embracing new ideas just because they happen to be new. What advantage do they bring us?
Thom points me back to , which he knows I read and commented on before. It didn't convince me then and it doesn't convince me know. For a start, it has a gaping hole: he doesn't explain how you separate "System" from "Programs". Aside from this, the benefits he claims are nothing that you can't do perfectly well within the FHS. There's no reason you can't install multiple versions of applications within the FHS; indeed, distributions have packaged multiple versions of the same app in the past, do so at present, and will do so in future. The reason this isn't *usually* done is not because there's something about the FHS that makes it impossible or difficult, but simply that it's sub-optimal practice in creating a distribution, and can have all sorts of ramifications that are best avoided if possible. So it's only done when there's a really good and unavoidable reason to do it. Making it 'easier' (which it isn't, really) by mandating that all 'Programs' (but not all 'System' components, it seems...) be installed as self-contained bundles wouldn't change that.
foljs: "Heck, even do a simple google search for complaints of CASUAL users of trying to install or uninstall or edit this or that thing and needing access to some files in the filesystem, but being unable to find them."
this is useless fluff.
"Like, "where's this foo.ini file the documentation talks about" etc."
It's in /etc , or possibly /etc/foo. There. That was ten seconds of education that no-one ever needs twice. Is that *really* worth the gigantic amount of effort that would be required to convert every major distribution to some completely new filesystem? Do any of the proposals even make it more likely that this user would magically be able to find foo.ini without assistance? I doubt it. How many OS X users go looking for foo.ini files? They like OS X because, generally speaking, they don't HAVE to.
foljs again: "The achieve a HUGE improvement in one part of the overall UNIX design."
You're thinking in circles. I'm asking what exactly *makes* it such an improvement. What exactly about it is, practically speaking, better?
"Really? This is how you think it works? Then Windows must do something really useful... "
When it became successful - around 3.0 - yes, it did. It was a rather better graphical user interface than any other available on PC hardware at the time.
"But even a simple 1% simplification, generalization and elegantization of the overall design is worth it... "
No, it really, really isn't. Making things more elegant is always a win *as long as* it doesn't disturb anyone else. I'll happily rework my spec files for elegance and efficiency all day, as long as what they generate behaves the same as it did before. But if I could make my spec files 20% more elegant at the cost of the app working differently for the user, I wouldn't do it, because then I'm inconveniencing them for my convenience. Wasn't this supposed to be all about the users? You can't eat (or, more to the point, use) elegance. (Never mind that I don't see exactly what it is about the Windows filesystem, the OS X filesystem, the Gobo filesystem, or any filesystem proposed in this thread that's any more 'elegant' than FHS).
There's no hole. My plan is a template. Mac OS X has a separation between system and programs. Windows has it. It isn't that hard. Every operating system would decide for itself what goes where. In the case of Linux, the LSB could implement it.
My plan allows for flexibility and transparency, and the freedom of users to manage their software in a way THEY want - not some method mandated by the operating system. It also reduces complexity by a large degree, because you don't need fallible dependency tools, and you don't require access to repositories - which may not always be readily available, especially in places without internet (and carrying around a disc with outdated repository files is ludicrous).
And I always thought that the UNIX/Linux world was about keeping things simple. Well, I obviously disregarded that thought eons ago, and you just seem to further cement my belief that the Linux world is just as afraid of moving on and true innovation as Microsoft.
Edited 2009-05-29 09:21 UTC
"There's no hole. My plan is a template. Mac OS X has a separation between system and programs. Windows has it. It isn't that hard."
Apparently it's hard enough that no-one's yet done it 'correctly', because both on Windows and OS X, plenty of 'programs' install stuff to both locations. And when they do that, where's the benefit over FHS?
"My plan allows for flexibility and transparency, and the freedom of users to manage their software in a way THEY want - not some method mandated by the operating system."
'Flexibility and transparency' - of what exactly? We're into angels dancing on a pin territory here. How exactly is a system based on the filesystem layout significantly better than a system where the location of files associated with a given program is tracked in a database with a perfectly standard and well-known format (i.e. package management systems)? Especially when it's almost inevitable that the filesystem-based method will be fundamentally broken, because all sorts of programs can *not*, practically speaking, restrict all their files to a single directory, so something else will have to track them anyway?
"It also reduces complexity by a large degree, because you don't need fallible dependency tools, and you don't require access to repositories - which may not always be readily available, especially in places without internet (and carrying around a disc with outdated repository files is ludicrous)."
You're baiting and switching here. You're talking about applications in self-contained, statically-linked bundles, which really has nothing much to do with the filesystem layout. You can perfectly feasibly do this within the FHS. Hell, you can do it within package management tools - you could build, oh, Firefox into a completely statically-linked, self-contained package which didn't depend on anything else, then you could perfectly easily give someone that package and they could install it with "rpm -Uvh firefox.rpm". No dependencies would have to be satisfied, no repository metadata required, no internet connection needed. There would be no need to change the FHS, even if we were all to take hallucinogens and decide that was a really great way to distribute all our software.
"And I always thought that the UNIX/Linux world was about keeping things simple."
This has nothing to do with simplicity. The proposals just look simple because you don't fill in any of the lower levels of the tree, and you leave out bits like /sys and /proc (which would have to exist in some form, even if you rename them just for kicks), and no-one's thought about the difficult cases (Python? Ruby? Tcl?)
Riiight, because no Software Installer in Windows
ever puts files in "C:\WINDOWS" - oh wait, they do!!
Because the backend of ClamXav for Mac OS X doesn't
go in /usr/local - oh wait, it does!!
FHS, by far, comes the closest to actually having its standards
followed - Mac and Windows are just Wishing in the Wind.
If you can't live with the built in package manger, maybe,
just maybe, you've chosen the wrong distro to begin with.
Because centralized packaged software deployment isn't
the next logical evolutionary step - oh wait, it is!
Because other companies aren't all scrambling to repeat the
success of the iPhone App Store - oh wait, they are!!
"Unix is simple. It just takes a genius to understand its simplicity."
~Dennis Ritchie
"innovation" is a meaningless buzzword -
you seem to have it confused with "progress"."
Oh, please, please, try and do that. I could do with a laugh.
Here's the first question - is Firefox a user app or part of the OS?
(hint: it's not as easy as you think.)
Oh, please, please, try and do that. I could do with a laugh.
It's been done, by pretty much every OS out there except the Linux distros.
(hint: it's not as easy as you think.).
Edited 2009-05-29 19:17 UTC
Ah, congratulations, you fell slap bang into my bear trap.
But, to rewind:
"It's been done, by pretty much every OS out there except the Linux distros."
someone already tried that. It won't wash. Other OSes have tried, but they all failed. All sorts of applications on Windows and OS X wind up installing stuff outside of the 'Programs' folder, and often in the 'System' space. We discussed this further up the thread.
."
Aaaaaand therein lies the bear trap.
Firefox is heavily tied to the Gecko rendering engine it contains, and dozens of other apps (on any distro) depend on Firefox being present in order to use Gecko.
Mozilla have been promising to split Gecko out properly for, ooh, years and years now. They still haven't quite managed it. It's now more or less split out as 'XULRunner' - some distros already have separate Firefox and XULRunner packages, like Mandriva - but in practice, XULRunner still includes all sorts of icky bits that really should be just part of individual web browser applications, not the rendering engine.
And that's just the _easy_ example - you can argue against that one by saying, well, it's Mozilla's damn fault for tying their web browser into the rendering engine and not properly splitting it up. And you'd be right. Still, it leaves you with a big practical problem for your nice neat 'elegant' system right there in the single most popular open source application...
Let's get on to some of the hard examples. What do you when an app provides a library that, say, two or three other apps use?
Well, you can call its library a 'system component' and split it out into a separate 'package' (or whatever your system is) that gets installed in /System, with just the binary and graphics and whatever going in /Program. And...that's just like distributions already do with /usr/bin and /usr/lib . What have you won again?
Or you can compile all three apps that use the library statically and keep everything in the /Program folder for each one...but then you lose all the benefits of shared resources. If there's a security problem in the library, you have to rebuild all three apps (in fact, you have to _know_ that all three apps use that library, and that you have to patch and rebuild them). And if you run two of them at once, both will load their own copy of the library, wasting a bunch of memory.
So...where's the win again?
And I haven't even gotten on to the really tricky bits, like...where do your system mail spools go? Where do your logs go? Where does the data you want to serve out via your web server go? (No, it can't just go in the web server's Program directory, or in any particular user's own Settings or Data directories. None of those options makes any sense.)
And...have you looked at how Python, Ruby or Tcl apps and plugins are implemented yet? What do you propose to do about them in this lovely elegant system?
If you want a quick summary of my post: the two ultimate problems with the "let's have a /System and a /Programs directory!" proposal are:
1) It's predicated on the idea that it's simple to split the stuff typically present on a system into 'user applications' and 'bits of the system'. It isn't.
2) It's also predicated on the idea that all applications are simple little independent bundles - an executable and maybe some static data used by the executable. They aren't.
...said like that's some sort of an achievement. "pretty much every OS out there" is distributed by a vendor, in whose interest it is to define what constitutes the OS. In the case of the Linux ecosystem, what's part of the OS in one distro is not (and is therefore an application) in another. Out of 25,000 packages, most would need to have dual personalities, installed in a system location for some of the time, and in an application location the rest of the time.
GNU/Linux _is_ different, because it is an ecosystem not an OS.
While your stupidity amazes me, your ability to withstand thinking about my main points for 2 seconds actually makes my nose bleed.
Edited 2009-05-29 17:37 UTC!""
Oh, and while we're at it - why the hell is the engine under the hood? That doesn't seem very logical. It should be behind a transparent panel in the driver's seat so newbies will know how to get at it. What's that you say? If I'm going to learn enough to tinker with the engine I should be capable of learning that I have to pop the hood to get at it? Tosh! Any idiot can figure out how to fix an engine once they can SEE it, but discovering that you have to pop the hood to find it is just really hard!
the reason why no one uses it is because no one understands it. Users find it hard. i used linux for 2 years. and i still don't know what all those weird directories are for. and apparently alot of developers have a problem with it.
seriously. they need to get rid of it. they used those short names so that a long time ago people could use a keyboard to easily navigate around. now even if you need to use a keyboard theres tab completion. and most people use a gui. so what they need to do is make a directory called programs. a directory called system. one called users. and be done with it.
The FHS is a joke.
Sabayon has had /usr/kde4 and /usr/kde3 as part of "transitioning" to KDE 4.
This was a clear violation of the FHS, and if Sabayon can use versioned directories already then I wonder why Gobo can not developed the concept further.
However, the FHS is like the holy grail. No distribution really *wants* to change from it, they aren't even truly compatible to it (see Sabayon), plus the FHS changes over time as well (in the past we had /usr/X11R6 as an exemption from their stupid rules, but this was now changed).
Still, someone explain to me why the Sabayon way is fine, but the Gobolinux way was bad bad bad.
PS: And on Gobolinux "cd /usr" just works exactly like on any other distribution. So what is the point?
Er. You seem to be under the impression that there's some kind of FHS Police going around enforcing the rules haphazardly.
There isn't.
Yes, Sabayon broke the FHS. So anyone who relies on it probably wouldn't choose Sabayon as their distro. I'd consider that a bug, and if I were a Sabayon user or developer I'd have complained about it. But I'm not.
There's no 'enforcement mechanism' for the FHS, distros just stick to it in general because they know it has a significant overall benefit (so people know where the hell to find stuff). There's no FHS Police.
And, wow, a standard that changes over time? It must be no good! Everyone revert to HTML 1.0 immediately!
I don't remember anyone above saying GoboLinux (or its filesystem) is bad, much less "bad, bad, bad." One doubts that many people care.
More problematic is that while there were 5 Gobo releases between late 2002 and 2004, there have been only 3 since, the latest being on 3 March 2009. At the moment, it has the dubious distinction of having older packages (e.g. Firefox, OpenOffice) than Debian Lenny (what I am using to post) or Slackware! ;-) You seem to be a Gobo supporter, what's the deal?
More to the point, if "new and improved" filesystems like that of GoboLinux or Thom's proposal are so superior as to be compelling, why has there been no flood of imitators or joiners? People will adopt something with a demonstrable benefit, or simply a perceived benefit--whether it is real or not. It is not like Linux developers and users are reactionary conservatives.
Perhaps the Gobo or a similar system is a genius-level advance that should be adopted by everyone. However, it is not the responsibility of ordinary folks like myself to be geniuses, it is the responsibility of genius to explain and demonstrate its inventions in a way that make the tangible benefits clear to the rest of us.
Rolling release distros tend to have fewer releases.
And while their binary package collection is lagging behind, the primary update method is source based. They have compilation scripts for firefox 3.0.10 and OO.org 3.0.1 in the Recipe database.."
I'm a bit confused when you say "Red Hat (Mandriva specifically)". These are two different distros.
RHEL and Mandriva are both LSB-compliant, which implies FHS compliance (Mandriva has a special lsb package, which ensures LSB compliance if you have it installed). I believe Debian is fully FHS-compliant too. You seem to be labouring under the mistaken impression that FHS canonically defines where every single file on the system must go. Of course it doesn't, how could it account for systems that weren't designed years ago when it was written? HTML doesn't define everything down to the last digit either. No standard does. Standards provide a broad framework for consistency. The FHS doesn't define exactly how a distribution should lay out its system-wide network configuration files, for instance, it just says they should be in /etc somewhere.
The reason for /etc/aliases being different is that under Debian postfix is only one choice of MTA. By default exim4 is used, and you can also install coriour and several others. They may all use /etc/aliases, or not.
Debian has the distinction of having perhaps the most consistent filesystem hierarchy of any Linux distribution. They have a policy, a superset of the FHS, and it is largely enforced. It always bothers me, when I am obliged to use Red Hat or (horror!) SuSE, to see the haphazard and random way in which things are placed. Consistency matters; in Debian it is a bug if a executable is installed in a bin dir and it has no corresponding man page, yet I see this situation constantly with other distributions.
How does that have anything to do with the filesystem layout? It's just a question of whether you consider it necessary for every executable to have a man page. Which Debian does. It's a nice feature, but it's not as if the other distros are doing anything 'wrong'. Just means Debian's maintainers get to spend a long time writing man pages for things which don't have them...
RHEL and Fedora both have a solid filesystem layout policy which is followed. If you find packages in RHEL or Fedora where files are not in the right cases according to the policies, by all means file bugs.
man pages have nothing to do with FS layout and I did not say they did. I said they are an example of consistency, which is something Debian does well.
Consistency is more important than logic when it comes to filesystem layout (in my opinion), so I am implying by this unrelated example of consistency that Debian does/will have good filesystem layout.
Perhaps the FSH on RH/Fedora is not so bad as I imagine, but I have seen over the years a number of strangely placed files on non-Debian distributions. I will say that SuSE is by far a worse offender than RH/Fedora.
All software available via official repositories in Fedora/ RHEL follows the FHS...
If anything that does not, it is merely a bug. No different from what you are talking about.
That was my guess but I wasn't sure that aliases was used across MTA where virtual and similar config files are specific to postfix.
(Now if I could get rsyslogd to stop shutting down overnight. Somehow I seem to have syslogd and rsyslogd installed thanks to a dist-upgrade from Etch to Lenny)
What is simple anyway?
I find that typing /usr/ takes much less time than typing "C:\Program Files\Ubisoft\Crytek\FarCry\" what do you think? If you really want to ln -s everything into wonderful fairyland newness so be it... but a belief that it makes life simple is simply a belief....
This is much ado about nothing really. Do you really want user poking around in system files.
The minutes users need to understand what is in the directories /usr, /var, /bin, /etc, etc, then the developers have already failed, whether the names change or not.
If the faux complexity keeps the users out of those directories, then that is actually be a good thing, because those people who need to know what's in there will figure it out, and those can't figure it out should probably keep out.
Seriously, and operating system is at least as complex as a car, if not more, and no one suggests that car manufacturers start putting more 'user friendly' descriptions on the internals, and make it easier for users to poke around. Users should generally only be interested in their home directory, their other storage (usb drives, external drives), emails etc.
Edited 2009-05-29 17:42 UTC
We are not discussing what end users do and do not want. We are discussing what the layout of the filesystem should be. Will you admit that some people have to deal with it? Those people are users, too, and the discussion is about them. Software developers are users and the discussion is also about them. Don't try and confuse the issue by bringing up clueless grandma-users. They are, after all, a minority on Linux. And, as you point out, what they think doesn't matter.
The entertaining thing is that most people commenting and implying knowledge of the fhs don't appear to have read it in any detail as:
/etc is exactly that = ecetera
there was no specific appliaction configuration directory.
The fhs could be vastly improved by simply providing a guideline to move actual system configuration files to a /cfg (or config to give abbreviations a break) and leave the rest of the mess in /etc.
/usr means UnixSystemResources - there is blatantly nothing in there that the 'User' needs to handle directly.
I think earlier comments along the lines of programs should be adapatable and be able to find libraries as opposed to standardised locations are notable due to slightly useful mis-feature of confusing the hapless script-kiddie with a few rootkits since they can't find important files to your system.
Also interestingly the comments regarding 'Library' on MOSX also bear relevance to GNUStep too - it too has a whole FHS of its own but thats another story..
Just my 1(0)p
Actually.... the name Unix System Resources didn't come up until long after the /usr directory. It's a "backronym", it was retrofitted. /usr does in fact mean user, because when it was designed, it held user files. But it has since been redefined, and "unix system resources" was some cutesy attempt to redefine it post-facto.
I'll just say that AmigaOS had the best damn file system hierarchy, and the designers understood that it eliminated the need for a lot of maintenance tools that other OS'es needed, thus making everything even simpler..
>
>
What a load of BS. The Amiga FS was just as fragile as any other OS FS,actually it was even more so because of the cluess cowboys like yourself who ran around screwing up their and other people's drives, and leaving people like me to clean up the messes they had made because they couldn't undo what they had done.
Nope, sorry. It's not true. You could always repair a screwed up AmigaOS installation, except for corrupted disks. Also if you had SnoopDOS, you pretty much always knew what was wrong, if a program wouldn't start.
A midlevel Amiga user, who has studied the file system can actually build his own working AmigaOS disk completely from scratch, build his own startup sequence and customized set of libraries necessary for just the programs you need.
By hand.
I did that many, many times to squeeze more space onto 880 KB disks, before I got a harddrive. I'm sure many other Amigans have done the same to make custom Workbench disks for very specific purposes. I also did it alot when playing around with WinUAE for a time.
Try that same process with Linux. Build an installation from scratch and see if you have a working computer tomorrow.
One example of eliminating unnecessary complexity through design, is how many operating systems want you to use a special program to determine which programs you want to start on boot. AmigaOS just reads the WBStartup directory. I don't remember using any package managers either. The GUI based installer was a 50 kb program with a simple scripting language.
Like I said, it's quite amazing that others are ignoring what AmigaOS could do in this regard, simply thanks to its extremely simple design.
Funny, that's exactly how sysvinit works. The only difference is multiple runlevels, but those are not strictly necessary. init just goes to /etc/rc?.d/ and executes everything that's executable in lexical order. Simple.
I'm sure Amiga had many nice things, but this was your only concrete example and it's not a very strong one.
The deal is that this is not going to change. That doesn't seem to stop people from posting ~ 200 posts to this thread. True bikeshedding in effect.
What we *really* need is
- More capitalizion
- More extensive use of whitespace like tabs.
E.g. Documents\tand\Settings
This makes the file listing "line up" much better on terminal window.
Hidden files would be preceded by ., AND followed by invisible character (remember ALT+255?)
I'm sorry, I thought this was a discussion of the FHS and how to improve it. I see a lot of people talking about user friendliness and desktop oriented distributions. Why? Solve one problem at a time, please!
If you want a filesystem layout best suited to average desktop users then you want on in which anything ca be given any name and located in any place at the user's discretion. Mac OS 9 managed a system that worked in practice a lot like this. If that's what you want, then do it! It's largely a solved problem.
If you want a filesystem that's more like a database, where you ask for what you want and don't worry about how it's stored, so users can create custom 'views' of data any which-way they want... then you want what MS promised but never delivered for Vista nee Longhorn. You can start with BeFS, which does most of this already. It's, again, mostly a solved problem.
Building a complete OS up around an innovative filesystem is a great idea. Go do it! But, it has nothing to do with a discussion of a revision to the FHS. If you want to solve some other people's computing problems with a new filesystem or a new system of organization, then solve their problems and leave Unix alone!
If what you want to do is what I want to do, if what you want to do is revise the traditional Unix FHS in a largely additive way, and not throw away the baby with the bathwater, then you are welcome to this topic. We are discussing fixing the FHS, not creating a completely new OS around Utopian user friendly ideals!
I don't want to hear certain comments; they are not germane. These comments include:
1) "The user should not be working outside of his own home directory. In his home directory the filesystem already has perfectly named directories for what every user needs: Documents, Pictures, etc."
This line of reasoning is less than useless. We're not talking about what the user ought or ought not know or do! We are talking about fixing what is, the FHS. In fact, the state of directories within a user's home directory is a mess, but this is largely irrelevant. We are discussing the FHS, which says about home directories not much or less. Stay on topic.
2) "Users should be using a GUI to configure their systems, not editing config files! They have no reason to know how the system is actually put together."
Again, a less than useless argument as it is off-topic! Someone needs to know how it works, someone needs to build and maintain it; whoever that person is deserves a system that is designed to work. That person cares about the FHS. Let all those who do not care remove themselves from the conversation, they are not in order.
3) "Other systems are just as horrible with respect to filesystem layout. Look at Windows! system, system32, wow64, etc.. Even Mac OS X just papers over the same problems."
And just because no one has a good system we should not try to improve the one we build? To the back of the bus, sir, and shut up.
Let us try to be constructive here. Too many times I see discussions of the FHS devolve into useless bickering. The young and impetuous make rash comments, causing the experienced to shout them down. SOme people say throw it all out, it's useless; they're decried as ignorant. Others declare that they use it, so let's keep it; they're attacked as dinosaurs. It happens every time this comes up!
Can we take a few points as given and work from there?
1) The FHS is not the ideal.
I know a lot of people like it (me, for example) for a lot of reasons, and I know that it has served us for many years. It has undeniable strengths! But, I have not yet met a Unix guy who wont admit frustration with the FHS. Most Unix and Linux guys will regale you with irritations over the filesystem layout of some *nix or other, though usually not his preferred one. There is a problem to be fixed. Let's start from there.
2) Hiding the problem doesn't help.
Any answer that solely involves more layers is not an answer but a bandage. Your file manager may hide root by default, but that doesn't mean it isn't there.
3) The problem isn't /etc
Or, rather, not just /etc. Let us not stray in to a discussion of config files, formats, XML and registries. That is a topic for another time. The FHS does not mandate the format of any file, nor should it. Solve one problem at a time or you never get anywhere.
I don't have all the answers. I don't have any answers. What I do have is some idea of how we can not get any answers, and that is by the kind of flammable debate I see on this topic. I have some kind of idea of what the form of a solution would look like, so let me outline it in general terms.
1) Throw nothing out.
There are reasons why some of the strange artifacts of the *nix filesystems are still in use. Any solution which fails to account for existing practices is as doomed as Gobolinux's solution.
2) Friendly names are OK.
In the modern world we have inexpensive output, tab completion and high resolution. There is little necessity to keep our names short. There are vast gains reductions in learning curve to more understandable names.
3) Do nothing radical.
Case insensitivity is the prime example of a radical change that just wont ever fly, but there are others. You can probably make radical changes down the line,f if an initial reform is successful, but making radical and controversial changes at first blush is a sure way to see that nothing new is ever adopted.
I fail to see how 'Distributions fail to adhere to the FHS consistently.' and 'Structures like /usr/bin, /etc, /opt, etc... are unintuitive.' are arguments for 'We need something completely different'.
At least in Debian, Ubuntu, and derivatives things seem to be pretty sane. And FHS is specified by the LSB, so theoretically any distribution that wants to be compliant with the LSB should by definition be compliant with the FHS.
If I want system wide config I go to /etc.
If I have to mess with anything in /sbin, /bin, or /lib, I've probably got bigger problems than filesystem organization, not unheard of, but not much of an argument for change, these should only be a small number of core things required for the basic operations of the system.
For other binaries and libraries unless an exception is made because upstream design is difficult to fit with FHS, binaries are in /usr/bin and libraries in /usr/lib, upstream design not fitting the FHS could also be considered reason by some distributions to put things in /opt.
Shared icons, wallpaper, system sounds, etc... I look for in /usr/share, program documentation (license, readme, etc..) in /usr/doc.
If I compile a program, I normally expect it to go in /usr/local, but usually I would also expect there to be some documentation indicating that, or failing that just end up with the compiled stuff that I move where I want it to go.
If I compile something and think it might clash with the rest of the system, I choose options to keep it more self contained and either have it go in my home directory or go in /opt, this is what /opt is geared for.
The argument for changing the names of some of these directories seems pretty clear. But the other changes seem like a pretty marginal benefit to the end user and a backward step for the sysadmins and distribution vendors.
Later, Seeker
I dare say the fact that the volume of comments on this is exploding - with a lot of them beeing very lenghty ones - proves that this is a serious issue.
To me the mess around the directory structure is one of the main aspects where Unix sucks - big time.
It would be interesting to hear Linus' take one it. Since a lot if directory names are hard coded into the kernel, there will be no clean solution on Linux unless the benevolent dictator decides to go for it. | http://www.osnews.com/comments/21579 | CC-MAIN-2015-40 | refinedweb | 20,483 | 63.59 |
Dex: Multi-step ray tracerSource file: dex-raytrace.fut
The following is a port of raytrace.dx, which is itself based on this Jax program by Eric Jang. See this blog post for details on the algorithm - this example won’t be getting into those details. We’ve tried to maintain the naming scheme of the original program, but we’ve re-ordered most definitions bring them closer to their first usage. This is mostly necessary due to the somewhat convoluted program structure forced by the use of modules for AD.
import "dex-prelude"
The biggest issue is that the Dex program uses the
grad operator to convert distance functions into normal functions. Futhark does not (yet) support anything like this as a language construct. Instead, we use forward-mode AD with dual numbers, which can be implemented as a library in Futhark. It works, and is reasonably efficient in this case, but it is certainly not as concise.
module ad = import "dual-numbers" module type expanded_field = { include ad.ordered_field val max : t -> t -> t val sqrt : t -> t val cos : t -> t val sin : t -> t val abs : t -> t } module f64_field : (expanded_field with t = f64) = { let max = f64.max let sqrt = f64.sqrt let cos = f64.cos let sin = f64.sin let abs = f64.abs
We expose all the definitions from
f64_field rather than repeating them.
open ad.f64_field }
The field implementation for dual numbers is mostly boilerplate. We cannot reuse the
mk_dual parametric module from dual-numbers.fut, because that module chose to make the representation abstract.
module f64_dual_field = { type underlying = f64 type t = (underlying, underlying) let primal ((x, _) : t) = x let tangent ((_, x') : t) = x' let dual0 x : t = (x, 0) let dual1 x : t = (x, 1) let max (x,x' : f64) (y,y') = (f64.max x y,if x >= y then x' else y') let sqrt (x,x') = 2 * f64.sqrt x)) (f64.sqrt x, x' / ( let cos (x, x') = (f64.cos x, f64.neg x' * f64.sin x) let sin (x, x') = (f64.sin x, x' * f64.cos x) let abs (x,x') = (f64.abs x, f64.sgn x * x') let neg (x,x') : t = (-x, -x') let recip (x,x') : t = (1/x, -(x'/(x*x))) let (x,x') + (y,y') : t = f64.((x + y, x' + y')) let (x,x') * (y,y') : t = f64.((x * y, x' * y + x * y')) let x - y = x + neg y let x / y = x * recip y let (x,_) == (y,_) = f64.(x == y) let (x,_) < (y,_) = f64.(x < y) let (x,_) > (y,_) = f64.(x > y) let (x,_) <= (y,_) = f64.(x <= y) let (x,_) >= (y,_) = f64.(x >= y) let (x,_) != (y,_) = f64.(x != y) let f64 x = dual0 x let zero = f64 0 let one = f64 1 }
Geometry
Sine we need the basic geometry functions of the ray tracer to work with both normal and dual numbers, we define it as a parametric module.
module mk_geometry(Float: expanded_field) = { type Float = Float.t
The original Dex program implements vectors in three-dimensional space with three-element arrays. This is not optimal in Futhark for reasons explained elsewhere, so instead we import the vector module from another example program.
module threed = import "3d-vectors"
And instantiate it with whatever
Float type we have at hand:
module vspace = threed.mk_vspace_3d Float
Convenient shorthands for various vector types and operations:
type Vec = vspace.vector let (*>) = vspace.scale let (<+>) = (vspace.+) let (<->) = (vspace.-) let (<*>) = (vspace.*) let dot = vspace.dot let length = vspace.length let normalize = vspace.normalise let cross = vspace.cross let rotateY = flip vspace.rot_y
These vectors are not arrays and we cannot
map them, but we can define our own mapping function.
let vmap (f: Float -> Float) (v : Vec) = {x = f v.x, y = f v.y, z = f v.z}
Dex calls the scaling operator
.*, but that name is not valid in Futhark. Note that the
length function will shadow the one in the Futhark prelude.
Dex’s
Color type is from the plot.dex file, which we’re not going to implement in its entirety.
Much of the following is just as straighforward in Futhark as in Dex, and so will not have much commentary.
type Color = Vec type Angle = Float -- angle in radians type Distance = Float type Position = Vec type Direction = Vec -- Should be normalized. type BlockHalfWidths = Vec type Radius = Float type Radiance = Color type ObjectGeom = #Wall Direction Distance | #Block Position BlockHalfWidths Angle | #Sphere Position Radius type Surface = #Matte Color | #Mirror type OrientedSurface = (Direction, Surface) type Object = #PassiveObject ObjectGeom Surface-- position, half-width, intensity (assumed to point down) | #Light Position Float Radiance
The signed distance function
This function is the reason why the Futhark implementation is so convoluted, as we will need its derivative.
let sdObject (pos:Position) (obj:Object) : Distance = match obj case #PassiveObject geom _ -> match geom (case #Wall nor d -> Float.(d + dot nor pos) case #Block blockPos halfWidths angle -> let pos' = rotateY (pos <-> blockPos) angle in length (vmap (Float.max Float.zero) (vmap Float.abs pos' <-> halfWidths)) case #Sphere spherePos r -> let pos' = pos <-> spherePos in Float.(max (length pos' - r) (f64 0))) case #Light squarePos hw _ -> let pos' = pos <-> squarePos let halfWidths = {x=hw, y=Float.f64 0.1, z=hw} in length (vmap (Float.max Float.zero) (vmap Float.abs pos' <-> halfWidths))
With that done, the rest of the ray tracer can be written in a non-modularised way, using just floating-point numbers.
}
Working with the geometry
We’ll need to instantiate the geometry module twice: once with ordinary floats, and once with dual numbers.
module geometry = mk_geometry f64_field module geometry_dual = mk_geometry f64_dual_field
To use
geometry_dual.sdObject, we’ll need to convert objects to objects-with-dual-numbers. For this, we’ll first define some utility functions.
let dual0 = f64_dual_field.dual0 let dual1 = f64_dual_field.dual1 let dualVec {x,y,z} = {x=dual0 x, y=dual0 y, z=dual0 z}
And then a bunch of boilerplate definitions.
let dualGeom (geom: geometry.ObjectGeom) : geometry_dual.ObjectGeom = match geom case #Wall nor d -> #Wall (dualVec nor) (dual0 d)case #Block blockPos halfWidths angle -> #Block (dualVec blockPos) (dualVec halfWidths) (dual0 angle)case #Sphere spherePos r -> #Sphere (dualVec spherePos) (dual0 r) let dualSurface (surf: geometry.Surface) : geometry_dual.Surface = match surf case #Matte c -> #Matte (dualVec c) case #Mirror -> #Mirror let dualObject (obj: geometry.Object) : geometry_dual.Object = match obj case #PassiveObject geom surface -> #PassiveObject (dualGeom geom) (dualSurface surface)case #Light squarePos hw r -> #Light (dualVec squarePos) (dual0 hw) (dualVec r)
The non-dual-number geometry module contains various useful type definitions. Instead of replicating their definitions, we make abbreviations.
type Object = geometry.Object type Position = geometry.Position type Direction = geometry.Direction type Distance = geometry.Distance type Radiance = geometry.Radiance type Color = geometry.Color type Surface = geometry.Surface type OrientedSurface = geometry.OrientedSurface type Vec = geometry.Vec
We also need some of the geometry functions:
let dot = geometry.dot let (<+>) = (geometry.<+>) let (<->) = (geometry.<->) let (<*>) = (geometry.<*>) let (*>) = (geometry.*>) let normalize = geometry.normalize let length = geometry.length
And a few more shorthands:
let vec x y z : Vec = {x,y,z}
Finally we can define the function that computes surface normals at a given position. This function is the reason we went to all that trouble with dual numbers.
let calcNormal (obj: Object) (pos: Position) : Direction = 1) geometry.normalize (vjp (\p -> geometry.sdObject p obj) pos
Random sampling
Since dex-prelude.fut defines the same random number generation interface as the Dex program, the sampling functions are straightforward ports.
First, a function for generating a number in a range:
let randuniform (lower: f64) (upper: f64) (k: Key) = let x = rand k in (lower + x * (upper-lower))
Sample within a square with side length 2*hw:
let sampleSquare (hw: f64) (k: Key) : Position = let (kx, kz) = splitKey k let x = randuniform (- hw) hw kx let z = randuniform (- hw) hw kz in {x, y=0.0, z}
Sample within a hemisphere in the direction of the normal vector:
let sampleCosineWeightedHemisphere (normal: Vec) (k: Key) : Vec = let (k1, k2) = splitKey k let u1 = rand k1 let u2 = rand k2 let uu = geometry.normalize (geometry.cross normal (vec 0.0 1.1 1.1)) let vv = geometry.cross uu normal let ra = f64.sqrt u2 let rx = ra * f64.cos (2 * f64.pi * u1) let ry = ra * f64.sin (2 * f64.pi * u1) let rz = f64.sqrt (1.0 - u2) let rr = (rx *> uu) <+> (ry *> vv) <+> (rz *> normal) in normalize rr
Ray marching
The essence of ray marching is simple: move along a given vector and find the first object we collide with. We do this the naive way, by invoking the distance function for every single object. This is not efficient, to put it mildly, but it is easy to implement.
First we need a
minimumBy function. Despite Futhark lacking Dex’s support for ad-hoc polymorphism, which matters here as we end up passing in the less-than operator, it doesn’t end up looking too bad.
let minBy 'a 'o (lt: o -> o -> bool) (f: a->o) (x:a) (y:a) : a = if f x `lt` f y then x else y let minimumBy [n] 'a 'o (lt: o -> o -> bool) (f: a->o) (xs: [n]a) : a = 0] xs reduce (minBy lt f) xs[
A scene is a collection of objects.
type Scene [n] = [n]Object
We can now define a function for finding the closest object, given a position.
let sdScene (objs: Scene []) (pos: Position) : (Object, Distance) = let i = minimumBy (<) (\i -> geometry.sdObject pos objs[i]) (indices objs)in (objs[i], geometry.sdObject pos objs[i])
When we ray march, we either collide with nothing and disappear into the aether, hit a light, or hit an object, in which case we also produce information about the surface, including the surface normal.
type Ray = (Position, Direction) type RayMarchResult = #HitObj Ray OrientedSurface | #HitLight Radiance | #HitNothing
The ray marching function is defined with the
iter function in Dex. In Futhark, a
while loop can express it in an equally natural way.
let positiveProjection (x: Vec) (y: Vec) = 0 dot x y > let raymarch [n] (scene:Scene [n]) (ray:Ray) : RayMarchResult = let max_iters = 100 let tol = 0.01 let (rayOrigin, rayDir) = ray let (_, _, res) = loop (i, rayLength, _) = (0, 10 * tol, #HitNothing) while i < max_iters do let rayPos = rayOrigin <+> (rayLength *> rayDir) let (obj, d) = sdScene scene rayPos let dNew = rayLength + 0.9 * d in if d >= tol then (i+1, dNew, #HitNothing) else let surfNorm = calcNormal obj rayPos in if positiveProjection rayDir surfNorm then (i+1, dNew, #HitNothing) else (max_iters, dNew,match obj case #PassiveObject _ surf -> #HitObj (rayPos, rayDir) (surfNorm, surf)case #Light _ _ radiance -> #HitLight radiance)in res
Light sampling
These definitions are pretty straightforward, and similar to those in Dex.
To figure out whether a light is shining on us along a given path, we just march along that path and see if we hit a light. If we do, the radiance is that light.
let rayDirectRadiance [n] (scene: Scene [n]) (ray: Ray) : Radiance = match raymarch scene ray case #HitLight intensity -> intensity case #HitNothing -> vec 0 0 0 case #HitObj _ _ -> vec 0 0 0
Shorthands for vectors along the cardinal axes will become useful in the following.
let xHat : Vec = vec 1 0 0 let yHat : Vec = vec 0 1 0 let zHat : Vec = vec 0 0 1 let relu (x: f64) = f64.max x 0 let probReflection ((nor, surf): OrientedSurface) (_:Ray) ((_, outRayDir):Ray) : f64 = match surf case #Matte _ -> relu (dot nor outRayDir) case #Mirror -> 0 let directionAndLength (x: Vec) = (normalize x, length x)
The following function determines how much light is shining on a given point. It’s very similar to the Dex function. Dex uses an explicit accumulator that is updated via effects, but I don’t think it makes it much more readable in this case.
let sampleLightRadiance [n] (scene: Scene [n]) (osurf: OrientedSurface) (inRay: Ray) (k: Key) : Radiance =let (surfNor, _) = osurf let (rayPos, _) = inRay in loop radiance = vec 0 0 0 for obj in scene do match obj case #PassiveObject _ _ -> radiance case #Light lightPos hw _ -> let (dirToLight, distToLight) = directionAndLength (lightPos <+> sampleSquare hw k <-> rayPos)in if ! (positiveProjection dirToLight surfNor) then radiance -- light on the far side of current surface else let fracSolidAngle = relu (dot dirToLight yHat) * sq hw / (f64.pi * sq distToLight)let outRay = (rayPos, dirToLight) let coeff = fracSolidAngle * probReflection osurf inRay outRay in radiance <+> (coeff *> rayDirectRadiance scene outRay)
Tracing
Almost done. Everything here is very similar to the Dex code.
type Filter = Color let applyFilter (filter:Filter) (radiance:Radiance) : Radiance = filter <*> radiance let surfaceFilter (filter:Filter) (surf:Surface) : Filter = match surf case #Matte color -> filter <*> color case #Mirror -> filter let sampleReflection ((nor, surf): OrientedSurface) ((pos, dir): Ray) (k: Key) : Ray = let newDir = match surf case #Matte _ -> sampleCosineWeightedHemisphere nor k case #Mirror -> dir <-> 2 * dot dir nor *> nor in (pos, newDir)
We’re excluding Dex’s
shareSeed field from the tracing parameters, since it seems mostly relevant for showing the impact of poor seeding on the convergence of the algorithm.
type Params = { numSamples : i32, maxBounces : i32 } let trace [n] (params: Params) (scene: Scene [n]) (init_ray: Ray) (k: Key) : Color = 2) <| (.loop 0, (vec 1 1 1), (vec 0 0 0), init_ray) (i, filter, radiance, ray) = (while i < params.maxBounces do match raymarch scene ray case #HitNothing -> (params.maxBounces, filter, radiance, ray)case #HitLight intensity -> if i == 0 then (params.maxBounces, filter, intensity, ray) else (params.maxBounces, filter, radiance, ray) case #HitObj incidentRay osurf -> let (k1, k2) = splitKey (hash k i) let lightRadiance = sampleLightRadiance scene osurf incidentRay k1 let outRayHemisphere = sampleReflection osurf incidentRay k2 let newFilter = surfaceFilter filter osurf.1 let newRadiance = radiance <+> applyFilter newFilter lightRadiance in (i+1, newFilter, newRadiance, outRayHemisphere)
Camera
The camera controls how the initial rays are sent into the scene.
type Camera = { numPix : i64, pos : Position, halfWidth : f64, sensorDist : f64 }
And now we’re ready to produce the n*n array of initial rays and RNG states.
let cameraRays (n: i64) (camera: Camera) : [n][n](Ray, Key) = let halfWidth = camera.halfWidth let pixHalfWidth = halfWidth / f64.i64 n let ys = reverse (linspace n (-halfWidth) halfWidth) let xs = linspace n (-halfWidth) halfWidth let kss = tabulate_2d n n (\i j -> newKey (i32.i64 (1+i*n+j))) let rayForPixel y x k = let dx = randuniform (-pixHalfWidth) pixHalfWidth k let dy = randuniform (-pixHalfWidth) pixHalfWidth k in ((camera.pos, normalize (vec (x + dx) (y + dy) (-(camera.sensorDist)))), k)in map2 (\y ks -> map2 (rayForPixel y) xs ks) ys kss
Most ray tracers perform multiple samples per pixel and take the average. The Dex program defines the
sampleAveraged function to be (potentially) parallel. We know the parallelism would never be exploited anyway, so we define it as a sequential loop, mostly to make the random number state management simpler.
let sampleAveraged (sample: Key -> Vec) (n: i32) (k: Key) : Vec = loop acc = vec 0 0 0 for i < n do ( (acc <+> sample (ixkey k (i64.i32 i))))1/f64.i32 n) *>) |> ((
The Dex implementation uses an unusual relative colorisation strategy, where the final color values are all divided by the average intensity. This is likely so we won’t have to fiddle with the light intensities to avoid very bright or very dark images.
let meanIntensity image = 3) |> mean image |> flatten |> map (\{x,y,z} -> (x+y+z)/
Smile for the camera!
let takePicture [m] (params: Params) (scene: Scene [m]) (camera: Camera) = let n = camera.numPix let rays = cameraRays n camera let sample (r, k) = sampleAveraged (trace params scene r) params.numSamples klet image = map (map sample) rays let mean = meanIntensity image in map (map ((1/mean)*>)) image
Scene definition
The only odd thing here is that apparently our vectors rotate opposite of the way Dex does it, so I had to give the block a rotation of -0.5 instead of 0.5.
let lightColor = vec 0.2 0.2 0.2 let leftWallColor = 1.5 *> vec 0.611 0.0555 0.062 let rightWallColor = 1.5 *> vec 0.117 0.4125 0.115 let whiteWallColor = (1/255) *> vec 255.0 239.0 196.0 let blockColor = (1/255) *> vec 200.0 200.0 255.0 let neg = ((-1)*>) let theScene : Scene [] = 1.9 *> yHat) 0.5 lightColor [ #Light (2.0) (#Matte leftWallColor) , #PassiveObject (#Wall xHat 2.0) (#Matte rightWallColor) , #PassiveObject (#Wall (neg xHat) 2.0) (#Matte whiteWallColor) , #PassiveObject (#Wall yHat 2.0) (#Matte whiteWallColor) , #PassiveObject (#Wall (neg yHat) 2.0) (#Matte whiteWallColor) , #PassiveObject (#Wall zHat 1.0 (-1.6) 1.2) (vec 0.6 0.8 0.6) (-0.5)) (#Matte blockColor) , #PassiveObject (#Block (vec -1.0) (-1.2) 0.2) 0.8) (#Matte (0.7 *> whiteWallColor)) , #PassiveObject (#Sphere (vec (2 2 (-2)) 1.5) #Mirror , #PassiveObject (#Sphere (vec ] let defaultParams : Params = { numSamples = 50 10 } , maxBounces = let defaultCamera : Camera = { numPix = 250 10.0 *> zHat , pos = 0.3 , halfWidth = 1.0 } , sensorDist =
Entry point
This is not part of the Dex program, but is needed if we want Futhark to produce anything for the outside world.
First, a function to convert floating-point colors to RGB-packed colors with 8 bits per channel. Note that we have to cap each channel, since there is no guarantee that the color components produced by the ray tracer cannot exceed 1.0.
let pix (c: Color) = 255 (c.x * 255)) << 16) | (u32.f64 (f64.min 255 (c.y * 255)) << 8) | (u32.f64 (f64.min 255 (c.z * 255))) (u32.f64 (f64.min let main n = with numPix = n) takePicture defaultParams theScene (defaultCamera |> map (map pix)
> :img main 500i64
-- == -- input { 100i64 } | https://futhark-lang.org/examples/dex-raytrace.html | CC-MAIN-2021-31 | refinedweb | 2,924 | 57.77 |
I have code to sort a list of tuples:
s = "betty bought a bit of butter but the butter was bitter"
words = s.split()
l = []
k = []
unique_words = sorted(set(words))
for word in unique_words:
k.append(word)
l.append(words.count(word))
z = zip(k,l)
print z
reversed(sorted(z, key=lambda x: x[1]))
print z
For an in-place sort, you should use
z.sort().
If you insist on using
sorted, then send the value back to
z.
So, use either,
z.sort(key = lambda x:x[1]) z.reverse()
Or,
z = reversed(sorted(z, key=lambda x: x[1]))
Or, a more sophisticated solution could be:
z = sorted(z, key=lambda x: x[1], reverse= True)
As a matter of fact, you can get the end result more easily by using
collections.Counter()
from collections import Counter z = sorted(Counter(s.split()).items(), key = lambda x:x[1], reverse = True)
Sorting by two multiple keys are fine, you can pass them as a tuple. In your case, the solution would be:
# first sort by negatives of the second item, then alphabetically. z = sorted(z, key=lambda x: (-x[1],x[0]))
Output:
[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1), ('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)] | https://codedump.io/share/cVWgJRNMsvvf/1/python-sort-not-working | CC-MAIN-2016-50 | refinedweb | 216 | 63.8 |
Hands on toolkits
Project description
RonChang
What is this?
This is my personal hands-on develop toolkits. |name|popurse| |-|-| |Timer|colorful and expandable timer|
How to install?
pip install ronchang
1. Timer
- import
from ronchang import Timer Timer( interval, # unit: seconds start=None, is_error=False, exception=None, **kwargs )
- demonstration
from ronchang import Demo Demo.Timer()
If you like my work, please consider buying me a coffee or PayPal
Thanks for your support! Cheers! 🎉
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/ronchang/0.1.1/ | CC-MAIN-2021-49 | refinedweb | 102 | 59.5 |
Java Applications Log Message Analytics Using Splunk
Learn how using Splunk in Java to accept log messages, do indexes using log messages, and provide metrics using log messages.
Join the DZone community and get the full member experience.Join For Free
Splunk is the most-used server for collecting data from different sources, indexing that collected data, analyzing the index data, and preparing reports based on the indexed data. The source of data may be from any environment. The source may be in a structured format or an unstructured format. Splunk provides some intelligent algorithms to understand the indexed data that are used in security, IoT machine logs, and application logs and to provide data analytics.
Splunk Data Sources
Splunk provides a wide range of plugins to support various resources. For example, to understand Windows event logs, it provides one plugin. For understanding Ubuntu machines logs, it provides different plugins. Based on the analysis of logs, Splunk will generate the number of times that the operating system is loaded, the average CPU load in each session, and how many different users logged into the system. It will generate the reports and it can also generate dashboard for live data streaming.
Scalability
Splunk will not depend upon any external services and it doesn't need any database support because Splunk internally uses a file system to store the indexed results. If the incoming data is increased, we can add another instance of Splunk server to index and store the data. Splunk will internally communicate and it will distribute the incoming data. While the searching, it will collect the data from all Splunk servers and display it to the user. If we enable redundancy, then incoming data is distributed to more than one Splunk server. Technology
You can; a
splunk-logging plugin for JavaScript; and a plugin on top of NodeJS. We can also use the
splunk-bunyan-logger plugin for JavaScript to collect HTTP events.
The Splunk SDK for Java ships with built-in support for IntelliJ for easy integration. SpringSource introduced the Spring Integration Extension for Splunk, making it easier for java developers using Spring to log directly to Splunk from their applications.
The Splunk Event Collector is the fastest way to send data to the Splunk Enterprises server and Splunk Cloud. HTTP Event Collector (HEC) enables users to send data over HTTP and HTTPS protocol directly to the Splunk Enterprise and Splunk Cloud from application code. HEC provides the one REST endpoint for accepting incoming data. In our application, we can write to send data to the REST endpoint. HEC is authorized using tokens, so we don’t need to hardcode the username a POST request to include authentication header or a key/value pair to include the HEC token.
- POST data to the HEC token receiver.
For Splunk cloud instances, it is not enabled. We can raise a request to Splunk cloud to enable the HEC token.
Connecting to Splunk Server Using Splunk SDK
We can add the Splunk JAR to the project classpath or we can download splunk-sdk and extract the Splunk JAR from the
splunk-sdk-java/dist folder.
The sample Java program below can be used to connect to Splunk Server and print the Same Token Across All Applications
The Service class creates a (with a namespace for Splunk. It will use the Spring integration adapter for Splunk internally.
Creating beans for Splunk server object:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" xmlns: </beans>
Outbound Channel Adapter
Outbound channel adapter is used to put data into Splunk from channels in Spring Integration. There are three kinds of method to put data:
Submit (HTTP REST).
Stream.
TCP.
The main difference between using the REST inputs versus plain TCP/UDP inputs is really in the Splunk event handling pipeline.
With REST, you have to declare your event metadata (index, source, source type…) in the HTTP request at the source. You can't really transform the log event anymore after you have created it" channel="outputToSplunk" splunk- </int-splunk:outbound-channel-adapter>
With TCP inputs, metadata manipulates and transforms the event data in Splunk before it gets indexed (using entries in
props.conf/transforms.conf). The metadata " channel="outputToSplunk" splunk-
To use outbound channel adapter with Stream, you can define the adapter as the following:
<int-splunk:outbound-channel-adapter
Inbound Channel Adapter
Inbound Channel Adapter is used to get data out of Splunk and put it into Spring Integration's channel. There are five ways to get data out of Splunk:
- Blocking.
- Nonblocking.
-" time- </int-splunk:inbound-channel-adapter>
...where
mode is one of the above 5 types.
Using Log Frameworks to Log Into Splunk Servers
Splunk logging provides the JAR, which provides appenders for the most-used logger frameworks.
java.util.logginghandler for logging to Splunk REST endpoints, logging to Splunk Raw TCP Server Socket, and logging to Splunk HEC Endpoint.
Log4j appender for logging to Splunk REST endpoints, logging to Splunk Raw TCP Server Socket, and logging to Splunk HEC Endpoint.
Logbackappenderfor logging to Splunk REST endpoints, logging to Splunk Raw TCP Server Socket, and logging to Splunk HEC Endpoint.
Log4j 2 appender for logging to Splunk HEC Endpoint and for config examples for TCP and UDP logging.
For example, if we want to use REST services, we can include the below configuration in
logger.properties.
log4j.appender..splunk.logging.log4j.appender.SplunkRestApp.
This way, it will be logged automatically.
Conclusion
In this article, we have explained the uses of Splunk in Java. Splunk is the software to accept log messages, do indexes using log messages, and provide metrics using log messages. It provides the SDK and logging frameworks for connecting to Splunk Enterprises and Splunk Cloud. Spring Integration provides an adapter for contacting Splunk Sever and provides a namespace for creating Splunk-related beans.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/java-applications-log-message-analytics-using-splu | CC-MAIN-2022-21 | refinedweb | 981 | 53.31 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to format a date while printing in rml or in openoffice report
Hi,
Can anyone tell me how to print a date in a desired format in openerp reports. I use both rml and openoffice for reporting
Default Date format in form
12/06/2013
Default Date format while printing in reports
2013/06/12
My Desired Format
12-June-2013
Thanks for your time
Write following code in report py:
import time from datetime import datetime 'get_my_date': self.get_my_date, #Add this line in self.localcontext.update dictionary def get_my_date(self, date): return time.strftime('%d') + '-' + datetime.strptime(date, '%d-%m-%Y').strftime('%b').upper() + '-' + time.strftime('%Y')
Call this method from your rml file:
<para style="P2"> [[ get_my_date(your_date) ]] </para>
Thanks sudir, How do i do this with regard to openoffice report i.e when i design a report in openoffice.
You can write
[[ get_my_date(your_date) ]] code in sxw file also but you must have to write given method in report py file.
Yeah, but there's a problem in there sudir, There's a default sxw file in every module is not considered while printing. It's taken a copy when i take it and in the copy we've modified the above line and sent it to server. Nothing gets printed. Kindly guide me.
Either you can make changes in rml or first change in sxw, then convert it in rml and replace original rml with you new rml.
hi where to put 'get_my_date': self.get_my_date, code if i want to change format of date in meeting custom report in crm module
I already have written it in comment that you have to put it in "self.localcontext" in your report py file.
If you are adding the fields through the openoffice report editor, try this:
[[ formatLang(o.date_start,date_time=True) ]] (for date + hours) or [[ formatLang(o.date_start,date=True) ]] (date)
Just replace "date_time" with your field. Take heed: this will not show it like your desired format, but it will be better than the default output.
For a better solution, follow Sudhir's instructions.
use [[ time.strftime('%d-%B-%Y') ]]
thank you for this answer, do you know how to add customer's contact person | https://www.odoo.com/forum/help-1/question/how-to-format-a-date-while-printing-in-rml-or-in-openoffice-report-20863 | CC-MAIN-2017-04 | refinedweb | 399 | 72.97 |
Hi all, I am a beginner to C. The following is not a completed program, or even a part of a program, but I see no point in writing any more before I can get this to compile...
The problem is already obvious to you guys, but I am getting the following errors:The problem is already obvious to you guys, but I am getting the following errors:Code:#include <stdio.h> #include <stdlib.h> int get_filename(); int main(void){ //declarations FILE *input_stream; //program statements input_stream = fopen( get_filename(), "r" ) ); //line 37 //there will be error checking here, in the form of an if, eventually } int get_filename(){ //declarations char filename[101]; //program statements printf("enter filename: "); scanf( "%s", filename); return (filename); //line 47 }
37 passing arg 1 of `fopen' from incompatible pointer type
37 syntax error before ')' token
In function `get_filename':
47 [Warning] return makes integer from pointer without a cast
47 [Warning] function returns address of local variable
To me this appears to be basically one error, that manifests in several places. I think it is to do with the returning of the contents of the variable filename. Of course, I could just put it in main, but that would be like giving up, and I will need to know how to do this in the future, anyway. Can you return strings out of functions like that? I have tried the FAQ and everything, to no avail....any ideas?
Thanks in advance...
fraktal | https://cboard.cprogramming.com/c-programming/73428-passing-strings-functions-return-part.html | CC-MAIN-2017-26 | refinedweb | 243 | 56.18 |
. A view callable is a specific bit of code, defined in your application, that receives the request and returns a response object.
High-Level Operational Overview¶
If any route configuration is present in an application, the Pyramid Router checks every incoming request against an ordered set of URL matching patterns present in a route map.
If any route pattern matches the information in the request, Pyramid will invoke the view lookup process view callable added to the configuration by way of
add_view() becomes associated with a route
via its
route_name predicate, that view callable will always be found and
invoked when the associated route pattern matches during a request.
More commonly, you will not use any
add_view statements in your project's
"setup" code. You will instead use
add_route statements, and use a
scan to associate view callables with routes. For example, if this is
a portion of your project's
__init__.py:
config.add_route('myroute', '/prefix/{one}/{two}') config.scan('mypackage')
Note that we don't call
add_view() in this
setup code. However, the above scan execution
config.scan('mypackage') will pick up each configuration
decoration, including any objects decorated with the
pyramid.view.view_config decorator in the
mypackage Python
package. For example, if you have a
views.py in your package, a scan will
pick up any of its configuration decorators, so we can add one there that
references
myroute as a
route_name parameter:
from pyramid.view import view_config from pyramid.response import Response @view_config(route_name='myroute') def myview(request): return Response('OK')
The above combination of
add_route and
scan is completely equivalent to
using the previous combination of
add_route and
add_view.
If a pattern is a valid URL it won't be matched against an incoming request. Instead it can be useful for generating external URLs. See External routes for details..
Changed in version 1.2::
The matchdict will look like so (the value is URL-decoded / UTF-8 decoded):
{'bar':u'La Pe\xf1a'}
Literal strings in the path segment should represent the decoded value of the
PATH_INFO provided to Pyramid. You don't want to use a URL-encoded value
or a bytestring representing the literal encoded as UTF-8 in the pattern. For
example, rather than this:
.':u''} in which route declarations are evaluated is the order in which they are added to the application at startup time. (This is unlike a different way of mapping URLs to code that Pyramid provides, named traversal, which does not depend on pattern ordering).
name and
factory. These arguments represent
neither predicates nor view configuration information.views command, as documented in
Displaying Matching Views for a Given URL..
Recall that the
@view_config is equivalent to calling
config.add_view,
because the
config.scan() call will import
mypackage.views, shown
below, and execute
config.add_view under the hood. Each view then maps the
route name to the matching view callable.:
Here is an example of a corresponding
mypackage.views module:. The view
mypackage.views.idea_view
might look like this:
Here,
request.context is an instance of
Idea. If indeed the resource
object is a SQLAlchemy model, you do not even have to perform a query in the
view callable, since you have access to the resource via
request.context.
See Route Factories for more details about how to use route factories._url and
route_path.
External routes are implicitly static. time.
Most pattern replacements and calls to
pyramid.request.Request.route_url() will work as expected. However, calls
to
pyramid.request.Request.route_path() against external patterns will
raise an exception, and passing
_app_url to
route_url() to generate a URL against a route
that has an external pattern will also raise an exception.
Redirecting to Slash-Appended Routes¶
For behavior like Django's
APPEND_SLASH=True, use the
append_slash
argument to
pyramid.config.Configurator.add_notfound_view() or the
equivalent
append_slash argument to the
pyramid.view.notfound_view_config decorator.
Adding
append_slash=True. In addition you may pass anything that implements
pyramid.interfaces.IResponse which will then be used in place of the
default class (
pyramid.httpexceptions.HTTPFound).
Let's use an example. If the following routes are configured in your application:
If a request enters the application with the
PATH_INFO value of
/no_slash, the first route will match and the browser will show "No slash".
However, if a request enters the application with the
PATH_INFO value of
/no_slash/, no route will match, and the slash-appending not found view
will not find a matching route with an appended slash. As a result, the
notfound view will be called and it will return a "Not found" body.. As a result, the
notfound view will never actually be called.
The following application uses the
pyramid.view.notfound_view_config
and
pyramid.view.view_config decorators and a scan to do
exactly the same job:
Warning
You should not rely on this mechanism to redirect
POST requests.
The redirect of the slash-appending Not Found View will turn a
POST request into a
GET, losing any
POST data in the original
request.
See pyramid.view and Changing the Not Found View for a more general description of how to configure a view and/or a Not Found View.
Debugging Route Matching¶
It's useful to be able to take a peek under the hood when requests that enter
your application aren't matching your routes as you expect them to. To debug
route matching, use the
PYRAMID_DEBUG_ROUTEMATCH environment variable or
the
pyramid.
You can also use the
proutes command to see a display of all the routes
configured in your application. For more information, see
Displaying All Application Routes.
Using a Route Prefix to Compose Applications¶
New in version. route will have an effective
route pattern of
/users/show instead of
/show because the
route_prefix argument will be prepended to the pattern. The route:, including
match
and
route.
match is a dictionary which. Here's an example of using the
route in a set of route predicates:
See also
pyramid.interfaces.IRoute for more API documentation
about route objects.
Route Factories¶
Although it is not a particularly common need in basic applications, a "route" configuration declaration can mention a "factory". When a route matches a request, and a factory is attached to. route's match dict to
see if the
article argument matches a particular string. Our sample
Article factory class is not very ambitious.
Route View Callable Registration and Lookup Details¶
When a request enters the system which matches the pattern of the route, the usual. | https://docs.pylonsproject.org/projects/pyramid/en/1.8-branch/narr/urldispatch.html | CC-MAIN-2022-05 | refinedweb | 1,075 | 57.77 |
Chatlog 2012-03-22
From Provenance WG Wiki
See original RRSAgent log or preview nicely formatted version.
Please justify/explain all edits to this page, in your "edit summary" text.
14:52:15 <RRSAgent> RRSAgent has joined #prov 14:52:15 <RRSAgent> logging to 14:52:17 <trackbot> RRSAgent, make logs world 14:52:17 <Zakim> Zakim has joined #prov 14:52:19 <trackbot> Zakim, this will be 14:52:19 <Zakim> I don't understand 'this will be', trackbot 14:52:20 <trackbot> Meeting: Provenance Working Group Teleconference 14:52:20 <trackbot> Date: 22 March 2012 14:52:25 <pgroth> Zakim, this will be PROV 14:52:28 <Zakim> ok, pgroth; I see SW_(PROV)11:00AM scheduled to start in 8 minutes 14:52:44 <pgroth> Agenda: 14:52:51 <pgroth> Chair: Paul Groth 14:53:04 <pgroth> Scribe: Curt Tilmes 14:53:12 <pgroth> rrsagent, make logs public 14:55:18 <pgroth> anybody, having problems with Zakim? 14:55:45 <Curt> Curt has joined #prov 14:55:56 <pgroth> curt, thanks for scribing 14:56:00 <pgroth> it's all set up 14:56:00 <Zakim> SW_(PROV)11:00AM has now started 14:56:02 <Curt> np 14:56:07 <Zakim> +Curt_Tilmes 14:56:25 <tlebo> tlebo has joined #prov 14:56:48 <Luc> Luc has joined #prov 14:57:23 <pgroth> anybody having problems with Zakim? 14:57:50 <Zakim> +??P39 14:58:06 <Paolo> Paolo has joined #prov 14:58:50 <MacTed> I'm not familiar enough with Hg.... 14:58:50 <MacTed> can someone tweak the opposite-of-generated example from "prov:consumedBy" to "prov:wasConsumedBy" to more properly parallel "prov:wasGeneratedBy"? 14:59:14 <zednik> zednik has joined #prov 14:59:21 <pgroth> having trouble joining 14:59:22 <satya> satya has joined #prov 14:59:50 <Zakim> + +4238059aaaa 14:59:53 <Zakim> +[IPcaller] 14:59:55 <Zakim> +Satya_Sahoo 15:00:06 <Zakim> +[OpenLink] 15:00:07 <Luc> zakim, +4238059aaaa is me 15:00:08 <Zakim> +Luc; got it 15:00:09 <MacTed> (it's either add "was" to the consumption, or remove it from the generation...) 15:00:18 <MacTed> Zakim, [OpenLink] is temporarily me 15:00:18 <Zakim> +MacTed; got it 15:00:20 <MacTed> Zakim, mute me 15:00:20 <Zakim> MacTed should now be muted 15:00:28 <dgarijo> dgarijo has joined #prov 15:00:39 <Luc> trackbot, start telcon 15:00:41 <trackbot> RRSAgent, make logs world 15:00:44 <trackbot> Zakim, this will be 15:00:44 <Luc> Zakim, this will be PROV 15:00:44 <trackbot> Meeting: Provenance Working Group Teleconference 15:00:44 <trackbot> Date: 22 March 2012 15:00:46 <Zakim> I don't understand 'this will be', trackbot 15:00:50 <Zakim> ok, Luc, I see SW_(PROV)11:00AM already started 15:00:54 <Zakim> +??P44 15:00:56 <GK1> GK1 has joined #prov 15:00:58 <MacTed> Zakim, who's here? 15:01:04 <pgroth> Zakim, who is on the call? 15:01:18 <mike_> mike_ has joined #prov 15:01:20 <Zakim> On the phone I see Curt_Tilmes, ??P39, Luc, [IPcaller], Satya_Sahoo, MacTed (muted), ??P44 15:01:22 <Zakim> +tlebo 15:01:29 <pgroth> Zakim, ??P44 is me 15:01:30 <Zakim> On the phone I see Curt_Tilmes, ??P39, Luc, [IPcaller], Satya_Sahoo, MacTed (muted), ??P44, tlebo 15:01:40 <Paolo> zakim, ??P39 is me 15:01:40 <Zakim> + +1.443.708.aabb 15:01:43 <GK> GK has joined #prov 15:01:45 <Zakim> On IRC I see GK1, dgarijo, satya, zednik, Paolo, Luc, tlebo, Curt, Zakim, RRSAgent, pgroth, MacTed, stain, trackbot, sandro 15:02:01 <Zakim> +??P1 15:02:03 <MacTed> Luc has a somewhat bad connection... fuzzes a lot on vocals 15:02:07 <Zakim> +pgroth; got it 15:02:10 <dgarijo> zakim, ??P1 is me 15:02:14 <Zakim> +Paolo; got it 15:02:39 <jun> jun has joined #prov 15:02:42 <Zakim> +dgarijo; got it 15:02:49 <Zakim> -Luc 15:03:22 <kai> kai has joined #prov 15:03:24 <Zakim> +Luc 15:03:39 <Zakim> +??P18 15:03:54 <smiles> smiles has joined #prov 15:03:54 <GK> zakim, ??P18 is me 15:03:57 <pgroth> Topic: Admin <pgroth> Summary: The group was reminded of the time change next week. Additionally, the schedule until the synchronous release was gone over. Paul gave an update on his progress on developing a new version of the prov-aq. 15:04:01 <Zakim> +sandro 15:04:05 <pgroth> Minutes of the March 15 2012 Telecon 15:04:09 <Zakim> +GK; got it 15:04:12 <Curt> +1 15:04:16 <dgarijo> +1 15:04:19 <Paolo> +1 15:04:20 <mike_> +1 15:04:21 <zednik> +1 15:04:25 <satya> +1 15:04:27 <Zakim> +[IPcaller.a] 15:04:35 <GK> +1 15:04:41 <jun> zakim, [IPcaller.a] is me 15:04:58 <pgroth> Approved Minutes of the March 15 2012 Telecon 15:05:12 <Zakim> +jun; got it 15:05:13 <Zakim> +??P21 15:05:18 <jcheney> jcheney has joined #prov 15:05:26 <Curt> pgroth: time change reminder -- return next week to normal times 15:05:45 <Curt> ... please sign up scribes 15:06:08 <Curt> ... open actions - paul has drafted PAQ review 15:06:12 <Zakim> +??P8 15:06:20 <jcheney> zakim, ??P8 is me 15:06:20 <Zakim> +jcheney; got it 15:06:24 <Curt> ... graham still needs to review that 15:06:45 <pgroth> +q? 15:06:46 <Curt> ... he just got it -- he will address this week or next 15:06:47 <Luc> q+ 15:06:48 <pgroth> q? 15:07:04 <GK> I'm tied up with project work this week, but should havew time to review next week. 15:07:04 <Curt> luc: is the plan to release the PAQ synced with the others? 15:07:32 <Curt> pgroth: depends -- it may be difficult to do that, graham may be able to get things and we might be able to do it 15:07:42 <pgroth> q? 15:07:42 <Curt> ... we'll at least try to get a synced draft release 15:07:44 <pgroth> ack Luc 15:07:45 <pgroth> ack ? 15:07:46 <GK> (lost my sound briefly then) 15:07:48 <Zakim> -jun 15:08:09 <pgroth> 15:08:09 <Zakim> +??P25 15:08:15 <Curt> pgroth: review updated time schedule from google doc 15:08:18 <jun> zakim, ??P25 is me 15:08:18 <Zakim> +jun; got it 15:08:34 <Christine> Christine has joined #prov 15:08:36 <Curt> ... synced release of docs in mid-april 15:08:54 <Curt> ... drafts available to the group by the end of next week for internal review 15:09:12 <pgroth> q? 15:09:15 <Zakim> +??P10 15:09:20 <Curt> ... a lot of work has happened, we need the synced release to show progress 15:09:26 <pgroth> Topic: Prov-dm <pgroth> Summary: Luc and Paolo presented the status of prov-dm. In particular, the component organization was focused on. The group was asked to give input on the definitions for alternate and specialization. Reviewers were identified for the three different documents that make up the DM: Prov-dm - Tim, Khalid, Satya, Curt, Jun ; Prov-dm-constraints - James, Tim, Graham ; Prov-N - Khalid, Simon, Tim 15:09:48 <Luc> 15:10:04 <Curt> luc: much work in the last week, revised editors draft exists, not quite ready for review 15:10:12 <Luc> 15:10:16 <Curt> ... structure revised 15:10:34 <khalidbelhajjame> khalidbelhajjame has joined #prov 15:10:41 <Paolo> you'll need to scroll down as usual 15:10:54 <Curt> ... section 4 beginning, has a picture of the 6 components 15:11:26 <Curt> ... for each component, we have a short overview and UML diagram depicting the relationships between components 15:11:41 <Luc> : 15:11:43 <Curt> ... things are taking shape, the essence we wanted to incorporate is there 15:11:55 <Zakim> +??P15 15:12:01 <khalidbelhajjame> zakim, ??P15 is me 15:12:01 <Zakim> +khalidbelhajjame; got it 15:12:07 <tlebo> colors and tetris. All right! 15:12:12 <Curt> ... section 3.1 has a revised picture taking into account feedback 15:12:17 <Luc> 15:12:29 <Curt> ... PROV-N updated editors draft 15:12:31 <GK> (This linking problem is a respec anomaly -- once page is loaded, clicking on section link works.) 15:12:49 <Curt> ... definition of production, some conflicts resolved, taking shape now 15:12:50 <Paolo> @tlebo I like to think it's a tangram :-) 15:13:04 <Curt> ... still working on collections -- more expected in the coming week 15:13:08 <Luc> 15:13:19 <Luc> 15:13:32 <Curt> ... solicit contributions for short english definitions for some concepts 15:13:44 <pgroth> q? 15:13:46 <Curt> ... please email suggestions to luc/paolo and they will incorporate 15:13:57 <Luc> 15:14:07 <GK> Do we really need alternates/specialization in part 1? 15:14:23 <Luc> Communication 15:14:39 <Luc> Start By Activity (wasStartedByActivity) 15:14:49 <Curt> ... wasInformedBy relation unclear -- suggesting "communication", read that section of the document 15:14:49 <dgarijo> what about dependency? 15:15:27 <Curt> luc: next steps to get to release, still going through some feedback 15:16:06 <Curt> paolo: constraints need some work 15:16:33 <Curt> ... how hard is the deadline next week? many things have to happen in the next week... 15:17:22 <Curt> luc: it is challenging to get 3 documents all together at once. section 2 needs some work 15:17:47 <Curt> ... help on definitions would be welcome 15:18:08 <Curt> paolo: part1, 3 are the priority 15:18:28 <Curt> pgroth: review other documents status, then discuss timeline 15:18:48 <Curt> ... still need to line up reviewers for various documents 15:19:01 <pgroth> q? 15:19:03 <Curt> ... that will help inform timeline 15:19:43 <pgroth> Prov-dm Reviewers 15:19:47 <tlebo> +1 15:19:49 <khalidbelhajjame> +1 15:19:50 <satya> +1 15:19:54 <Curt> pgroth: need reviewers for each of three documents 15:19:58 <Curt> +1 15:20:15 <jun> +1 15:20:15 <satya> q+ 15:20:53 <Luc> @satya: documents are not ready!!!!!! 15:21:07 <pgroth> ack satya 15:21:21 <pgroth> Prov-dm-constraints Reviewers 15:21:30 <Luc> q+ 15:21:35 <pgroth> ack Luc 15:21:38 <jcheney> +1 15:21:40 <tlebo> +1 15:21:56 <GK> I'll plan to review "constraints", provided it's available before April 15:22:28 <pgroth> Prov-n Reviewers 15:22:33 <khalidbelhajjame> +1 15:22:36 <smiles> +1 15:22:37 <tlebo> +1 15:23:03 <pgroth> Topic: Prov-o <pgroth> Summary: An update on the status of prov-o was given. The document has been reorganized and authors have been identified to contribute to the various parts of the document. The group is on track to release by next week. Reviewers were identified for prov-o: Luc, Paul, Simon 15:23:37 <Curt> tlebo: reorganized HTML document, emphasizing difference between simple/extended 15:23:48 <tlebo> 15:23:55 <Curt> ... new design in progress, met monday and assigned some writing sections 15:24:12 <Curt> ... getting together early next week, draft available next friday 15:24:15 <pgroth> q? 15:25:05 <pgroth> Reviewers Prov-o 15:25:08 <Luc> +1 15:25:16 <pgroth> +1 15:25:40 <smiles> +1 15:25:58 <Luc> q+ 15:26:03 <GK> I think the most important reviews of PROV-O will come from implementers like Stian 15:26:22 <Curt> luc: for next week, editors of the documents should identify specific questions for reviewers to address 15:26:37 <khalidbelhajjame> @Graham, Stian is part of the provo team :-) 15:26:53 <Curt> pgroth: this is a review to determine public release, should they go public? 15:26:58 <pgroth> q? 15:27:00 <pgroth> ack Luc 15:27:05 <pgroth> Topic: Primer <pgroth> Summary: An update on the status of the primer was given. Input was given to Simon by Stian and Paolo. Simon is looking for examples for some of the constructs and was pointed to the coverage page. The primer should be on schedule for release. Reviewers were identified for the next release: Paolo, Christine, Curt 15:27:06 <GK> @Khalid - Even better! 15:27:07 <Curt> luc: that is one question, there may be others 15:27:42 <Zakim> -??P10 15:27:52 <Curt> gk: still revising, determine if other docs are stable to incorporate any change back into the primer 15:28:18 <GK> @Curt ^^ That was Simon, I think 15:28:34 <Curt> s/gk/smiles/ 15:28:37 <pgroth> q? 15:29:03 <Curt> smiles: looking for examples to put in 15:29:11 <Curt> tlebo: use the big example collection online 15:29:23 <Zakim> +??P10 15:29:37 <Curt> smiles: examples organized by domain, not by concept -- need to find focused examples for concepts 15:30:02 <Curt> tlebo: we might try to pick trivial examples for each concept 15:30:26 <Curt> ... look at the descriptions -- it lists the constructs that various examples use 15:30:37 <pgroth> q? 15:30:40 <pgroth> q? 15:30:49 <pgroth> Primer Reviewers 15:30:50 <Curt> ... might be out of date, let me know if something needs to get updated 15:30:58 <Paolo> +1 15:30:58 <tlebo> coverage page: shows which constructs are used in which examples (or did, or should...) 15:30:59 <Christine> +1 if you think it would be useful 15:30:59 <Curt> +1 15:31:05 <Zakim> -??P10 15:31:19 <Luc> Will review, but may not meet deadline if still editing prov-dm-* 15:31:27 <pgroth> Topic: Schedule <pgroth> Summary: The group revisited the schedule based on current progress. The following time table was agreed to: April 2 - drafts released to the working group for review. April 9 reviews submitted. A vote on release will happen on April 12 if possible but otherwise on April 19. 15:31:41 <smiles> @tlebo great, thanks 15:31:49 <Curt> pgroth: schedule -- editors can you meet the target dates? 15:31:51 <pgroth> q? 15:32:03 <Paolo> q+ 15:32:15 <tlebo> @smiles, some of it looks broken, if there's a particualr question you need answered, point it out to me, please. 15:32:21 <GK> Might it be helpful to stagger releases, so reviewers aren't overcommitted? 15:32:36 <Curt> paolo: two out of three parts, next friday possible, part 2 maybe the next week 15:32:41 <pgroth> ack Paolo 15:32:48 <tlebo> q+ 15:32:51 <Curt> luc: yes, I would like to do that 15:33:11 <tlebo> Friday is reasonable target, early the follwoing week is realistic 15:33:12 <Curt> luc: PROV-DM,PROV-N by friday; constraints early the next week 15:33:32 <GK> It might be difficult for me to get a printed copy for review oif not available by 3-Apr 15:33:32 <Curt> tlebo: next friday possible, early the next week more realistic for PROV-O 15:33:47 <Curt> smiles: next friday ok 15:34:11 <Curt> pgroth: how about Monday the second, but earlier if possible 15:34:21 <smiles> Fine by me 15:34:22 <Luc> review timetable? 15:34:52 <Curt> pgroth: if we do Monday 2nd, then use 1 week for review 15:34:54 <pgroth> 4/9 for reviews back 15:35:04 <Luc> easter vacations .... 15:35:21 <GK> 1 week for review would be OK for me. 15:35:32 <tlebo> leaves 1.5 weeks to review, no? (was 2 weeks) 15:35:43 <Luc> i can review provo on 4th in time for the 5th telecon 15:35:57 <Paolo> if I am doing just the primer, won't take long. I would like to contribute a new example for collections. So, 2 days 15:36:11 <Curt> pgroth: the 2 weeks was 1 week to review, 1 week to respond to the review 15:36:19 <tlebo> @paul, got it. 1 week to review and 1 week to reflect feedback. 15:36:56 <Curt> luc: release/voting had been planned for 12th, probably not realistic with new schedule, esp. with Easter et al. 15:37:27 <Curt> pgroth: what about 4/19 for formal vote for release 15:37:31 <pgroth> Vote April 19 15:37:33 <Curt> luc: at the latest 15:37:56 <smiles> q+ 15:38:02 <pgroth> ack tlebo 15:38:04 <pgroth> ack smiles 15:38:29 <Curt> smiles: clarify 15:38:49 <Curt> pgroth: one of the questions for review -- are there release blockers? 15:39:07 <Curt> ... if there are things that can be addressed later, that's ok 15:39:41 <Curt> smiles: even non-reviewers need to read enough to determine their vote 15:39:55 <Luc> yes, everybody will be invited to review 15:40:34 <pgroth> Revised schedule 15:40:43 <pgroth> 4/2 for release to reviewers 15:40:54 <pgroth> and working group 15:41:12 <pgroth> 4/9 reviews in 15:41:23 <pgroth> 4/19 vote by working group 15:41:27 <pgroth> q? 15:41:37 <tlebo> looks fine 15:41:49 <Paolo> works for me 15:41:50 <satya> works for me 15:41:53 <jun> +1 15:42:00 <jcheney> I may need another day or two = the period from 4/2-4/9 is super busy for me 15:42:00 <Curt> luc: potentially earlier, perhaps 4/12 if possible 15:42:06 <khalidbelhajjame> good for me 15:42:18 <smiles> Yes, possible I think 15:42:45 <Curt> pgroth: reviewers should focus on question of release 15:42:47 <pgroth> q? 15:42:58 <pgroth> Topic: Namespace Unification <pgroth> Summary: The idea for a common namespace across the various products of the WG has been proposed a number of times. Paul put out a concrete proposal to adopt a particular namespace with a corresponding landing page. This approach seemed to have broad support in the group, however, there were questions about the ramifications of a choice of namespace on both XML and rdf processing tools (i.e. do we have a # or not in the namespace). Sandro agreed to ask xml experts on the issue and get back to the group with their opinion. 15:43:11 <pgroth> 15:43:37 <pgroth> 15:43:42 <Curt> pgroth: put out proposal^ 15:43:59 <Curt> pgroth: that would point to landing page with glossary of all the terms 15:44:27 <Curt> ... content negotiation would return OWL/TTL/XSD as requested 15:44:33 <pgroth> q? 15:44:35 <GK> q+ to ask Do tools that try to read ontologies generally generate accept headers? 15:45:08 <pgroth> ack GK 15:45:08 <Zakim> GK, you wanted to ask Do tools that try to read ontologies generally generate accept headers? 15:45:26 <MacTed> voice is there, but it's not OK.... lots of breakup. some is comprehensible, most is not. 15:45:33 <Curt> gk: <breaking up> will the tools be able to retrieve the right thing? 15:45:37 <tlebo> @gk, AFIAK, yes. Tools do request RDF. If they don't, they should. 15:45:46 <Luc> q+ 15:45:52 <pgroth> ack Luc 15:46:27 <Luc> in rdf 15:46:34 <Luc> in xml. 15:46:59 <Curt> luc: I'm fine with pgroth proposal, but we also had a namespace for the XML schema, is the hash compatible? 15:47:30 <Zakim> -??P21 15:47:45 <GK> AFAIK, The choice of XML namespace for XSD preceded the use of namespaces for RDF, and the issue of concatanating namespace+local to forkm a URI didn't arise. 15:47:46 <tlebo> q+ to state that # is part of the fragid, and is taken off before HTTP request. Also, all w3 namespaces uses the #. 15:48:00 <Curt> pgroth: if you use RDF, you use the hash, with XML, you don't [??] you still dereference to the same place 15:48:20 <Curt> tlebo: you have to remove the fragement when you request the URI with HTTP 15:48:32 <Curt> s/fragement/fragment/ 15:48:46 <pgroth> sandro are you there? 15:48:50 <Curt> tlebo: others use the hash the way we are proposing 15:48:56 <GK> (I('m looking in XML namespace spec at moment) 15:48:59 <zednik> '#' is for client side processing, yes? 15:49:19 <pgroth> : 15:49:21 <Curt> luc: not sure -- it is frustrating to have to use two different namespaces 15:49:22 <pgroth> : 15:49:29 <sandro> (I am here, pgroth and trying to page in the details) 15:49:39 <Curt> pgroth: XML usage would double the hash 15:49:46 <GK> [Definition: An XML namespace is identified by a URI reference; element and attribute names may be placed in an XML namespace using the mechanisms described in this specification. ] 15:49:53 <GK> That's from XML namespace spec 15:49:59 <sandro> 15:50:07 <GK> That allows a '#' in the namespace URI for XML namespaces 15:50:24 <GK> 15:50:33 <MacTed> Zakim, unmute me 15:50:34 <Zakim> MacTed should no longer be muted 15:50:35 <Curt> sandro: RIF used the hash within the XML usage, didn't get pushback 15:50:38 <MacTed> q+ 15:50:46 <pgroth> ack tlebo 15:50:46 <Zakim> tlebo, you wanted to state that # is part of the fragid, and is taken off before HTTP request. Also, all w3 namespaces uses the #. 15:50:49 <Curt> sandro: the hash is very normal within RDF community 15:51:09 <Curt> macted: hash is problematic, esp. since it is really a client side thing 15:51:10 <GK> q+ to note that my reading of spec says '#' OK in XML namespace ... see notes above 15:51:30 <pgroth> ack MacTed 15:51:31 <GK> Tools that send '#' are BROKEN 15:51:31 <Curt> macted: a small number of tools send it to the server 15:51:53 <MacTed> Zakim, mute 15:51:53 <Zakim> I don't understand 'mute', MacTed 15:51:55 <pgroth> can you not talk into your mike 15:51:56 <MacTed> Zakim, mute me 15:51:56 <Zakim> MacTed should now be muted 15:52:24 <Curt> pgroth: how can we best resolve this? 15:52:50 <Curt> pgroth: this plan sounds good, but how can we determine if it is correct? 15:53:14 <Curt> sandro: I'll consult with XML experts, schema workgroup, etc. 15:53:45 <Curt> pgroth: semantic web activity group? 15:53:54 <GK> What we could do for now is choose a '#' URI and document our rationale that this is OK in XML (see above), and ask for explcit review in PWD. 15:53:58 <Curt> sandro: this is really an XML question 15:54:25 <Curt> sandro: could also ask semantic web coordination group 15:54:31 <tlebo> refers to #used at -- isn't this the same as what luc's xml schema is referencing? 15:54:35 <tlebo> q+ 15:54:43 <pgroth> ack GK 15:54:43 <Zakim> GK, you wanted to note that my reading of spec says '#' OK in XML namespace ... see notes above 15:54:46 <GK> ack gk 15:54:48 <Curt> sandro: will draft an email requesting input from others 15:54:55 <pgroth> ack Luc 15:54:59 <pgroth> ack tlebo 15:55:27 <Curt> tlebo: namespace shouldn't have the hash 15:55:37 <Curt> sandro: do any tools break? 15:56:20 <GK> RDF really likes the namespace to end with '#' or '/' - so that the parts can be teased apart later. 15:56:28 <Curt> luc: esp. with RDFa, you are using RDF and XML together, namespace declarations just define 'prov' 15:56:32 <pgroth> q? 15:56:39 <sandro> <prov xmlns="">... 15:56:41 <MacTed> are there any known examples where NOT having the # in the namespace leads to problem? 15:56:41 <MacTed> we've come up with various ways having it *MIGHT* cause trouble... 15:56:41 <MacTed> so why do we *want* it to be part of the namespace? 15:56:45 <MacTed> what's the argument to include it? 15:56:48 <GK> RDF/XML commonly uses XML namespace decls with '#' at end of URI 15:57:04 <Luc> q+ 15:57:15 <Luc> 15:57:18 <pgroth> ack Luc 15:57:26 <Curt> luc: see blog^ she talks about this problem 15:57:41 <Curt> luc: maybe she could help us 15:57:53 <GK> Yes, that;s the issue - RDF concatenates, XML doesn't assume the pair are used to create a new URI 15:58:06 <Curt> pgroth: let's consult with all these groups/people to figure out the right common namespace 15:58:27 <GK> I think a common namespace is nice, but if we can't it's not a total disaster IMO 15:58:45 <pgroth> q? 15:58:50 <Curt> sandro: will review the blog and include jeni as well 15:59:00 <Zakim> -khalidbelhajjame 15:59:02 <Zakim> -tlebo 15:59:02 <Zakim> -dgarijo 15:59:03 <Zakim> -Satya_Sahoo 15:59:03 <Zakim> -Paolo 15:59:07 <Zakim> -sandro 15:59:09 <Zakim> -jcheney 15:59:12 <Zakim> -[IPcaller] 15:59:13 <Zakim> -MacTed 15:59:23 <Zakim> - +1.443.708.aabb 15:59:25 <Zakim> -pgroth 15:59:31 <Zakim> -Luc 15:59:35 <Zakim> -Curt_Tilmes 15:59:46 <GK> - this may be Jeni's blog post 16:00:06 <GK> Dated 2007, "Things that make me scream ..." 16:00:46 <pgroth> rrsagent, set log public 16:00:51 <pgroth> rrsagent, draft minutes 16:00:51 <RRSAgent> I have made the request to generate pgroth 16:00:56 <pgroth> trackbot, end telcon 16:00:56 <trackbot> Zakim, list attendees 16:00:57 <Zakim> As of this point the attendees have been Curt_Tilmes, [IPcaller], Satya_Sahoo, Luc, MacTed, tlebo, +1.443.708.aabb, pgroth, Paolo, dgarijo, sandro, GK, jun, jcheney, 16:00:59 <Zakim> ... khalidbelhajjame 16:01:04 <trackbot> RRSAgent, please draft minutes 16:01:04 <RRSAgent> I have made the request to generate trackbot 16:01:05 <trackbot> RRSAgent, bye 16:01:05 <RRSAgent> I see no action items # SPECIAL MARKER FOR CHATSYNC. DO NOT EDIT THIS LINE OR BELOW. SRCLINESUSED=00000402 | https://www.w3.org/2011/prov/wiki/Chatlog_2012-03-22 | CC-MAIN-2016-44 | refinedweb | 4,445 | 66.98 |
This is your resource to discuss support topics with your peers, and learn from each other.
03-03-2010 11:30 AM - edited 03-03-2010 11:31 AM
Hello,
know I have another question!
I want to change the size from a HFM or VFM! I try it with sublayout() and with setExtent(). But I think the only value I set is the maximum width or height, but I want to set the permanent size of the manager. Know the manager is so wide like the field which is in it. Anybody understand me and can help me?
regards Maja
03-03-2010 11:49 AM
Did you call setExtent before or after the call to super.sublayout?
03-04-2010 03:14 AM
Know I call setExtent() only!
public CustomVerticalFieldManager(long style, int width, int height){ super(style); super.setExtent(width, height); } protected void paint(Graphics graphics) { graphics.setBackgroundColor(); graphics.setColor(); graphics.clear(); super.subpaint(graphics); }
03-04-2010 08:54 AM - edited 03-04-2010 08:55 AM
So ok maybe I can explain it a little bit more!
I want that it looks like:
--------------------------------------------------
| | |
| | Field1 |
| Field | |
| | Field2 |
| | |
--------------------------------------------------
Know it looks like
--------------------------------------------------
| | |
| |Field1|
|Field| |
| |Field2|
| | |
--------------------------------------------------
anybody an idea?
03-04-2010 01:09 PM
Here's a quick-and-dirty Manager that uses half the width of the screen. You could put two of these in a HorizontalFieldManager and your layout would look like your picture.
NB: this is not necessarily good Manager design, it's just an example that works.
public class HalfWidthManager extends VerticalFieldManager { private int halfScreenWidth = Display.getWidth() / 2; protected void sublayout(int width, int height) { super.sublayout(getPreferredWidth(), height); setExtent(getPreferredWidth(), getPreferredHeight()); } public int getPreferredWidth() { return halfScreenWidth; } }
10-30-2012 03:02 AM
Can we set width and height of HFM and VFM object without subclassing them ?
Are there any methods that sets the width and height directly on objects of HFM and VFM .
HorizontalFieldManager mTitleFieldManager = new HorizontalFieldManager(); mTitleFieldManager.anyMethodToSetWidthOrHeight();
Any help ?
10-30-2012 05:20 AM
"Can we set width and height of HFM and VFM object without subclassing them ?"
There are cases where you can set height to width, using style bits like USE_ALL_WDITH. But these specific layout managers have been designed to take all the width (for HorizontalFieldManager, and height (for VerticalFieldManager) that they need. Given this design criteria, the RIM developers did not feel it necessary to offer the methods you are suggesting.
However there is nothing stopping you writing your own manager that does this, or extending HFM or VFM to attempt to do this. I suggest you try to write your own Manager, the effort of doing this will make you appreciate what is going on in the supplied Managers better too I think.
"Are there any methods that sets the width and height directly on objects of HFM and VFM"
Pretty much the same comments apply to this question too.
Does this help or have I misunderstood the question?
11-02-2012 07:56 AM
Hi peter
You got everything absolutely correct. Thanks for your reply.
It means we cannot provide hardcoded values (like field.setwidth(100Units) or field.setHeight(100Units)) to the width and height properties of a particular field or manager.
Yes will do the necessary subclassing. | https://supportforums.blackberry.com/t5/Java-Development/Size-of-FieldManager/m-p/1969159/highlight/true | CC-MAIN-2017-13 | refinedweb | 544 | 57.67 |
Convolutions for Fashion MNIST in Python
In this tutorial, let us find out how to use convolutions for fashion MNIST with Python. Fashion MNIST data set consists of Zalando’s article images of a training set of 60,000 examples and a test set of 10,000 examples. Often used for bench marking machine learning algorithms. Let us see how to classify images with a simple example.
Introduction:
For this we define a neural network consisting of convolution layers in addition to pooling layers. For instance we need to distinguish between a shirt and a shoe, let us see an example.
Fashion MNIST example:
Let us see the example step by step.
1. Importing necessary Python libraries.
First let us import the libraries required for this example. First let us import the libraries required for this example.
import tensorflow as tf import numpy as np from tensorflow import keras
2.The callback function.
Here we define a callback function to stop the training after particular metric. Therefore further epochs need not be executed.
class CustomCallbacks(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('acc')>0.998): print("\n 99% acc reached") self.model.stop_training = True
Here we see that if the accuracy reaches above 0.988 the training stops.
3. Training the data.
As we can see there is presence of pooling layers. The Convolution layers in a CNN summarize the presence of features in an input image.
The pooling layer is used to:
- Down sample the detection of features in feature maps.
- Calculate and implement average and maximum pooling in a CNN.
- Global pooling in a CNN.
We use maximum pooling in the below example, which reduces the matrix size depending on the pooling dimensions.
def preprocess_images(image_set): image_set = image_set.reshape(-1, 28, 28, 1) image_set = image_set / 255.0 return image_set mnist = tf.keras.datasets.mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() training_images = preprocess_images(training_images) test_images = preprocess_images(test_images) model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ])
4. Compiling and testing the Data.
Finally, we then test the data and see if the accuracy is above a certain value, the training stops. In conclusion, we are improving the dataset by using convolutions. Below is the Python code for this:
model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) model.fit( training_images, training_labels, batch_size=64, epochs=20, callbacks=[CustomCallbacks()] )
Output:
Epoch 1/20 60000/60000 [==============================] - 82s 1ms/sample - loss: 0.1793 - acc: 0.9467 Epoch 2/20 60000/60000 [==============================] - 82s 1ms/sample - loss: 0.0551 - acc: 0.9827 Epoch 3/20 60000/60000 [==============================] - 76s 1ms/sample - loss: 0.0354 - acc: 0.9889 Epoch 4/20 60000/60000 [==============================] - 79s 1ms/sample - loss: 0.0248 - acc: 0.9920 Epoch 5/20 60000/60000 [==============================] - 78s 1ms/sample - loss: 0.0179 - acc: 0.9944 Epoch 6/20 60000/60000 [==============================] - 80s 1ms/sample - loss: 0.0144 - acc: 0.9953 Epoch 7/20 60000/60000 [==============================] - 79s 1ms/sample - loss: 0.0111 - acc: 0.9965 Epoch 8/20 60000/60000 [==============================] - 82s 1ms/sample - loss: 0.0071 - acc: 0.9976 Epoch 9/20 60000/60000 [==============================] - 84s 1ms/sample - loss: 0.0089 - acc: 0.9973 Epoch 10/20 59968/60000 [============================>.] - ETA: 0s - loss: 0.0047 - acc: 0.9986 99% acc reached 60000/60000 [==============================] - 87s 1ms/sample - loss: 0.0047 - acc: 0.9986
The Callback function is present. Therefore only 10 epochs are executed as the accuracy level is reached.
In conclusion, convolution improves the dataset. | https://valueml.com/convolutions-for-fashion-mnist-in-python/ | CC-MAIN-2021-25 | refinedweb | 609 | 55.5 |
Presentation of local sensor with GatewayESP8266MQTTClient seems to fail
Hi MySensors,
I was doing some tests yesterday with an ESP8266-01 as an MQTT Client Gateway. Really impressive work from you Henrik and the rest of the team.
When trying to add a local sensor to the ESP8266MQTTClient Gatway, the Presentation part doesn't seems to work. Nothing is being sent to the MQTT Broker.
#include <ESP8266WiFi.h>
#include <MySensor.h>
MyMessage msg(1,V_TRIPPED);
void setup() {
}
void presentation() {
// Present locally attached sensors here
sendSketchInfo("Test", "1.0");
present(1, S_DOOR);
}
If I add the same commands to the loop they're being sent forward to the Broker.
void loop() {
// Present locally attached sensors here
sendSketchInfo("Test", "1.0");
present(1, S_DOOR);
wait(5000);
}
I'm using ESP8266-01 for my tests without any radio (NRF24L01/RFM69) attached.
The rest is working great, so far.
// Enables and select radio type (if attached)
//#define MY_RADIO_NRF24
//#define MY_RADIO_RFM69
I'm using the development branch, and it's up-to date.
Hmm.. that has probably been forgotten for the MQTT client gateway...
Could you try adding:
if (presentation) presentation();
Here: | https://forum.mysensors.org/topic/3955/presentation-of-local-sensor-with-gatewayesp8266mqttclient-seems-to-fail/1 | CC-MAIN-2020-29 | refinedweb | 187 | 58.48 |
Details
Description
When using a String constant as the value for an annotation groovyc errors out with the following message:
Attribute 'value' should have type java.lang.String but found type java.lang.Object in @SpringBean
I've attached sample code to reproduce. The annotation and PersonDao are regular Java classes, just as was my case when finding the bug. The PersonAction is a Groovy class.
Issue Links
- duplicates
GROOVY-2827 org.codehaus.groovy.ast.expr.PropertyExpression when using external constants in annotations
Activity
Not sure it matters whether we call it a bug or enhancement request. It isn't supported now and seems a very worthwhile (necessary?) enhancement.
I was thinking the same thing as Paul, FWIW
You are right. It does look a worthwhile feature but if it more like an enhancement, then it may not be scheduled for 1.6, right?
Or, enhancements are still being taken up for 1.6?
It can be seen as improvement or as bug. But knowing that the groovy compiler does no form of inlining atm and this issue means we have to add that I would say it should not go into 1.6.0, but 1.6.1 might be ok
It is a bug, not an improvement
I haven't double checked how it's working in Java, but since the PersonDao.DAO_ID field is a String constant, it should be allowed in Java.
And hence in Groovy.
I wish it could be fixed in 1.6.0, but if it's not, it should really be fixed in 1.6.1.
It works in Java. I had double checked that earlier but then I saw that mailing list thread reply and thought that groovy annotations had some known constraints and were not as flexible as Java.
Groovy's annotations should work as much as possible as in Java.
But it doesn't prevent us from providing additional capabilities
But at least, here, I think it should behave just as in Java.
I think I agree with Guillaume's last comment. But just so that we all understand the implications. Consider this code example:]) // *1 class Child2 extends Base {} assert new Child1().run() == ['foo'] assert new Child2().run() == ['bar', 'baz']
Currently *1 breaks because we are expecting a static String but get a PropertyExpression that would evaluate at runtime to a constant.
The implication if we somehow evaluate this is that we are bypassing any runtime behavior, i.e.
if Base had any MOP in place which changed the value of CONST at runtime, that would be ignored here.
I believe that is the right thing. Just confirming everyone's opinions.
isn't that equal to a problem you showed me in Paris? Where we found that we cannot access the constant value through reflection without initializing the class? And where we said that we maybe have to say, that we don't support that particular part? So from the language side it would be good to have that, but from the technical side I don't know how to implement that. As of runtime vs. compile time... I agree with Paul here
I think the attached patch will cover most cases but there is quite likely a better way to do it. As per the issue Jochen and I discussed in Paris, you can't wait until (say the ExtendedVerifier) and do checking in one spot because by then 'constants' are actually pulled out of 'fields' and placed into a static initializer. This meant that I had to try 'statically resolving' the constants earlier. I did it in ResolveVisitor and StaticImportVisitor. Happy for other suggestions. If I don't get feedback in the next couple of days, I will apply as is and we can tweak later if need be.
If anyone is interested, here is the test case I was using:
import java.lang.annotation.* import static Constants.BAR @Retention(RetentionPolicy.RUNTIME) @Target([ElementType.METHOD, ElementType.FIELD]) @interface Anno { String value() default "" String[] array() default [] } class Constants { static final String FOO = "foo" static final String BAR = "bar" } class ClassWithAnnotationUsingConstant { @Anno(array = [Constants.FOO, BAR, org.objectweb.asm.Opcodes.INVOKEDYNAMIC_OWNER]) public annotatedField } assert ClassWithAnnotationUsingConstant.getDeclaredField('annotatedField').annotations[0].value() == ['foo', 'bar', "java/lang/dyn/Dynamic"]
Making use of InvokeDynamic parts of ASM 3.2 (locally on my machine) already!
fix and test applied to trunk (pending merge with 1_6_X branch but I will wait a day to let dust settle and make sure no catastrophes)
But Paul... am I right assuming that
import java.lang.annotation.* import static Constants.BAR @Retention(RetentionPolicy.RUNTIME) @Target([ElementType.METHOD, ElementType.FIELD]) @interface Anno { int value() default -1 } class ClassWithAnnotationUsingConstant { @Anno(value = Integer.MAX_VALUE) public annotatedField } assert ClassWithAnnotationUsingConstant.getDeclaredField('annotatedField').annotations[0].value() == Integer.MAX_VALUE
will not work? IMHO the solution you provided looks for a ConstantExpression and if that is there the value can be used. If not, then it is a problem. Assume that in your example Constants is precompiled and you get exactly the same problem, even if it is a groovy class. The solution you gave works only with not precompiled classes or will have unwanted side effects. using Annotation constants is a different thing, because here the constant can be read without executing the static initializer. Because of that for example @Target([ElementType.METHOD, ElementType.FIELD]) works in Groovy.
But I am against a solution that works sometimes under some special occurrences only. So I am also against this fix.
The example you give (at least after removing the import to Constants which isn't around in your example) will work fine and having it work for Java constants was my main motivation but I understand your reservations.
We can't at the moment make it work for constants in pre-compiled Groovy classes but it will for constants in pre-compiled Groovy interfaces. So, sniffing around looking for the constant expressions is a bit of a compromise trying to cater for some of the more common cases.
Can you think of a better approach? I don't think not supporting Java cases is a nice option as existing Java libraries already have such usage patterns when used from Java.
if that example is working then I missed out part of your change. Before your patch, if you asked the ClassNode of Integer for the FieldNode MAX_VALUE, you got no initialExpression, so you could not get an constant expression and no value to use... right, I missed out this part:
try { if (type.isResolved()) { Field field = type.getTypeClass().getField(pe.getPropertyAsString()); if (field != null) { return new ConstantExpression(field.get(null)); } } } catch(Exception e) {/*ignore*/}
If the class has an static initializer, then this code here will cause the static initializer to be executed, else it is impossible to get the value. And I thought we don't want this to happen. Btw, this part of the code forgets to check that the field is static, but you swallow the exception anyway... which is another part I don't like. If we execute the static initializer, then why making things even worse by swallowing any exception that initializer may throw? Then I don't understand your text about interfaces. Normal interfaces are not that much different from normal classes. They have an static initializer too, and that one will get executed as well. Only in case of an annotation it is possible to read the value directly without first executing the static initializer.
Also it is a bit unclear to me why most of your code is in StaticImportVisitor. If I got it right, then you transform ClassNode.Field variant used by a PropertyExpression, even if that is outside of an annotation. If we are going to add such dangerous code, that executes static initializers, then we should not make matters worse and execute it for parts we don't even need... that is unless I misread the code and it is really limited to annotations... If it is limited to annotations, then it should be in an annotations handling visitor or a new visitor. It is no good to just enlarge the existing visitors, especially not the big ones. Your argument that you cannot do it in ExtendedVerifier is one I cannot follow. Sure, there the values are pulled out, but what is so bad for this? Why not change AnnotationVisitor to do exactly that? It is not like the constant will have any value for us in other parts at the moment.
As for precompiled Groovy classes. I don't folow that argument. The code you added will execute the static initializer, thus it will not make any difference between precompiled Groovy code or Java code, regardless of being a class or interface. The only case we can safely support is groovy code we currently compile, which is too limited.
Can I think of a better approach that works in all cases? No. We could try reading the class in bytecode and extract this information from there, but that is lot more complicated and will not work if we don't have the bytecode.. which at runtime is a common case.
The ClassNode.Field variant is only looked at when inside annotations unless I made a mistake in the code that checks that. So, yes we are executing the static initializer but for what should be only a very small handful of classes. I'll have a think about how to move the code. The reason I put it where I did was because I couldn't get it to work in ExtendedVerifier. I might ask for your assistance later. Do you know what the javac compiler does here? Do you know if it has equivalent code that would cause static initializers to be executed?
javac is a different problem domain, since javac has always the byte or the source code. javac must inline the constant because no other option is allowed. that means javac will read the bytecode, extract the value and then... just found an interesting corner case for javac:
class Constants { final static String FOO; static { FOO = "foo"; } } class ClassWithAnnotationUsingConstant { @Anno(value=Constants.FOO) public Object annotatedField; }
This code does not compile. And indeed the inline version is represented different in bytecode. Now that opens a new issue for Groovy. To allow this usage pattern Groovy has to do it the same way, meaning inline. If not then it will make problems even from Java. Sadly reflection does not provide any way to go around this issue. There is only one way, and that will get the static initializer being executed.
Have you come to a conclusion on how to solve this issue? We frequently use String constants in annotations, and it's very awkward that Groovy forces us to inline them.
I test EL evaluator on my bean in Spock. Because of this bug I am not able to compile the code.
class VisibleAndEditableEntity { public static final String PASSING_CONDITION = "#{e.age > 20}"; public static final String FAILING_CONDITION = "#{e.age < 20}"; int age = 25; @Visible(PASSING_CONDITION) Object visiblePassed; @Visible(FAILING_CONDITION) Object visibleFailed; @Hidden(PASSING_CONDITION) Object hiddenPassed; @Hidden(FAILING_CONDITION) Object hiddenFailed; }
AnnotationReaderFieldVisibilityGroovyTest.groovy: 87: expected 'PASSING_CONDITION' to be an inline constant of type java.lang.String not a field expression in @za.co.fnb.csip.jastin.annotation.Visible @ line 87, column 14. @Visible(PASSING_CONDITION) (and so on)
That's unacceptable. When I explicitly say public static final String, @Visible(PASSING_CONDITION) should be allowed!]) class Child2 extends Base {} assert new Child1().run() == ['foo'] assert new Child2().run() == ['bar', 'baz', 'bing']
does work with Groovy 2.1.7, so I guess this was fixed?
Pascal, it works if you are in the same source unit. I think you'll find that if you place a constant in a separate file, e.g.:
class Constants { static final String OTHER = 'fizz' }
and reference that in your script above we still have a problem. I think though, we might have re-jigged how such constants are represented in our files and perhaps some rework might now be possible.
I've found in Grails that if I specify "public", this works. e.g.
public static final String ADMIN = "ROLE_ADMIN"
compared to
static final String ADMIN = "ROLE_ADMIN"
Is there any progress on this issue? I can confirm that the generated class file for the Groovy class with the constant properly presents the string as a java.lang.String constant, but the compiler still generates a bogus error trying to use it in an annotation parameter from outside the class.
Ugh. Just hit this myself in grails (2.3.7) trying to pass a static final Class array to a @Mock() annotation. 5+ years and no resolution? Kinda silly to have to inline things.
(Threw me for a loop because IntelliJ doesn't complain, nor does IntelliJ "make" complain, but a "rebuild" does give the error: "@Mock annotation expects a class or a list of classes to mock")
Going to try the 'public' based on Edward's comment. 'public' forces it to be a field instead of a property, correct?
UPDATE: adding 'public' to my 'static final Class[]' made no difference. Same error.
As per and looking at the code, it looks like annotation values in groovy can only be constant values (like Strings, classes, numbers, other annotations and enums, etc).
In this case, annotation value itself is a property expression PersonDao.DAO_ID, which is pointing to a static final String but in terms of groovy internals, it is not a constant expression but a property expression.
So, should this case be seen as a defect or as designed? | http://jira.codehaus.org/browse/GROOVY-3278?focusedCommentId=161183&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-06 | refinedweb | 2,268 | 57.67 |
I need to get the line numbers of certain keys of a YAML file.
Please note, this answer does not solve the issue: I do use ruamel.yaml, and the answers do not work with ordered maps.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ruamel import yaml
data = yaml.round_trip_load("""
key1: !!omap
- key2: item2
- key3: item3
- key4: !!omap
- key5: item5
- key6: item6
""")
print(data)
CommentedMap([('key1', CommentedOrderedMap([('key2', 'item2'), ('key3', 'item3'), ('key4', CommentedOrderedMap([('key5', 'item5'), ('key6', 'item6')]))]))])
!!omap
print(data['key1'].lc.line) # output: 1
print(data['key1']['key4'].lc.line) # output: 4
print(data['key1']['key2'].lc.line) # output: AttributeError: 'str' object has no attribute 'lc'
data['key1']['key2]
str
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ruamel import yaml
DATA = yaml.round_trip_load("""
key1: !!omap
- key2: item2
- key3: item3
- key4: !!omap
- key5: item5
- key6: item6
""")
def get_line_nb(data):
if isinstance(data, dict):
offset = data.lc.line
for i, key in enumerate(data):
if isinstance(data[key], dict):
get_line_nb(data[key])
else:
print('{}|{} found in line {}\n'
.format(key, data[key], offset + i + 1))
get_line_nb(DATA)
key2|item2 found in line 2
key3|item3 found in line 3
key5|item5 found in line 5
key6|item6 found in line 6
This issue is not that you are using
!omap and that it doesn't give you the line-numbers as with "normal" mappings. That should be clear from the fact that you get 4 from doing
print(data['key1']['key4'].lc.line) (where
key4 is a key in the outer
!omap).
As this answers indicates,
you can access the property lc on collection items
The value for
data['key1']['key4'] is a collection item (another
!omap), but the value for
data['key1']['key2'] is not a collection item but a, built-in, python string, which has no slot to store the
lc attribute.
To get an
.lc attribute on a non-collection like a string, is non-trivial: you would have to subclass the RoundTripConstructor, to use something like the classes in
scalarstring.py (with
__slots__ adjusted to accept the
lc attribute and then transfer the line information available in the nodes to that attribute. | https://codedump.io/share/zJrNOuHEPROH/1/parsing-yaml-get-line-numbers-even-in-ordered-maps | CC-MAIN-2019-09 | refinedweb | 357 | 74.69 |
LLDB API Documentation
#include <SBModule.h>
Definition at line 21 of file SBModule.h.
Find functions by name.
Find global and static variables by name.
Get const accessor for the module file specification.
This function returns the file for the module on the host system that is running LLDB. This can differ from the path on the platform since we might be doing remote debugging.
Get accessor for the module platform file specification..
Get.
Get accessor for the symbol file specification.
When debugging an object file an additional debug information can be provided in separate file. Therefore if you debugging something like '/usr/lib/liba.dylib' then debug information can be located in folder like '/usr/lib/liba.dylib.dSYM/'.
Get a type using its type ID.
Each symbol file reader will assign different user IDs to their types, but it is sometimes useful when debugging type issues to be able to grab a type using its type ID.
For DWARF debug info, the type ID is the DIE offset.
Get all types matching type_mask from debug info in this module.
Get the module version numbers.
Many object files have a set of version numbers that describe the version of the executable or shared library. Typically there are major, minor and build, but there may be more. This function will extract the versions from object files if they are available.
If versions is NULL, or if num_versions is 0, the return value will indicate how many version numbers are available in this object file. Then a subsequent call can be made to this function with a value of versions and num_versions that has enough storage to store some or all version numbers.
Set.
If file specifies a full path to an install location, the module will be installed to this path. If the path is relative (no directory specified, or the path is partial like "usr/lib" or "./usr/lib", then the install path will be resolved using the platform's current working directory as the base path.
Definition at line 299 of file SBModule.h.
Definition at line 300 of file SBModule.h.
Definition at line 301 of file SBModule.h.
Definition at line 302 of file SBModule.h.
Definition at line 303 of file SBModule.h. | http://lldb.llvm.org/cpp_reference/html/classlldb_1_1SBModule.html | CC-MAIN-2018-26 | refinedweb | 378 | 67.76 |
Hi,
I have a view that queries all data in my model (DrinkModel) and passes values to a table. I want to add a column to the table from a function that creates a list. If I pass the second list to the template i need a second iteration and effective just produce a column below the table.
My view:
def d_list(request):
drinks = models.DrinkModel.objects.all()
print(drinks)
duration_qs = duration_queryset()
return render(request, ‘list.html’, {‘drinks’: drinks, ‘duration_qs’: duration_qs})
My template:
{% for drink in drinks %}
<tr> <td>{{ drink.pk }}</td> <td><a href="{% url 'detail' drink.id %}"/> {{ drink.dn }}</td> <td>{{ drink.ds }}</td> <td>{{ drink.df }}</td> <td>{{ drink.dt }}</td> </tr> {% endfor %} {% for qs in duration_qs %} <tr> <td>{{ qs }}</td> </tr> {% endfor %}
Is there a way to iterate over duration_qs so that it lines up as the far right column of the first table?
Many thanks,
Brad | https://forum.djangoproject.com/t/creating-one-table-from-two-lists-in-django-template/5372 | CC-MAIN-2022-21 | refinedweb | 151 | 76.82 |
Hi all,
I am trying to upload sketches from one Arduino (a mega2560) to another (a pro mini) through Serial, and I have trouble getting the two boards in sync over Serial.
The code works perfectly between the mega and a UNO, however with the pro mini I get loads of 0x0 from Serial.read().
I never read unless Serial.available() has returned true; I don't see 0x00 described as a special value in the Serial doc?
Here is a sample output: after 7-8 attempts I get a valid response from the pro mini, but the next command (get signature) fails when I again read a 0x0.
Stk500 started at 38400 STK: Created -> Begun Resetting target board... done. Synching at 38400 bps..14 RCV 0x10 done. AVR device initialized and ready to accept instructions. SND 0x75 0x20 RCV 0x0 Could not read device signature: 0x15
The code I use to read Serial is below; the same code with no timeout detection yields the same results:
uint32_t start = millis(); while (!_line.available()) { if (millis() - start > STK_TIMEOUT) { return (uint8_t) Stk::NOSYNC; } }; uint8_t b = (uint8_t) _line.read(); #ifdef DEBUG _ui.print(F("RCV")); printByte(_ui, b); _ui.println(); #endif ...
I have also tried to save _line.read() into an int to check for -1, and that isn't the problem, it's indeed 0.
Any hint??
Thanks!
Franck | https://forum.arduino.cc/t/help-needed-with-serial-issue-between-two-arduinos/514363 | CC-MAIN-2022-05 | refinedweb | 227 | 74.08 |
I am trying to include a ".jsx" file so i can use their functions i've written.
Now when i use:
#include "filename.jsx"
i only get an error message when i add the extension in Photoshop CC
i think the #include statement must have a correct path, or the file won't be found, now my question would be.
Which path das #include use?
Or,
How can i include a .jsx file which is in the xxx.assets Folder within the extension Folder?
e.g. myScript.jsx inside the myScript.assets Folder, to access a function named myFunction()...
Retrieving data ... | https://forums.adobe.com/thread/1256445 | CC-MAIN-2018-26 | refinedweb | 101 | 78.85 |
XSL stylesheets begin with the XML declaration because they are well- formed XML documents, so planets.xsl starts with this same declaration:
<?xml version="1.0"?> . . .
The XML declaration is stripped off by the XSLT processor immediately, however, and wont figure in our XSLT discussion. The first element of an XSL stylesheet that is pure XSL is the <xsl:stylesheet> element (not to be confused with the <?xml-stylesheet?> processing instruction, which goes in the XML document). Some people have objected to the name of this element, because its usually used in XSLT transformations, so W3C also allows you to refer to this element as <xsl:transform> .
Heres how you use this element:
<?xml version="1.0"?> <xsl:stylesheet . . .
The following list includes the attributes of <xsl:stylesheet> :
id (optional). Used to identify the stylesheet. Set to an XML name.
version (mandatory). Sets the version of XSLT needed to work with the stylesheet. This value is normally set to 1.0 currently. You can also set this value to 1.1; although, because XSLT 1.1 is not going to go past the working draft stage, this will probably not be a legal value as far as W3C is concerned .
extension-element-prefixes (optional). Defines the extensions in the stylesheet used to identify extension elements. Set to a whitespace-separated list of NCNames .
exclude-result-prefixes (optional). Specifies the namespaces in the stylesheet that should not be copied to the output (unless they are intentionally used in the output document). Set to a whitespace-separated list of NCNames .
The content of this element can consist of any of the following top-level XSL elements: <xsl:attribute-set> , <xsl:decimal-format> , <xsl:import> , <xsl:include> , <xsl:key> , <xsl: namespace-alias > , <xsl:output> , <xsl:param> , <xsl: preserve-space > , <xsl: strip-space > , <xsl:template> , or <xsl:variable> . XSLT 1.1 added <xsl:script> to this list.
Note that the id attribute of this element can be used when you want to refer to a particular stylesheet (and note that you should have an XSLT processor that also reads DTDs or XML schemas in this case).
The version attribute is mandatory, and currently can be set to 1.0. You can also set this value to 1.1 for the XSLT 1.1 working draft; however, because XSLT 1.1 is not going past the working draft stage, 1.1 will probably not be considered a legal value for this attribute in the long run. Im going to set the version attribute to 1.0 in this book, because thats the current W3C XSLT recommendation, and version 1.1 is not going to progress beyond working draft stage. As mentioned in Chapter 1, the W3C has also released the requirements for XSLT 2.0, so that will be the next version.
Note that XSLT elements such as <xsl:stylesheet> use the namespace prefix xsl , which, now that XSLT has been standardized, is always set to. That namespace is usually set with the xmlns attribute (which is not an XSL attribute, but rather an attribute of any XML element), in the stylesheets root element, <xsl:stylesheet> :
<xsl:stylesheet . . .
XSL stylesheets use their own namespace this way to avoid conflict with the other elements you use in your stylesheet. For example, you might want to indicate what stylesheet was used to transform a document, in which case you might create your own <stylesheet> elementwhich is no problem, because it wont conflict with the XSL element <xsl:stylesheet> .
The namespace prefix customarily used in XSLT stylesheets for XSLT elements is xsl . You can, in fact, use any namespace prefix you want for XSLT elements (or even none at all), but xsl is used almost universally because thats the namespace used throughout the XSLT recommendation.
In practice, this means that all XSLT elements well be using start with the namespace prefix xsl , as in <xsl:stylesheet> . That, then, is how you start an XSLT stylesheet, with the <xsl:stylesheet> element. (There is one exception: simplified stylesheets omit this element, as youll see later in this chapter).
Like any other XML application, XSLT has a well-defined set of rules for what makes an XSLT stylesheet valid. The W3C even defines a pseudo-DTD for XSLT, listing all the syntax rules, and you can find that DTD in Appendix A, which is a good resource if youre ever at a loss to understand some part of XSLT syntax. As Appendix A shows, the <xsl:stylesheet> element can legally contain several other XSLT elements, and those elements are called top-level elements . | https://flylib.com/books/en/1.262.1.39/1/ | CC-MAIN-2020-40 | refinedweb | 762 | 64 |
Peter Torr's blog on HD DVD, JScript, the Pet Shop Boys, and anything else he feels like blogging.
Normal disclaimers apply. I am not responsible for anything, and neither is Microsoft.
Now 'ticks'
< Configuration >
< StreamingBuffer
< Aperture
< MainVideoDefaultColor
</ Configuration >
< MediaAttributeList />
< TitleSet
< Title
< PrimaryAudioVideoClip
< Video
< Audio
</ PrimaryAudioVideoClip >
< ChapterList >
< Chapter
< Chapter
< Chapter
</ ChapterList >
</ Title >
< PlaylistApplication
< PlaylistApplicationResource
</ PlaylistApplication >
</ TitleSet >
</ Playlist >
Looking at the Elements
This will be a very quick look at the elements. Personally I don't mess with playlists too much (I tend to use the same playlist for all my iHD code, with the same background video playing) and I don't have the HD DVD spec with me, so some of this will be off the top of my head.
Playlist
The Playlist element is just the root of the file. Nothing too interesting here except the namespace.
Configuration
The Configurartion element tells the player how to configure video playback for this playlist.
StreamingBufferSize
The StreamingBufferSize element tells the player how much of its memory to reserve for streaming audio / video data from the internet. Since we're not going to be streaming any content in this sample, it is zero. Because HD DVD discs need to play back on a variety of devices (from expensive PCs with gigabytes of RAM to cheap set-top boxes with minimal hardware), the HD DVD specification provides details about how much memory a player must have, and disc authors need to be careful with how they use that memory. I won't go into that in detail right now, but (in theory) the iHDSim program will fail to load your disc if you use up too much memory.
Aperture
Not just an image-editing program from Apple, Aperture is also an element that tells the player how much screen real-estate the playlist will use -- 1280 x 720 or 1920 x 1080. Note that the player will automatically scale these values correctly for different TV sets (eg, a 1080 playlist will still display on a 720 monitor), so you will typically choose 1920 x 1080 unless you only have 720 content.
MainVideoDefaultColor
The MainVideoDefaultColour element is the colour to display if the main video has been scaled to not fill the full aperture. Typically you won't care about this value because you will have video filling the full screen, but in this case I have made it green. (Note that the colour is not specified in the familiar in RGB format; it is specified in the YUV colour space).
MediaAttributeList
The MediaAttributeList is not used here. It would typically be used to store attributes about you audio / video clips that could then be referenced later on. Attributes include things such as the codec used, number of channels of audio, and so on.
TitleSet
The TitleSet element defines all the titles in the playlist. A "title" is a linear path through a set of media files. Typically, titles would be things like the main move, the deleted scenes, a making-of documentary, and so on. Here we set the timeBase to be 60 frames per second, which would be typical for North American usage. We also set the defaultLanguage to be English ("en") which is used to choose other resources later on (like which applications to load).
Title
The Title element specifies the resources needed for a particular title (the movie, the deleted scenes, etc.) Typically this will include one or more "primary" video files; possibly some "secondary" video files (for picture-in-picture); chapter mark information; subtitles; and possibly some specific per-title applications. We give the title a titleDuration (using the timecode notation of hours:minutes:seconds:frames), a titleNumber, an id and displayName, and an onEnd attribute which is the id of the title to play when this one ends (which, in this case, is set to loop back on itself).
PrimaryAudioVideoClip
The PrimaryAudioVideoClip element defines one of the files used to make up the title. In this case, the title consists of a single file, but it could consist of several different files. For example, if there were two versions of a movie on a disc -- the "normal" version and the "extended" version -- each would be its own Title and you would break the movie up several chunks. The two titles would share the chunks that were the same in both versions, and swap out the "normal" or "extended" scenes only where they differ. This would save on disc space, since you don't have to have two whole copies of the movie.
The clip has both titleTimeBegin and titleTimeEnd attributes, and these correspond to where on the overall title timeline the video should be played. For a simple title with only one clip, the start is 00:00:00:00 and the end is the length of the clip. The dataSource of the file is also specified (in this case, the optical disc) and also the src URI of the file -- in this case, a WMV file.
Two things to note about the src attribute:
1. Because iHDSim only supports running Windows Media files, this attribute is pointing to a WMV file. For a real disc, this would point to a different kind of file.
2. Nevertheless, iHDSim fully simulates the filesystem structure of the HD DVD player, and so the URI is specified as it will appear on the final disc (ie, you don't put in "C:\Documents and Settings\ptorr\My Documents\video.wmv" or anything like that).
Video and Audio
The Video and Audio elements describe which of the various tracks inside the video file should be used. Within a given file, you can multiplex several different tracks (for example, English, French, Dolby, and DTS audio) and then later you can switch between them. I don't pretend to know much about this aspect of the playlist though :-).
ChapterList
The ChapterList element is just a container for chapter markers.
Chapter
The Chapter elements use the titleTimeBegin attribute to specify at what point in the title the chapter starts. You can then jump to the chapter using the navigation buttons on your remote, or by using the chapter buttons on the menu (which end up calling APIs inside the player).
PlaylistApplication
The PlaylistApplication element describes an application that will run for the entire duration of the playlist. Contrast this to a normal application (also called a "title application") that only runs within a given title. The playlist application allows you to build your main navigation menu (eg, the menubar on any of the Warner Bros. titles) that is available at all times. It has a description, a language, and a src that points to a manifest file (see below). Note again that we use "real" HD DVD paths, not Windows filesystem paths.
PlaylistApplicationResource
The PlaylistApplicationResource elements list all the resources needed for the application -- markup files, script files, images, sounds, and so on. Because of the way optical discs work, you can't really do random disc access while the movie is playing. Instead, you need to load all your resources up-front (or multiplex them into the main video stream) so that the laser isn't interrupted while it's trying to read the movie off the disc. Here we specify the src to the resource, its size (which we over-estimate during development, but you should put the real size in before burning a disc), and whether or not it is a stand-alone file or multiplexed into the video stream.
Moving Swiftly On...
Phew! That's it for the playlist... and that's only a simple one. They can get much more complicated than that for a real disc with many titles and different audio tracks, subtitles, applications, etc.
Next, we will look at the markup file. | http://blogs.msdn.com/ptorr/archive/2006/05/19/602391.aspx | crawl-002 | refinedweb | 1,296 | 59.33 |
Why Did I Write Acme::Pythonic
Acme::Pythonic is a Perl module of mine that allows the user to write Pythonic code as valid Perl code. I mean, you feed this code)
and perl executes it right away, directly. There's no intermediate file being generated or anything. Sounds like magic unless you know what's a source filter.
But some people don't get that even with the work behind this module, the test suite, etc. this module is just a fucking joke! That's why it belongs to the Acme:: namespace in the first place.
It is a joke about taking programming languages too seriously, to the hell with that, there you have Python and Perl mixed together. Sublimation. Climax. You can put that code against a wall and do vipassana contemplating it, release your attachments to this mundane world! | http://www.advogato.org/person/fxn/diary/513.html | CC-MAIN-2015-22 | refinedweb | 142 | 73.07 |
- Reference
- BSON
- Mapping Classes
- Handling Schema Changes
Handling Schema Changes
Just because MongoDB is schema-less does not mean that your code can handle a schema-less document. Most likely, if you are using a statically typed language like C# or VB.NET, then your code is not flexible and needs to be mapped to a known schema.
There are a number of different ways that a schema can change from one version of your application to the next.
- A new member is added
- A member is removed
- A member is renamed
- The type of a member is changed
- The representation of a member is changed
How you handle these is up to you. There are two different strategies:
- Write an upgrade script.
- Incrementally update your documents as they are used.
The easiest strategy is to write an upgrade script. There is effectively no difference to this method between a relational database (SQL Server, Oracle) and MongoDB. Identify the documents that need to be changed and update them.
Alternatively, and not supportable in most relational databases, is the incremental upgrade. The idea is that your documents get updated as they are used. Documents that are never used never get updated. Because of this, there are some definite pitfalls you will need to be aware of.
First, queries against a schema where half the documents are version 1 and half the documents are version 2 could go awry. For instance, if you rename an element, then your query will need to test both the old element name and the new element name to get all the results.
Second, any incremental upgrade code must stay in the code-base until all the documents have been upgraded. For instance, if there have been 3 versions of a document, [1, 2, and 3] and we remove the upgrade code from version 1 to version 2, any documents that still exist as version 1 are un-upgradeable.
A Member Has Been Added
When a new member is added to an entity, there is nothing that needs to be done other than restarting the application if you are using the auto mapping features. If not, then you will manually need to map the member in the same way all the other members are getting mapped.
Existing documents will not have this element and it will show up in your class with its default value. You can, of course, specify a default value.
A Member Has Been Removed
When a member has been renamed, it will exist in old documents with the old name and in new documents with the new name. The way to handle incremental upgrades for this rename would be to implement an ExtraElements member in conjunction with ISupportInitialize.
For example, let’s say that a class used to have a
Name property which has now been split into a
FirstName and a
LastName property.
public class MyClass : ISupportInitialize { public string FirstName { get; set; } public string LastName { get; set; } [BsonExtraElements] public IDictionary<string, object> ExtraElements { get; set; } void ISupportInitialize.BeginInit() { // nothing to do at beginning } void ISupportInitialize.EndInit() { object nameValue; if (!ExtraElements.TryGetValue("Name", out nameValue)) { return; } var name = (string)nameValue; // remove the Name element so that it doesn't get persisted back to the database ExtraElements.Remove("Name"); // assuming all names are "First Last" var nameParts = name.Split(' '); FirstName = nameParts[0]; LastName = nameParts[1]; } }
The Type of a Member Is Changed. | https://mongodb.github.io/mongo-csharp-driver/2.14/reference/bson/mapping/schema_changes/ | CC-MAIN-2022-21 | refinedweb | 568 | 61.97 |
Have you ever felt this before? It's the day after you send your product to manufacturing. You step back, look at the big picture, and start to see minor flaws. A dread sinks in when you realize you just blogged about it too! That was Monday morning. :-) The good news is that our analysis shows that the flaws are minor. They are unlikely to affect people in real practice, don't affect the code we wrote, and there are workarounds if you're trying something complicated. So... here's the whirlwind tour of IPropertyStoreCapabilities (IPSC):
We needed a way to mark which properties are writable and which aren't. We looked at a few models and decided we wanted a runtime check for writability. So we invented IPSC to let a property handler declare what properties it supports and those it doesn't. For example, the PNG property handler uses IPSC to tell explorer that it supports writing System.Photo.DateTaken, but nothing else.
Enter the multiplex property store. This is a building block object we wrote to help shell namespaces and property handlers to build their property stores. Like the name suggests, it selects from various inputs. From the start, we found this object hard to design and work with. We had to figure out reasonable ways to select which input to select. We had to decide how to handle writing. How to handle IPSC. To keep things simple, we decided to not have an interface to let the MUX know which store handles what property. Instead...
#1 means the store returned by GPS_READWRITE cannot use the MUX. This means if you use IPSC on a GPS_READWRITE store, you don't get the full picture since we're ignoring the read-only data sources.
#2 is interesting, but doesn't affect us much today.
#3 is what made me panic yesterday. Imagine if two stores implemented IPSC and were joined by a MUX. The calling application would only be able to query the first store! So here are the mitigating circumstances:
So in the end, I am going back to my original recommendation: Use IPropertyStoreCapabilities with GPS_DEFAULT. This is what explorer does, the shipping proprety stores are fine, and other hopefully other developers will find and understand my blog.
-Ben | http://blogs.msdn.com/b/benkaras/archive/2006/11/14/the-deal-with-ipropertystorecapabilities.aspx | CC-MAIN-2016-07 | refinedweb | 382 | 66.54 |
WooCommerce Aliexpress Import Plugin
Orçamento $10-30 USD: [login to view URL]
- Everything from product description.
- Original price
Requirements:
1. import individual products from Aliexpress to WooCommerce or
import products from a specific category in a store to WooCommerce or
Import ALL products from a store to WooCommerce.
2. Imported product images need to be large images, not thumbnail size.
3. Everything from "product description" needs to be scraped and uploaded to WooCommerce, including images (no img src links or any link back to source)
4. Option to only import products if certain value exist in "Item specifics". Eg. Only import If "brand name" is "nike".
5. Data that needs to be imported into product custom fields:
- Store ID
- Product ID
- product web link
6. Scraped text need to follow the style/text formatting of the wordpress theme, not Aliexpress.
7. Some products have similar images in product description, so it needs to avoid importing duplicate images into WooCommerce.
8. Scheduling options to:
- Check if imported product still exist on aliexpress or not. This means checking product urls to see if it's still alive or not. (If yes, do nothing. If no, then put it to draft)
- Check if there's new items in a store. New product ID in store = new products available (if yes, import and put to draft and notify admin of new products. If no, do nothing)
- Option to run manual checks on both the above.
9. A widget in WooCommerce "edit order" page that displays aliexpress links for products ordered (refer image). Links are extracted from product's custom field weblink.
Additional Info:
- SKU can be anything except the aliexpress product ID.
- While importing, it's best the plugin show progress status, otherwise would be hard to know whether it's still working or not.
- Scraping thousands of products can take a long time and even fail to import all products. You need to find a way to scrape efficiently and not fail in the process.
- I will not pay for an incomplete plugin that doesn't work, my requirements are specific and needs to be delivered (unless it is a truly a technical limitation).
- Able to start work immediately.
-Prefer person with skype or IM.
15 freelancers estão ofertando em média $81 para esse trabalho
can do this deal on time without any error and delay in time. It will take maximum of 12 days to complete the project | https://www.br.freelancer.com/projects/php/woocommerce-aliexpress-import-plugin-17195160/ | CC-MAIN-2018-51 | refinedweb | 406 | 65.01 |
CanCan
Wiki | RDocs | Screencast
CanCan is an authorization library for Ruby on Rails which restricts what resources a given user is allowed to access. All permissions are defined in a single location (the Ability class) and not duplicated across controllers, views, and database queries.
Installation
In Rails 3, add this to your Gemfile and run the bundle command.
gem "cancan"
In Rails 2, add this to your environment.rb file.
config.gem "cancan"
Alternatively, you can install it as a plugin.
rails plugin install git://github.com/ryanb/cancan.git
Getting Started
CanCan expects a current_user method to exist in the controller. First, set up some authentication (such as Authlogic or Devise). See Changing Defaults if you need different behavior.
1. Define Abilities
User permissions are defined in an Ability class. CanCan 1.5 includes a Rails 3 generator for creating this class.
rails g cancan:ability
In Rails 2.3, just add a new class in `app/models/ability.rb` with the following contents:
class Ability include CanCan::Ability def initialize(user) end end
See Defining Abilities for details.
2. Check Abilities & Authorization
The current user's permissions can then be checked using the can? and cannot? methods in the view and controller.
<% if can? :update, @article %> <%= link_to "Edit", edit_article_path(@article) %> <% end %>
See Checking Abilities for more information
The authorize! method in the controller will raise an exception if the user is not able to perform the given action.
def show @article = Article.find(params[:id]) :read, @article end
Setting this for every action can be tedious, therefore the load_and_authorize_resource method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for every action.
class ArticlesController < ApplicationController def show # @article is already loaded and authorized end end
See Authorizing Controller Actions for more information.
3. Handle Unauthorized Access
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the ApplicationController.
class ApplicationController < ActionController::Base rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert => exception. end end
See Exception Handling for more information.
4. Lock It Down
If you want to ensure authorization happens on every action in your application, add check_authorization to your ApplicationController.
class ApplicationController < ActionController::Base end
This will raise an exception if authorization is not performed in an action. If you want to skip this add skip_authorization_check to a controller subclass. See Ensure Authorization for more information.
Wiki Docs
Questions or Problems?
If you have any issues with CanCan which you cannot find the solution to in the documentation, please add an issue on GitHub or fork the project and send a pull request.
To get the specs running you should call bundle and then rake. See the spec/README for more information.
Special Thanks
CanCan was inspired by declarative_authorization and aegis. Also many thanks to the CanCan contributors. See the CHANGELOG for the full list. | http://www.rubydoc.info/github/ryanb/cancan | CC-MAIN-2015-40 | refinedweb | 500 | 50.02 |
Sampling in Application Insights in the portal, they are renormalized to take into account sampling. Doing so minimizes any effect on the statistics.
Sampling reduces traffic and data costs, and helps you avoid throttling.
In brief:
- Sampling retains 1 in n records and discards the rest. For example, it might retain one in five events, a sampling rate of 20%.
- Adaptive Sampling is enabled by default in all the latest version of ASP.NET and ASP.NET Core Software Development Kits (SDKs).
- You can also set sampling manually. This can be configured in the portal on the Usage and estimated costs page, in the ASP.NET SDK in the ApplicationInsights.config file, in the ASP.NET Core SDK via code or in the Java SDK in the ApplicationInsights.xml file.
- If you log custom events and need to ensure that a set of events is retained or discarded together, the events must have the same OperationId value.
- The sampling divisor n is reported in each record in the property
itemCount, which in Search appears under the friendly name "request count" or "event count".
itemCount==1when sampling is not in operation.
- If you write Analytics queries, you should take account of sampling. In particular, instead of simply counting records, you should use
summarize sum(itemCount).
Types of sampling
There are three alternative sampling methods:
Adaptive sampling automatically adjusts the volume of telemetry sent from the SDK in your ASP.NET/ASP.NET Core app. This is the default sampling from ASP.NET Web SDK v 2.0.0-beta3 onwards and Microsoft.ApplicationInsights.AspNetCore SDK v 2.2.0-beta1 onwards. Adaptive sampling is currently only available for ASP.NET server-side telemetry. Works in the Azure portal..
If Adaptive or Fixed rate sampling are in operation, Ingestion sampling is disabled.
Adaptive sampling in your ASP.NET/ASP.NET Core Web Applications
Adaptive sampling is available for the Application Insights SDK for ASP.NET v 2.0.0-beta3 and later, Microsoft.ApplicationInsights.AspNetCore SDK v 2.2.0-beta1 and later, and is enabled by default.
Adaptive sampling affects the volume of telemetry sent from your web server app to the Application Insights service endpoint., sampling rate is adjusted so as to achieve the target volume. approximately correct values in Metric Explorer.
Configuring adaptive sampling for ASP.NET Applications
In ApplicationInsights.config, you can adjust several parameters in the
AdaptiveSamplingTelemetryProcessor node. The figures shown are the default values:
<MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
The target rate that the adaptive algorithm aims for, how soon after are we allowed to lower sampling percentage again to capture less data.
<SamplingPercentageIncreaseTimeout>00:15:00</SamplingPercentageIncreaseTimeout>
When sampling percentage value changes, how soon after are we allowed to increase, the weight assigned to the most recent value. Use a value equal to or less than 1. Smaller values make the algorithm less reactive to sudden changes.
<InitialSamplingPercentage>100</InitialSamplingPercentage>
The value assigned when the app has just started. Don't reduce value while you're debugging.
<ExcludedTypes>Trace;Exception</ExcludedTypes>
A semi-colon delimited list of types that you do not want to be sampled. Recognized types are: Dependency, Event, Exception, PageView, Request, Trace. All instances of the specified types are transmitted; the types that are not specified are sampled.
<IncludedTypes>Request;Dependency</IncludedTypes>
A semi-colon delimited list of types that you want to be sampled. Recognized types are: Dependency, Event, Exception, PageView, Request, Trace. The specified types are sampled; all instances file.
- Use the following snippet to configure Adaptive Sampling.
C#
using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.WindowsServer.Channel.Implementation;.
C#
// The following configures adaptive sampling with 5 items per second, and also excludes DependencyTelemetry from being subject to sampling. builder.UseAdaptiveSampling(maxTelemetryItemsPerSecond:5, excludedTypes: "Dependency");
Configuring adaptive sampling for ASP.NET Core Applications.
There is no
ApplicationInsights.Config for ASP.NET Core Applications, so every sampling feature. Follow the steps below to add sampling with more customization options.
Configure Sampling settings
Use extension methods of
TelemetryProcessorChainBuilder as shown below to customize sampling behavior.
Important
If you use this method to configure sampling, please make sure to use aiOptions.EnableAdaptiveSampling = false; settings with AddApplicationInsightsTelemetry().
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration) { var builder = configuration.TelemetryProcessorChainBuilder; // version 2.5.0-beta2 and above should use the following line instead of above. () // var builder = configuration.DefaultTelemetrySink"); builder.Build(); // If you have other telemetry processors: builder.Use((next) => new AnotherProcessor(next)); // ... }
If using the above method to configure sampling, make sure to use
aiOptions.EnableAdaptiveSampling = false; settings with AddApplicationInsightsTelemetry().
Fixed-rate sampling for ASP.NET, ASP.NET Core, and Java websites
Fixed rate sampling reduces the traffic sent from your web server and web browsers. Unlike adaptive sampling, it reduces telemetry at a fixed rate decided by you. It also synchronizes the client and server sampling so that related items are retained - for example, when you look at a page view in Search, you can find its related request.
Like other sampling techniques, this also retains related items. For each HTTP request event, the request and its related events are either discarded or transmitted together.
In Metrics Explorer, rates such as request and exception counts are multiplied by a factor to compensate for the sampling rate, so that they are approximately correct.
Configuring fixed-rate sampling in ASP.NET>
Alternative: enable fixed-rate sampling in your server code
Instead of setting the sampling parameter in the .config file, you can programmatically set these values.
C#
using Microsoft.ApplicationInsights.Extensibility;; builder.UseSampling(10.0); // percentage // If you have other telemetry processors: builder.Use((next) => new AnotherProcessor(next)); builder.Build();
Configuring fixed-rate sampling in ASP.NET Core
Disable adaptive sampling: Changes can be made in the method
ConfigureServices, method
Configureas shown in below snippet:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var configuration = app.ApplicationServices.GetService<TelemetryConfiguration>(); var builder = configuration.TelemetryProcessorChainBuilder; // version 2.5.0-beta2 and above should use the following line instead of above. () // var builder = configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder; // Using fixed rate sampling double fixedSamplingPercentage = 10; builder.UseSampling(fixedSamplingPercentage); builder.Build(); // ... }
Configuring fixed-rate sampling in JAVA
Download and configure your web application with latest application insights java SDK
Enable the fixed-rate sampling module by adding the following snippet to ApplicationInsights.xml file.
<TelemetryProcessors> <BuiltInProcessors> <Processor type = "FixedRateSamplingTelemetryProcessor"> <!-- Set a percentage close to 100/N where N is an integer. --> <!-- E.g. 50 (=100/2), 33.33 (=100/3), 25 (=100/4), 20, 1 (=100/100), 0.1 (=100/1000) --> <Add name = "SamplingPercentage" value = "50" /> </Processor> </BuiltInProcessors> </TelemetryProcessors>
You can Include or Exclude specific types of telemetry from Sampling using the following tags inside the Processor tag "FixedRateSamplingTelemetryProcessor"
<ExcludedTypes> <ExcludedType>Request</ExcludedType> </ExcludedTypes> <IncludedTypes> <IncludedType>Exception</IncludedType> </IncludedTypes>
The telemetry types that can be included or excluded from sampling are: Dependency, Event, Exception, PageView, Request, and Trace.
Note
For the sampling percentage, choose a percentage that is close to 100/N where N is an integer. Currently sampling doesn't support other values.
Ingestion sampling
This form of are not available in any Application Insights feature such as Continuous Export.
Ingestion sampling doesn't operate while SDK-based adaptive or fixed-rate sampling is in operation. Adaptive sampling is enabled by default when ASP.NET/ASP.NET Core SDK is enabled in Visual Studio or enabled in Azure Web App extensions or by using Status Monitor, and ingestion sampling is disabled. If the sampling rate at the SDK is less than 100% (i.e items are being sampled) then the ingestion sampling rate that you set is ignored.
Warning
The value shown on the tile indicates the value that you set for ingestion sampling. It doesn't represent the actual sampling rate if SDK sampling is in operation.
Sampling for web pages with JavaScript
You can configure web pages for fixed-rate sampling from any server.
When you configure the web pages for Application Insights, modify the JavaScript snippet that you get from the Application Insights portal. (In ASP.NET apps,>
For the sampling percentage, choose a percentage that is close to 100/N where N is an integer. Currently sampling doesn't support other values.
If you also enable fixed-rate sampling at the server, the clients and server will synchronize so that, in Search, you can navigate between related page views and requests.
When to use sampling?
Adaptive sampling is automatically enabled in latest .NET and .NET Core SDKs. Regardless of which version of the SDK you use, you can enable ingestion sampling to allow Application Insights to sample the collected data.
By default no sampling is enabled in Java SDK. Currently, it only supports Fixed Rate Sampling. Adaptive Sampling is not supported in Java SDK. short time interval.
- To keep within the quota of data points for your pricing tier.
- To reduce network traffic from the collection of telemetry.
Which type of sampling should I use?
Use ingestion sampling if:
- You often go through your monthly quota of telemetry.
- You're using a version of the SDK that doesn't support sampling - for example ASP.NET versions earlier than 2.
- You're getting too much telemetry from your users' web browsers.
Use fixed-rate sampling if:
- You're using the Application Insights SDK for ASP.NET web services version 2.0.0 or later or Java SDK v2.0.1 or later, and
- server SDK. It will not reduce traffic until a certain minimum rate is reached, therefore, low-use sites will not be affected.
How do I know RetainedPercentage for any type is less than 100, then that item is being sampled.
Application Insights does not sample session, metrics and performance counters telemetry types in any sampling techniques described above. These types are always excluded from sampling as reduction in precision can be highly undesirable for these telemetry types
How does sampling work?
Fixed-rate sampling feature of the SDK in ASP.NET versions from 2.0.0 and Java SDK version 2.0.1 and onwards. Adaptive sampling is a feature of SDK in ASP.NET versions from 2.0.0 onwards. Ingestion sampling is a feature of the Application Insights service, and can be in operation if the SDK is not performing sampling.
The sampling algorithm decides which telemetry items to drop, and which ones to keep (whether it's in the SDK or in the Application Insights service). The sampling decision is based on several rules that aim to preserve all interrelated data points intact, maintaining a diagnostic experience in Application Insights that is actionable and reliable even with a reduced data set. For example, if for a failed request your app sends additional telemetry items (such as exception and traces logged from this request), sampling will not split this request and other telemetry. It operation ID set (for example telemetry items reported from asynchronous threads with no http context) sampling simply captures a percentage of telemetry items of each type. Prior to 2.5.0-beta2 of .NET SDK, and 2.
Warning
Application Insights does not sample metrics and sessions telemetry types. Reduction in the precision can be highly undesirable for these telemetry types.
Adaptive sampling
Adaptive sampling adds a component that monitors the current rate of transmission from the SDK, and adjusts the sampling percentage to try to stay within the target maximum rate. The adjustment is recalculated at regular intervals, and is based on a moving average of the outgoing transmission rate.
Sampling and the JavaScript SDK
The client-side (JavaScript) SDK participates in fixed-rate sampling in conjunction with the server-side SDK. The instrumented pages will only send client-side telemetry from the same users for which the server-side made its decision to "sample in." This logic is designed to maintain integrity of user session across client- and server-sides. As a result, from any particular telemetry item in Application Insights you can find all other telemetry items for this user or session.
My client and server-side telemetry don't show coordinated samples as you describe above.
- Verify that you enabled fixed-rate sampling both on server and client.
- Make sure that the SDK version is 2.0 or above.
- Check that you set the same sampling percentage in both the client and server.
Frequently Asked Questions
What is the default sampling behavior in ASP.NET and ASP.NET Core SDK?
If you are using one of the latest versions of the above SDK, Adaptive Sampling is enabled by default with five telemetry items per second. There are 2 AdaptiveSamplingTelemetryProcessors added by default, and one includes Event type in sampling, and the other excludes Event type from sampling. This configuration means that the SDK will try to limit telemetry items to five telemetry items of Event types, and five telemetry items of all other types combined, thereby ensuring that Events are sampled separately from other Telemetry types. Events are typically used for business telemetry, and most likely should not be affected by diagnostic telemetry volumes.
The following shows the default ApplicationInsights.Config file generated. As described, there are two separate AdaptiveSamplingTelemetryProcessor nodes added, one excluding Event types, and another including it. In ASP.NET Core, exact same default behavior is enabled in code. Use the examples in the earlier section of the document ability to correlate diagnostic data per user, session, and request, which is critical for diagnostics. Therefore, sampling works better with "collect all telemetry items for X percent of app users", or "collect all telemetry for X percent of app requests" logic. sampling percentage too low?
- Excessively low sampling percentage (over-aggressive sampling) reduces the accuracy of the approximations, when Application Insights attempts to compensate the visualization of the data for the data volume reduction. Also, diagnostic experience might be negatively impacted, as some of the infrequently failing or slow requests may be sampled out.
What happens if I configure sampling percentage too high?
- Configuring too high previous version of Java SDK(1.0.10 or before).
- If you're using ASP.NET SDK versions 2.0.0 and above or ASP.NET CORE SDK version 2.2.0 and above (hosted either in Azure or on your own server), you get adaptive sampling by default, but you can switch to fixed-rate as described above. With fixed-rate sampling, the browser SDK automatically synchronizes to sample related events.
- If you're using Java SDK version 2.0.1 or above, you can configure ApplicationInsights.xml to turn on Fixed Rate Sampling. Sampling is turned off by default. With fixed-rate sampling, the browser SDK automatically synchronizes to sample related events.
There are certain rare events I always want to see. How can I get them past the sampling module?
- The best way to achieve this is to write a custom TelemetryProcessor, which sets the
SamplingPercentageto 100 on the telemetry item you want retained, as shown below. This ensures that all sampling techniques will ignore this item from any sampling considerations.
if(somecondition) { ((ISupportSampling)item).SamplingPercentage = 100; }
Next steps
- Filtering can provide more strict control of what your SDK sends.
- Read the Developer Network article Optimize Telemetry with Application Insights.
Feedback | https://docs.microsoft.com/en-gb/azure/azure-monitor/app/sampling | CC-MAIN-2019-30 | refinedweb | 2,518 | 51.24 |
Markdown as a String InterpolatorMarkdown as a String Interpolator
Proof of concept of a markdown string interpolator. E.g. you can write
import mads.Mads.text._ val mads = "Mads" md""" # An example This is an example of $mads """
and produce a value in a number of output formats (
String, scalajs-react,
etc.) By "a number of output formats" I mean text, which is currently the only
supported format---but other formats could easily be added.
It's like MDX but not tied to Javascript and React.
To use, add the following dependency to your
build.sbt:
libraryDependencies += "org.creativescala" %% "mads" % "0.2.0"
Supported MarkdownSupported Markdown
Mads does not currently support much of markdown. The following is implemented:
- Headings in the sane ATX format (
# Heading)
- Paragraphs
- Code blocks with backticks for fences. A language must be specified after the opening fence.
More will be added as the need arises. It's unlikely it will ever support Setext headings.
How it WorksHow it Works
It uses a so-cool-it's-frozen parser combinator library that allows suspending and resuming parsing.
PublishingPublishing
To publish a release:
- update the version number on master in publish.sbt
- update the version number in README.md
- run + publishSigned
- run sonatypeBundleRelease
- tag master with the release version
- push tags to origin. | https://index-dev.scala-lang.org/noelwelsh/mads | CC-MAIN-2022-40 | refinedweb | 216 | 51.24 |
Django utilities for honoring the Do Not Track HTTP header.
Project Description
Dj.
Refer to the documentation for complete information.
Quick-Start
Installation of the middleware is required. The context processor is convenient and thus recommended.
Settings:
MIDDLEWARE_CLASSES = ( # default/other processors ... 'donottrack.middleware.DoNotTrackMiddleware', # default/other processors ... ) TEMPLATE_CONTEXT_PROCESSORS = ( # default/other processors ... 'donottrack.context_processors.donottrack', )
Then in your template you can do things like:
{% if not donottrack %} {% include "google-analyitcs.html" %} {% endif %}
And your views can also handle DNT:
def my_view(request): if not request.donottrack: # Log some request data ... # continue with view logic
Tip
Adding this app to your INSTALLED_APPS is currently unnecessary unless you want to run tests.
Other Information
Important
Installing this app in your Django project does not mean that you honor Do Not Track any more than installing django-secure means your web applicaiton is secure. It only means you have some tools to help with that end goal. You will need to audit your full stack to ensure that you are honoring DNT. But this app is a great start, and we hope you find it useful.
Note
This is an initial release. Despite being simple and theoretically solid (it has a full test suite) this is a beta-type release, and the public API may change, and as I learn more about DNT, more functionality may be added.
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-donottrack/ | CC-MAIN-2018-17 | refinedweb | 249 | 59.6 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to get value from one field to another in Odoo?
I want to pass the value of this field:
Image:
for this field:
Image:
Hi Robson
You make the second field to compute (wiil be readonly automatically , you may know)
def _foo(self):
# On2many field will have a related Many2one field to parent object, example parent_id
bar = # Calculate the parent_id
for i in self.env['model of first field'].search([('parent_id', '=', bar )]):
# You can get all lines of One2many field of that parent object
# Find the value
self.second_field = value to be passed
second_field = fields.Float(compute='_foo')
All the best
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-get-value-from-one-field-to-another-in-odoo-110422 | CC-MAIN-2017-22 | refinedweb | 157 | 55.44 |
From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2004-01-06 11:03:09
Gennadiy Rozental <gennadiy.rozental_at_[hidden]> wrote in message
news:bt8cmd$ujn$1_at_sea.gmane.org...
> Hi,
>
> I know that numeric conversion library review is over and it's got accepted.
> But since I was on vocation at the time let me give these comments now to
> the version that was submitted. I did not have time to look through review
>
Thanks for your detailed review!
> Design
> ------------------------------------------------------------------
>
> In most part proposed design looks reasonable. I have only one major IMO
> concern.
>
> Issue: (Major) Why traits are template parameter of converter?
> I've expressed my opinion in the matter before: Traits - as name suggest
> could not be policy. IOW should not be template parameters. Traits are type
> specific and an ability to supply them independently to the primary type in
> most cases leads to invalid/too complicated design.
> Traits are not only template parameters of public converter class but
> many other classes. IMO all of them should use S and T as template
> parameters instead.
>
I have to disagree.
Traits are used as policies in too many designs, including the STL itself, and I don't see a
problem with that.
I agree that traits classes are type specific, but they are used as policies precisely because
of that: if the user of a parametrized facility wants a different treatment for a given type,
she can't change *the* traits for the type, all she can do is pass in a different traits as a
policy.
If this were not a policy, users would be stuck with the definiton of the default traits
class.
I agree that this opens a window to all sort of problems in case a user plugs in an invalid
traits, but I think that should not constitute a reason for fixing the traits into the
converter.
As always, "trust the programmer"
> 1. Why bounds<>::smallest() returns 0 and not 1, for integral types? Doesn't
> it supposed to return smallest positive value?
>
You're right... nobody missed this one :-)
> 2. boost::numeric::converter is part of public interface and have 7 (should
> be 6) template parameters. Such number of parameters asks for named template
> parameters facility.
>
Right indeed...
I just couldn't get bcc5.5/5.6 to work with the new ntp so I leaved it off until we get an ntp
facility working with most compilers.
> 3. All converter policies required to be stateless. Why?
> I don't understand this requirement. Moreover, I believe in some (rare)
> cases I may want statefull one. For example Let say I want to keep track of
> location where risky arithmetic operations performed. So OverflowHandler
> needs hold on to this position and report it in exception.
>
I see.
The motivation was to avoid having instances of the policies as part of the converter state.
That is, to make it leaner.
But I see your point and after all most compilers will effectively optimize away those policies
which are actually empty classes, so I think I'll remove the requirement.
> 4. converter<>::convert converts only rvalue. Why?
> IMO we need second operation that works with lvalues. What if I want to
> convert int& into char&?
>
This requires the target lvalue as a parameter instead of a return value.
It could be done yes, but I don't see the reason.
Why would want to do that?
> 5. IMO Thee should be simple direct way to make range checking debug only
> operation
>
Good point.
Though out of range errors are usually not bugs, meaning that the checks really shouldn't be
debug only, there should be a at least a simple way to remove range checking all toghether for a
release build for those rare applications working with constrained data.
>
> Implementation
> ------------------------------------------------------------------
>
> 1. I am not sure that it is really the issue. But if it is it would be major
> concern. Whole implementation is based on the following logic
>
> template<...>
> some_type_generator
> {
> typedef some-complex-type-generator case1;
> typedef some-complex-type-generator case2;
> ....
>
> typedef ct_switch( type_selector ) case1 or case2 .... type;
>
> // for example
> // typedef typename
> //
> mpl::apply_if<use_internal_RC,InternalRangeCheckerQ,UserRangeCheckerQ>::type
> // RangeChecker ;
> };
>
> I wonder whether all caseN types get instantiated. If yes, it may be quite
> wasteful.
>
I may need to revise this on a case by case basis, but I used metafunction "quoting"
to instantiate only those which are actually used.
What you may be seeing is the situation when the "cases" are types extracted from
template parameters, as in:
typedef typename X::type case0 ;
typedef typename Y::type case1 ;
In this situation, case0, case1, etc are already instantiated inside X and Y (here are just
"promoted" into the scope of the template class)
> 2. Could you please explain logic behind subranged_Unsig2Sig,
> subranged_Udt2BuiltIn, subranged_BuiltIn2Udt implementations
Sure,
subranged_Unsig2Sig:
--------------------
First, let's see the relevant sections of the standard:
(a) 3.9.1/3 Fundamental Types, Unsigned Integer Types
"....each signed integer type has the same object representation as its corresponding unsigned
integer type..."
(b) 3.9.1/3 Fundamental Types, Unsigned Integer Types
"...The range of nonnegative values of a signed integer type
is a subrange of the corresponding unsigned integer type, and the value representation of each
corresponding signed/unsigned type shall be the same..."
(c) 3.9.1/7 Fundamental Types, Integral Types
"The representation of integral types shall define values by use of a pure binary representation
system"
(d) 18.2.1.2/7 numeric_limit::digits
"For built-in integer types, the number of non-sign bits in the representation"
AFAICT, there are _only_ 3 binary representation schemes for signed integers: two's complement,
one's complement and sign-magnitude. (the standard even gives these 3 schemes as examples of
valid representations).
All these 3 reps have in a common that 1, and only 1 bit is needed for the sign.
It follows from this that if N is the number of non-sign bits used to represent a signed
integer, N+1 bits are used to represent the corresponding unsigned integer.
(b) says that "...the range of nonnegative values of a signed integer type
is a subrange of the corresponding unsigned integer type...", but,
it follows from (a) and (c) that this subrange is not _any_ subrange but
exactly half the range of the unsigned type minus 1.
Furthermore, half range is covered by exactly half bits, thus, the range of a signed type
completely contains the range of an unsigned type iff: s+1 >= u, were s and u are the non-sign
bits used by the signed and unsigned types respectively.
NOTE: The following contains a good survey of representation schemes:
subranged_Udt2BuiltIn
subranged_BuiltIn2Udt
---------------------
User Defined Numeric Types can be almost anything, so, in order to compare the ranges of a UDT
and a built-in I had two choices: come up with some general way to compare ranges of arbitrary
numeric types "at compile time" (using only constant expression), or fix the relation
arbitrarily.
I choseen option 2 and assumed that any UDT ha wider range than any built-in type.
Anyway, this assumption has been noted already during the review and I agreed to give the matter
a deeper thought to see if UDTs can be better supported.
> 3. ct_switch4 implementation: could we make this implementation more
> efficient? If is_case0 is true why would we need the rest checks?
Good point. Yes, I think it can be improved
> 4. How would trivial_converter_impl will work if one convert from const int
> to int? Should it work?
Yes, it should.
Top-level cv-qualifiers are removed from template parameters, so a conversion
from "const int" to "int" is actually _seen_ by the converter as a trivial conversion
from just "int" to "int"
> 5. Separation of policies in make_converter_from type generator looks
> unclear tome. In an case: why would I want to use it, instead of using
> converter directly? NTP looks better solution to me.
hmmm, I agree that it looks odd....
I also agree that NTP is a better solution... but as I said above, NTP technology is not well
supported by some compilers.
>
> Docs
> ------------------------------------------------------------------
>
> Definitions:
>
> 1. Why "object representation" is sequence of bytes, while "value
> representation" is set of bits?
Because the standard said so that way (3.9.4).
...well, almost :-)
The standard uses "unsigned char" instead of "byte", which is not necesarily the same,
so I have to correct this.
> 2. "Typed value" definition: how it could by determined only by set of bits
> (value representation)? What about signed unsigned values? They have the
> same value representation as a set of bits.
The "value representation" of an object contains _all_ the bits that form the value of that
object.
In the case of signed/unsigned types, the sign bit is part of the value representation; it is
the "sign scheme" which makes sense of the value rep to extract the value with its proper sign.
> 3. "intrinsic value" definition: why are you using unsigned characters
> instead of bytes here?
Because the object rep is given in terms of unsigned chars instead of bytes (though the docs
incorrectly state the opposite)
> 4. After "abstraction" definition: "Abstraction is just an abstract
> operation" - it's like saying salt is salty
Yes it is... and it is an important qualification worth mentioning it IMO.
> 5. In C++ arithmetic types section: operation {} needs to be defined
Does it? It the classic set-by-extension nomenclature.
> 6. In C++ arithmetic types section: " The integer types are required ....
> " - what does this statement mean
The complete statement is
"The integer types are required to have a binary value representation"
It means that integer types must be binary.
> 7. In C++ arithmetic types section: you give some advice at the end - does
> it belong here?
> Actually I completely disagree with second part of what you recommend.
> IMO one should use unsigned values to model non-negative values. For once
> it's better reflect design. And also it's more safe and efficient. Would I
> use signed value as an container index, then before accessing value by index
> I need to not only check that it does not exceed size of the container but
> also check that it is non negative - twice as much work and easy to forget.
> Also in most cases errors with "negative" index are easier to catch.
> Instead of more or less safe (begin-1) memory access, one would get (begin +
> max_int)
>
Well, we won't get into this endless argument, so I'll remove the advice which anyway doesn't
belong there.
> 8. In numeric types section: definitions for integer and floating types are
> unclear to me. Does everybody know what whole and real means?
"whole" means unfragmented, it is used in math to refer to integer numbers
"real" is the standard math name for the set of numbers that floatint-point formats represent.
> 9. In Range and Precision: "The set of representable values of type 'T'. is
> ...." - representable where?
In T
> 10. Why precision is defined the way it is defined? What value this
> definition brings? There seems to be two different concepts combined undef
> the same hood.
Because the term has different meanings when applied to integer or floating-point types.
I've split the definiton in those two meanings.
> 11. Exact, ... section: " Notice that a representation is an operation ...
> ". Actually "Rounding" is an operation, which has direction and error. This
> name seems more logical. So we are getting representation my means of
> applying rounding operation to an abstract value.
It is true that technically computers do not "represent" numbers.
But it is also true that "to represent" is in itself an operation, or action if you prefer:
namely, to "give a concrete form to something". It is just not a "computer" operation.
You may argue that I shouldn't describe it as an opertation if it is not actually produceable by
a computer... however,
These definitions uses the artifact of "trampolining" out form the computers world over the
abstract math world. Things such as "abstract values", and the "abstaction" operations do not
really exist neither in a computer, yet they are used througout the document.
"to represent" is an (hypotetical) operation in the context of the document because it refers to
the (hypotetical) action of giving numbers (abstract entities) a concrete form within a
computer.
"to abstract", for instance, is the opposite operation.
"rounding" is also an operation; in fact, one produceable by a computer; but is conveys a
different meaning so I can't use it in place of "representation".
> 12. In "Standard (numeric) Conversions": "Promotions, both Integral and ...
> is not changed with the conversion" - should be promotion?
I used the word "conversion" there precisely to indicate that a promotion
is a kind of conversion which doesn't change the value.
> 13. In "Standard (numeric) Conversions": what does "in a sequel" mean?
The corrrect expression is "in the sequel" (note the "the"); it means: in what follows.
> 14. In "Standard (numeric) Conversions": "Floating to Floating conversions
> are defined only if 'N' is representable" - where?
in the target type.
> 15. In "Subranged Conversion ... ": why are you using word intersection in
> one place and symbol & in another?
Good point.. I'll change this either way.
> 16. In "Subranged Conversion ... ": "Notice that for S->T, the adjective
> subranged applies to 'T'" - why not to conversion?
Good point... it applies to 'T' w.r.t 'S', that is, to the conversion.
> 17. Discussion list address is wrong
>
Oh, I'll fix it.
>
> Type requirements and ....
>
> 18. ... in order to use the default Trunc<> policy - Instead of putting it
> into brackets
>
Oh.. I don't understand this comment.
> Header boost/numeric/conversion_traits.hpp
>
> 19. In template class is_subranged description you use source (first letter
> lowercase) and Target (first letter uppercase).
>
OK
> Header boost/numeric/converter.hpp
>
> 20. range_check_result used but not defined
OK
> 21 "If the user supplied a UserRangeChecker policy, is this policy which
> ...". "is this" looks incorrect
Not to me, but, maybe... I'm not a native English speaker. Anyone?
> 22. "This function is externally supplied by the RawConverter policy
> class.". "externally supplied" term is unclear.
Is "supplied externally" better? Again, I can't tell which form is more correct.
> 23. "Internal Member Functions: ...., but they can be called separately for
> specific needs.". If they could be called by end-user why do you name them
> internal?
>
Because they are alrady called by the "usual" public interface.
> Header boost/numeric/converter_policies.hpp
>
> 24. "This stateless non-template policy class": what do you mean by
> non-template?
That this policy is not parametrized. It is not a template class but a regular class.
> And later you mention template policy class. What do you mean
> by that?
>
That this policy _is_ parametrized. It is a template class, not a regular class.
> Code
> ------------------------------------------------------------------
>
> 1. Copyright needs to be updated.
OK
> 2. Why do you name namespace convdetail/boundsdetail and not detail?
To avoid conflict with other stuff in boost::detail...
Sometimes different boost libraries declare clashing names in boost::detail.
This situation is not covered by the regression test; it shows up when both libraries are used
toghether.
> 3. IMO for_both maybe named if_both
To me, if_both would look like a function returning true if both expr are true, false otherwise;
but this is not what for_both does.
> 4. Why ct_switch4 and not ct_switch3. After all you have only 3 case clauses
Because it is conceptually dispatching 4 possibities. The fourth clause is ommited
because it drops by default.
> 5. for_round_style and similar selectors I would name select_round_style
> e.t.c.
It was like that originally, but then I thought about sorthening the names a little.
> 6. Why do you need get_ in get_is_subranged?
Because there are classed named "subranged" which are the predicates themselves,
while "get_subranged" is the metafunction selecting one of those classes.
There is one "get_is_subranged" though, which is the top-level selector.
I could have use "is_" al over the other subselectors and predicates, but I
removed the "get" to make the names a little shorter.
> 7. GetRC_Sig2Sig_or_Unsig2Unsig I would name GetRC_SameSig
But "Sig" alone doesn't tell whether Sig2Unsig and viceversa is also included.
These names require a delicate balance between terseness and clarity.
> 8. Name you are using for some identifiers looks like mix of 2 styles (
> GetRC_Sig2Unsig ). I think we may better following boost naming
> recommendations (like get_rc_sig_2_unsig)
Most underscores used by this naming scheme are unnecesary.
I prefer to use them not to separate words (Capitals are used for that) but to separte concepts.
For example, GetRC_xyz were xyz are specific range checkers.
> 9. Why do you need first three typedefs in rounding converter
> implementation?
Becasue they are all used in the code
> 10. Why do you need separate files for most of implementation details?
> Majority of implementation presented as one tiny header in numeric
> directory that present public interface implemented by inheritance from
> implementation located in separate header in details directory. I do not see
> real advantage in such separation.
Because those details are used by interface headers which can be used separatedly.
> 11. Why each enums are defined in separate header? Did you intend them to be
> used separately from rest of implementation?
Yes.
The "mixture" traits classes, and is_subranged trait class is intended to be used separately.
>
> Tests
> ------------------------------------------------------------------
>
> 1. Why test_helpers are .cpp and not .hpp?
> 2. All your test ask to be written in terms of test cases. Do you need help
> to convert them to use unit_test_framework?
> 3. Many of your tests ask to be converted to use new test case template
> facility. I attached I test that I reworked in this direction. Do you need
> help with that?
>
OK, Great! I'll see to use you version.
>
> Congratulation to the author for the solid work.
>
Thanks!
>Hope my comments were productive and may help to make it even better.
>
They sure did!
Best,
Fernando Cacciola
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2004/01/58689.php | CC-MAIN-2021-31 | refinedweb | 3,001 | 57.67 |
Ok, my site is setup like pretty much every other blog out there. A
list of the most recent 5 posts, then by clicking one, you go to an
individual post page, displaying the full context of that post.
Now, what I would like to do is to display the related entries in the
side column, which is part of the layout, based on the tags belonging to
that specific entry.
Here’s my coding so far:
#view
<% for post in @posts %>
<%= post.title %>
tags: <%= post.tags.collect { |tag| link_to tag.name, :controller =>
“articles”, :action => “by_category”, :category => tag.name.to_s
}.join(", ") %>
<%= post.entry %>
<% end %>
#layout
<% for related in @contents_related %>
#controller (how do I pass the tag_id and the content_id?)
@contents_related = Content.show_related_entries(?,?)
#model
def self.show_related_entries(t_id, c_id)
find_by_sql(“select c.title from contents c inner join contents_tags
ct on c.id = ct.content_id where ct.tag_id = #{t_id} and c.id !=
#{c_id}”)
end
The function works if I manually pass a content_id (for my entry) and a
tag id (for a tag of that entry). Now, how can I dynamically pull out
the single content_id for the post, but execute the function for each
tag related to that individual post???
Hopefully you can see what I’m trying to accomplish, and can have a
suggestion (even if it’s completely different) as to how I can get this
working!
Thanks for any help! | https://www.ruby-forum.com/t/displaying-related-entries-by-tags-help/80193 | CC-MAIN-2020-50 | refinedweb | 233 | 67.15 |
Introduction: Handmade Anubis Art Speaker
Anubis Artspeaker is an art project I did during my 1st year graduate study in San Francisco Art Institute.
The concept is to create a product like sculpture that can be functional and aesthetic innovated. I was drawn by boombox and hip hop culture since I was a teenager, so i decide to make a unique speaker sculpture. At the flick of a switch My sculptures can summon up musical and audio experiences. Technological and aesthetic innovation have profoundly altered our sense of how music can be performed, distributed, heard, and visualized. the inspirational exchange between music and design flows in both directions. My speaker sculpture has empowered me to create and explore unprecedented range of music and sound. simultaneously, sound has been a model for many of my conceptual sculpture development.
The Speaker is made of composite polymer materials that content paper, resin, fiber glass, etc. I use most of the materials from the sculpture store Doulgas&Sturgess in San Francisco and Smooth-on brand which you can purchase online.
The electric components are all from parts express. for sculpture materials for speaker components
I have include the STL file for the speaker at the end of the post !
P.s. this is my first instructables post. I try my best at explaining things clear and simple. however some of the steps won't have photos.
Step 1: Design the Speaker Shell
I use Autodesk 3DS Max for modeling. the program might take a few days to get familiar with the interface and hotkeys. overall is a very powerful 3d software. I didnt need to learn that much in depth because all i need is to have the form build in polygon. the polygon count should be fairly low to achieve this geometric aesthetic.
there are few tips when making the model.
1. always try to make polygon that have 4 to 6 sides. it will be easier to cut once is printed on paper. avoid acute angles when separate the polygon mesh.
2. make sure no over lapping vertices
3. the model has to be one whole shell in order to have a good import in pepakura. make sure there is no parts that intersect
4. check the scale and volume after the model is done. make a close estimate to the speaker's Optimum Cabinet Size that is stated on parts-express . so pick a woofer, and write down the volume it needs. then scale the model to a size that has such volume.
Step 2: Import to Pepakura
Save the file to obj or STL
import to pepakura. then start separate the model into paper patterns
I use 110lb/298gm letter size cardstock to print the patterns. pick a cardstock that is very stiff but not too thick is very important.
make sure the paper doesnt have any coating on it. on the plane surface where the speaker is held print out the pattern and glue it to a big sheet. then trace it onto plywood or MDF sheet. it can be 1/4 to 1/2 inch thick.
Step 3: Construct the Wooden Frame
once the pattern is traced on wood board. I precisely cut the pattern with a jigsaw. then sand the edges smooth. The size for cutout baffle for speaker is also stated on parts-express.com.I used 1/2 '' ply wood to attach the speaker . 1'' at the base. the structure should be vertical to the ground
Step 4: Reinforce the Paper Shell.
Once the paper shell is cut ,score on the fold lines and glue them together. with the heavy card stock the shell can hold its shape without any resin reinforcement. brush on composite polymer material mixture. on the inside of the the shell. and glue the shell to the wood base.
for the composite polymer mixture. i use epoximite fast from smooth-on, mix with calcium carbonate, poly fill micro filber, silica fume, 1/4 chopped fiber and 1/2 chopped fiber. the result is a cream cheese consistency opaque paste that cures to a hardness of 84D shoreA and also light weight.
Step 5: Sanding
sand any overlap paper edge that is not soaked with the composite polymer. filling any dent and blemish with automotive filler. I recommend EASY SAND from EVERCOAT. to avoid buildup. apply small batch at one time. then sand with 80 grit sand block. finishes with 220 grit sand block.
Step 6: Prime and Paint
Use 3 coats of High build 2k primer. then 3 coats of base coat. finishes with 3 coats of clear.
Step 7: Assemble the Speaker Parts
wire the crossover board with the speakers. make sure the ohm matches the crossover board. polish with spray wax.
Step 8: Replicate , Making Mold
the mold making process is very difficult since it is my first ever mold. and the speaker is considered large with complex shape. it took me 3 tries to make a usable mold. the process was stressful but at the end I succeeded.
so first i did spray a generous amount of release agent on the surface. Once it is dried build the seam line with clay where the silicone mold separates. I used plastalina clay contents no sulfur.
the silicone mold is made of mold star 30 from Smooth-on. Brush on at least 6 thin layers on one side. the silicone mold should be at least 1/2 inch thick.
the mother shell is made of 5 pieces. I used Plasti Paste from Smooth-on.
Step 9: Rotational Casting.
once the mold is made. it's ready for casting. I use white polyurethane that has a 10minutes demold time. for each piece, the first pour only contents polyurethane resin to capture the maximum detail. the 2-4 time i poured a mixture of polyurethane resin with chopped fiber and poly fill micro fiber. then Sand any blemish and seams. whip clean with alcohol. it's ready to paint!
the last image you can see I made 3 molds, the two on the left were not successful. so be patient and very careful when make the mold. once a quality production mold is made, you can cast any many speakers as you would like.
Step 10: Paint and Assemble
repeat the paint process
3 coats of high build 2 k primer.
3 coats of base coat
3 coats of clear
Step 11: Speakers in Perfomance
These speakers really sound amazing. although, I m not a sound expert and these speakers are not intended to be hi-fi sound systems, they are just as good as any home stereo. the key is to have the shell sealed to create an sealed volume so no air can escape from the inside. I used hot glue gun to seal the bottom with a 3/4 wooden base that is painted to the same color. I was very fortunate to show them at the De Young museum in San Francisco with my mentor Rigo 23 and DJ Dino. These speakers were also shown in Swell Gallery in San Francisco this year.
once again. this is my very first instructable post and I have learned most of the knowledge through instructables.com, youtube tutorials and forums online. I hope to share my learning and my experience with the online viewers as well.
let me know there is anything you would like to know more.
The STL file of this speaker model is available on thingiverse.
I am a MFA student in San Francisco Art Institute. if you like my work, there are more speaker sculptures on my website.
Practice and Enjoy
Participated in the
DIY Audio and Music Contest
Be the First to Share
Recommendations
21 Discussions
2 years ago
Amazing job! Beautiful work!
4 years ago
These are epic, amazing work, I really must get into making molds
4 years ago
this speaker looks amazing, my school basketball team is the jackals, think we need a team one for practices
5 years ago
Beautiful work. I have been into Ancient Egyptian Art, Culture, and History since I was a child. Well done and the Scarab is extremely impressive! Very well done!!! Keep them coming!!! ;-)
5 years ago on Introduction
Really neat! Very professional result too. Now I want to make some cool speakers. xD
5 years ago
Are these for sale?
Reply 5 years ago on Introduction
Not at this moment. Just a part an installation. :)
5 years ago on Step 11
wow, that's cool job have been done. Did you upload the scarab beetle design speaker there?
Reply 5 years ago on Introduction
Not yet . Ima do it real soon!
5 years ago on Introduction
Wow, looks really great :D Good job! ^^,
5 years ago on Introduction
What speaker parts did you use?
Reply 5 years ago on Introduction
5 inch woofer with 2 inch tweeter. the crossover component is 2way cross @ 3.5k
Reply 5 years ago on Introduction
Thank you, I am thinking of making one!
5 years ago
Now this is what instructables was made for
Love it
5 years ago
How much for a pair?
Reply 5 years ago on Introduction
Hi, they are not for sale right now. I am preparing for my Graduate exhibition and these will be included in the show. I will probably sell them after that. :)
5 years ago
awesome
5 years ago on Introduction
This is a really cool speaker design!
Reply 5 years ago on Introduction
Thanks I will post some more on Instructables later on. There are more on my website feel free to check out.
5 years ago
Wow! I want a pair. Thanks for sharing | https://www.instructables.com/id/Handmade-Anubis-Art-Speaker/ | CC-MAIN-2020-34 | refinedweb | 1,615 | 84.88 |
I “print” statements sprinkled throughout code. Of course, “print” takes many forms—dump pertinent data structures, emit trace statements to standard error, and log interim results in a separate file—and there are cases where these methods are mandated. Still, it puzzles me why more skilled developers do not use a debugger. Extensions to PHP allow for interactive forensics; Perl running within mod_perl supports debugging; and Ruby on Rails’s Mongrel provides the --debugger option to interrupt execution and drop to a debug console.
In my Rails work, I use the debugger extensively. The debugger combines the power of the Rails console and the Interactive Ruby Debugger, irb, and peers into running code responding to incoming requests. Better yet, I can yield to the debugger console anywhere—in a controller, a view, a plug-in or helper. Within the debugger, I can inspect the stack, variables, the params hash, and more.
Installing the Debugger
The debugger, ruby-debug, is provided as a Ruby gem and installs just as easily as any other extension.
$ sudo gem install ruby-debug
Once installed, you can invoke the debugger anywhere in your code with a call to debugger.
class ExampleController < ApplicationController
def index
# ...
debugger
# ...
end
end
By default, Rails's script/server ignores calls to the debugger (and instead emits a message such as Debugger requested, but was not available). To enable the debugger and temporarily halt execution at each call, launch Mongrel with the option --debugger.
$ ruby ./script/server --debugger
=> Booting Mongrel
=> Rails 2.3.2 application starting on
=> Debugger enabled
=> Call with -d to detach
=> Ctrl-C to shutdown server
Once the debugger is enabled, each call to debugger generates a command prompt. The prompt is prefaced by the file name and line number where the call occurred and the next line of code to execute.
/Users/supergiantrobot/Projects/dc/trunk/app/controllers/search_controller.rb:32
@results = Part.uniqify( @results ) if logged_in?
(rdb:3)
(The 3 in the prompt is the thread number, which you can safely ignore if you're not juggling multiple threads.) At the prompt, you can type a number of commands to help ferret out your mistake. When in doubt, simply type help for a list of available commands or help command for hints about a specific command.
Commands to Query State
Like gdb (the Linux debugger for many languages) and Firebug (the Firefox debugger for JavaScript), rdb provides instructions to march through code and examine state. Here's an example using some of the most common commands.
The sample code prints the catalog of revisions made to records in the database. The controller is standard; the view is written in HAML, but could just as well be any other format. A call to debugger has been added at the start of the index action.
class RevisionController < ApplicationController
before_filter :login_required
def index
debugger
@revisions = Revision.paginate :page => params[:page],
:order => 'created_at DESC'
end
end
%table
- @revisions.each do |revision|
%tr
%td
= revision.author.capitalize
%td
= revision.field
%td
= revision.value
The first command is list (which can be abbreviated to simple l, or lowercase L). It prints the ten lines of code surrounding the breakpoint to provide context.
.../app/controllers/revision_controller.rb:7
@revisions = Revision.paginate :page => params[:page],
(rdb:20) list
[2, 11] in .../app/controllers/revision_controller.rb
2 before_filter :login_required
3
4 def index
5 debugger
6
=> 7 @revisions = Revision.paginate :page => params[:page],
8 :order => 'created_at DESC'
9 end
10 end
The arrow (=>) reflects the program counter, or the statement about to execute. If you type list again, it shows the next ten lines of code.
The next command is print or p. It reveals the value of its argument, and formats the output as inspect would.
(rdb:20) p params
{"action"=>"index", "controller"=>"revision"}
(rdb:20) params
{"action"=>"index", "controller"=>"revision"}
Inspecting a variable is so common, there's a shortcut: omit print and simply type the name of the variable. That's the latter command above.
The backtrace command displays the call stack. The current frame—that is, the frame where you called debugger&mdashlis numbered 0. Commands such print and list always apply to the current frame.
Preceding call frames are numbered 1, 2, and so on. Use the frame n command, where n is a frame number, to move to a specific frame. Again, an arrow (-->indicates your current frame.
(rdb:20) backtrace
--> #0 RevisionController.index
at line .../app/controllers/revision_controller.rb:7
#1 Kernel.send(e#NilClass)
at line .../actionpack-2.3.2/lib/action_controller/base.rb:1322
...
#44 Mongrel::HttpServer.run
at line .../mongrel-1.1.5/lib/mongrel.rb:285
(rdb:20) frame 44
(rdb:20) list
[280, 289] in /opt/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/lib/mongrel.rb
280 if worker_list.length >= @num_processors
281 STDERR.puts "Server overloaded with #{worker_list.length} processors (#@num_processors max). Dropping connection."
282 client.close rescue nil
283 reap_dead_workers("max processors")
284 else
=> 285 thread = Thread.new(client) {|c| process_client(c) }
286 thread[:started_on] = Time.now
287 @workers.add(thread)
288
289 sleep @throttle if @throttle > 0
(rdb:20) backtrace
#0 RevisionController.index
at line /Users/supergiantrobot/Projects/dc/trunk/app/controllers/revision_controller.rb:7
...
--> #44 Mongrel::HttpServer.run
at line .../mongrel-1.1.5/lib/mongrel.rb:285
By the way, if you want to know what instance variables are defined in the current frame, type instance_variables.
(rdb:20) frame 0
#0 RevisionController.index
at line .../app/controllers/revision_controller.rb:7
(rdb:20) instance_variables
["@_params", "@request_origin", "@_request", "@search_options", "@performed_render", "@_headers", "@template", "@action_name", "@_response", "@url", "@performed_redirect", "@before_filter_chain_aborted", "@target", "@_session"]
You can also use the var command to query global variables, local variables, and constants and instance variables in any object.
(rdb:20) var global
$! = nil
...
$tcp_defer_accept_opts = nil
$~ = nil
(rdb:20) var local
__dbg_verbose_save => false
const_name => :Revision
e => nil
parent_qualified_name => nil
qualified_name => nil
(rdb:20) var instance Inventory
@after_create_callbacks = [#<ActiveSupport::Callbacks::Callback:0x262f35c
@identifier=nil, @kind=:after...
...
@observer_peers = [#<StockObserver:0x25f4090>]
@parent_name = nil
Next: Commands to Control Execution
I’m truly enjoying thhe design and layout off your
site. It’s a very easy on the eyes which makes it much mmore pleasant ffor me to come
here and visit mire often. Did you hire out a developer to create your theme?
Fantastiic work!
Allso visit my blog post; cheap car insurance
It is not my first time to visit this site, i am browsing this
website dailly and get good data from here every day.
my web blog; cheap car insurance california
It’s actually a cool and useful piece of info. I’m happy that
you simply shared tbis useful information with us.
Please keep us informed like this. Thank you for sharing.
my web site – cheap car insurance
When someone writes an article he/she retains the idea of a user
in his/her mind that how a user can know it. Therefore that’s whhy this article is great.
Thanks!
Feel free to visit my blog – cheap car insurance florida
Verry good article. I aam dealing with some of these issues as well..
Here is my web site – cheap car insurance for students
Thankls for a marvelous posting! I quite enjoyed
reading it, you may bee a great author.I will ensure that I bookmark your blog and will
eventually come back in the future. I want to encourage yourself to continue your great work, have a
nice evening!
Stop by my web site cheap car insurance online
Hey! Do you know if they make any plugins to help with SEO?
I’m trying tto get mmy bloog to rank for some targeted kehwords
but I’m not seeing very good success. If youu know of
any please share. Many thanks!
Also visit my blog ::
Also visit my blog ::
My web page :: ancientayurved.net
Quality content is the important to invite the viewers to visit the website, that’s what this
web page is providing.
Feel free to visit my blog post :: cheap car insurance
Together with every thing that appears to be building within this particular subject material, many of your opinions are actually rather exciting. Nonetheless, I am sorry, because I do not subscribe to your entire idea, all be it exhilarating none the less. It seems to us that your remarks are not completely rationalized and in reality you are yourself not totally certain of the point. In any case I did take pleasure in reading through it.
The crux of your writing whilst appearing agreeable in the beginning, did not really settle very well with me after some time. Somewhere within the sentences you actually were able to make me a believer but only for a while. I nevertheless have a problem with your jumps in assumptions and you might do nicely to fill in those breaks. When you can accomplish that, I could surely be fascinated.
Hello! I could have sworn I’ve been to this blog before but after
looking at many of the posts I realized it’s new to me.
Nonetheless, I’m definitely happy I discovered it and
I’ll be book-marking it and checking back regularly!
Here is my blog … Cheap car insurance
The very root of your writing whilst appearing agreeable originally, did not work properly with me personally after some time. Someplace throughout the sentences you were able to make me a believer but only for a while. I nevertheless have got a problem with your jumps in assumptions and one would do well to help fill in all those gaps. In the event that you can accomplish that, I will definitely end up being impressed.
Eveгүtthing iѕ vегʏ ореn witһ ɑ
ѵeгу сⅼеаг claгіfіcatіⲟn оf tɦе cһaⅼⅼеngеѕ.
Іt ᴡаѕ ɗefіnitеⅼү infօrmɑtiνе.
Ⲩоur ѕіtе іѕ
usᥱfսⅼ. ТҺаnkѕ
fⲟг ѕһaгіng!
My ѡᥱЬlоg …
is.gd/kSuBvD
I do like the way you have presented this issue plus it does indeed supply us a lot of fodder for consideration. On the other hand, coming from everything that I have experienced, I really wish when the actual feedback stack on that people stay on point and don’t start upon a soap box regarding the news of the day. Still, thank you for this fantastic piece and whilst I can not necessarily go along with the idea in totality, I value the perspective.
It was my pleasure finding your site this morning. I got here now hoping to uncover something new. I was not disappointed. Your ideas with new techniques on this thing were topical and a wonderful help to my family. Thank you for having time to create these things along with sharing your notions.
Awesome blog.Much thanks again. Awesome.
Throughout the awesome design of things you actually receive a B- with regard to hard work. Exactly where you actually confused everybody ended up being on your specifics. You know, people say, the devil is in the details… And it couldn’t be more accurate in this article. Having said that, let me say to you what did do the job. Your writing is definitely pretty convincing which is possibly the reason why I am making the effort to comment. I do not really make it a regular habit of doing that. Second, while I can easily see the jumps in reasoning you make, I am not necessarily convinced of just how you seem to unite your ideas which inturn help to make your conclusion. For right now I shall subscribe to your position but wish in the future you link your dots better.
I do love the manner in which you have framed this matter and it does indeed supply me some fodder for thought. Nevertheless, through just what I have seen, I only wish when the reviews stack on that people keep on issue and in no way get started on a soap box regarding some other news du jour. Yet, thank you for this superb point and although I can not really concur with this in totality, I respect the perspective.
A large percentage of of whatever you point out happens to be astonishingly appropriate and it makes me ponder why I hadn’t looked at this in this light before. This article truly did turn the light on for me as far as this issue goes. But at this time there is actually just one issue I am not necessarily too comfy with so while I make an effort to reconcile that with the actual core theme of your position, permit me observe just what the rest of your readers have to say.Well done.
I am so grateful for your article.Really thank you! Really Cool.
Throughout the grand design of things you actually secure a B+ for hard work. Where you confused me was first in all the facts. You know, people say, the devil is in the details… And it couldn’t be much more accurate in this article. Having said that, let me say to you exactly what did work. The authoring can be extremely convincing and that is possibly the reason why I am taking the effort in order to opine. I do not make it a regular habit of doing that. 2nd, although I can easily notice a leaps in reason you make, I am not necessarily certain of how you seem to unite your ideas which help to make your final result. For the moment I will yield to your issue however hope in the near future you link the facts better.
Most of the things you mention is supprisingly appropriate and it makes me wonder the reason why I had not looked at this in this light previously. This article truly did switch the light on for me as far as this specific issue goes. Nonetheless at this time there is one point I am not really too comfy with and while I try to reconcile that with the actual central idea of the issue, permit me observe exactly what the rest of your visitors have to point out.Well done.
The crux of your writing whilst appearing agreeable initially, did not really work properly with me personally after some time. Someplace throughout the paragraphs you were able to make me a believer unfortunately just for a short while. I still have got a problem with your jumps in logic and one might do nicely to fill in those gaps. If you actually can accomplish that, I would surely end up being amazed.
In this awesome scheme of things you actually get an A+ for effort. Exactly where you actually lost us was first in the facts. As as the maxim goes, details make or break the argument.. And that couldn’t be more accurate at this point. Having said that, allow me say to you what did deliver the results. The text can be very persuasive which is probably why I am taking the effort to opine. I do not really make it a regular habit of doing that. Next, while I can certainly see a leaps in reasoning you make, I am not necessarily sure of exactly how you seem to unite the points which produce the actual conclusion. For now I shall subscribe to your position however wish in the foreseeable future you link the facts much better.
The very core of your writing whilst sounding reasonable in the beginning, did not work properly with me personally after some time. Someplace within the paragraphs you managed to make me a believer unfortunately only for a short while. I however have a problem with your leaps in logic and one would do well to help fill in those breaks. If you can accomplish that, I could definitely end up being impressed.
The heart of your writing while appearing agreeable originally, did not work properly with me personally after some time. Somewhere within the sentences you managed to make me a believer but only for a while. I nevertheless have a problem with your leaps in assumptions and you would do nicely to help fill in those breaks. When you can accomplish that, I will definitely end up being fascinated.
Throughout this awesome scheme of things you secure an A for effort and hard work. Where you confused everybody ended up being on your specifics. You know, they say, the devil is in the details… And it couldn’t be more correct here. Having said that, allow me tell you exactly what did do the job. Your text is actually incredibly persuasive which is most likely why I am making the effort to opine. I do not really make it a regular habit of doing that. 2nd, despite the fact that I can easily notice a jumps in reasoning you make, I am not really certain of exactly how you appear to unite your points which inturn help to make your final result. For right now I will subscribe to your point but wish in the future you connect the facts better.
Just about all of what you claim is supprisingly precise and that makes me ponder why I had not looked at this in this light previously. This particular article really did turn the light on for me personally as far as this particular issue goes. Nonetheless there is actually one factor I am not too comfortable with and while I attempt to reconcile that with the actual core theme of the point, allow me observe just what the rest of your visitors have to say.Well done.
Throughout this awesome design of things you secure an A with regard to effort. Exactly where you actually misplaced me personally ended up being on the specifics. As as the maxim goes, details make or break the argument.. And it couldn’t be much more true here. Having said that, let me say to you just what did do the job. Your article (parts of it) is actually really engaging which is probably the reason why I am making the effort in order to comment. I do not really make it a regular habit of doing that. Next, whilst I can see a leaps in reason you come up with, I am not convinced of just how you appear to connect your points which inturn make the actual conclusion. For now I shall subscribe to your issue but hope in the future you link your facts much better.
I simply want to tell you that I am just all new to blogs and actually loved you’re blog site. Almost certainly I’m likely to bookmark your site . You definitely come with outstanding posts. Cheers for sharing your web page.
I will right away clutch your rss feed as I can not to find
your email subscription link or e-newsletter service.
Do you have any? Please permit me recognise in order that I
may just subscribe. Thanks. | http://www.linux-mag.com/id/7319/ | CC-MAIN-2016-36 | refinedweb | 3,146 | 64.51 |
Your official information source from the .NET Web Development and Tools group at Microsoft. needs to be optimized until you measure perf. This tutorial will primarily use a modified version of Tom Dykstra's EF6/MVC 5 Contoso University app to introduce you to measuring and monitoring performance.
This topic contains the following sections:
Add the StopWatch NuGet package to your ASP.NET MVC app using the following command in the Package Manager Console:
PM> Install-Package StopWatch
The StopWatch package will create a Filter directory and add a class containing the UseStopwatch attribute. You can apply this filter to controllers with the following syntax:
UseStopwatch
[UseStopwatch]
public class HomeController : Controller
{
To apply it globally (that is to every controller), add the following code to the App_Start\FilterConfig.cs file:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new UseStopwatchAttribute());
}
}
Add settings to the root web.config file to control how timing information is sent to the trace system. For development we want all requests to be under 250 MS. Action methods taking more than 500 MS are recorded at the warning level, and requests taking more than 2.5 seconds are considered errors. In the markup below, we've also set ShowTimeInLayout to 1 (true), so every page will display the elapsed time. We will show timing information for each page in development and test, but not in production. Later in the tutorial I’ll show how to set these values outside of source code for the Azure environment.
ShowTimeInLayout
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<!-- Keys deleted for clarity. -->
<add key="TraceErrorTime" value="2.5" />
<add key="TraceWarningTime" value=".5" />
<add key="TraceInformationTime" value=".25" />
<add key="ShowTimeInLayout" value="1" />
</appSettings>
<system.web>
The last change we need to make is to add the timing information to the Views\Shared\_Layout.cshtml file:
<footer>
<p> @Html.Encode(ViewBag.elapsedTime) </p>
</footer>
Run the app, each page shows the elapsed time for the action method.
If you're running in Visual Studio, you can see the trace data in the output window:
Deploy the app to Azure where you can see the page level timings.
You can configure Azure settings in the Azure portal or in Visual Studio. Most of the steps in the following section will be done in Visual Studio, but they are easily done in the Azure portal. In Server Explorer, navigate to your web site (con2 in the image below), right click > View Settings.
Set the Application Logging level to Verbose. The Verbose level logs all trace message. Setting it to Information logs Information, Warning and Error levels. Setting it to Warning logs Warning and Error levels. You can set the logging level in the Azure portal on the Configure tab of the web site:
Run the app on Azure, and in Visual Studio, navigate to your web site, right click > View Streaming Logs:
The output window in shows the trace data. Note the filter lists all the route data plus any query string data.
Looking at trace data from Visual Studio is interesting, but it's not a viable approach to production monitoring. A good way to save trace data on Azure is to connect the trace provider to Azure storage.
In Server Explorer, right click Storage > Create Storage Account.
In the Azure portal, click on your web site and select the Configure tab. Under application diagnostics set application logging (blob storage) to On. Set the logging level to Information. Click the manage blob storage button and enter the storage account you created. (Note: if you don't see the storage account you created from Visual Studio, navigate to the storage account in the portal and force a full refresh of the browser (^F5)).
Click Save. Test you web app so you can generate trace data.
In Server Explorer, navigate to the blob storage you created and double click on the container.
Double click on the trace data log to open it in Excel.
You can use Excel to sort the data and hide columns you're not interested in.
In Server Explorer, navigate to your web site (con2 in the image below), right click > View Settings.
Under Application Settings, hit the Add button to add the app settings from the web.config file. The app settings here will override those in the web.config file. On a production app, we won't want to show page timings.
The simple stopwatch filter misses the authorization portion of the ASP.NET pipeline (which can be expensive), and it stops timing after the OnResultExecuted completes. The filter completely ignores client side timing, which can be significant. Glimpse is a much more powerful tool to profile and monitor your ASP.NET app - stay tuned, I'll be blogging on that next.
Probably good to mention MiniProfiler as well?
I have a simple MVC 5.2 site.
I added package, added filter, added ShowTimeInLayout in web.config, and added elapsed time to the footer. When I F5 in VS, I don't see elapsed time on any page.
Is this something that only runs on full IIS, or is there a necessary fifth step?
Pete - put a break point in Filters\UseStopwatchAttribute.cs OnResultExecuting and examine ViewBag.elapsedTime
Hi Rick, I put out some fires and returned to this experiment.
At the breakpoint ViewBag.elapsedTime was null.
I pushed the web site to Azure and ran it there, and the elapsed time showed up in the footer. I'm guessing it behaves differently on full IIS than it does with F5 in VS.
@pete - no, it works fine in iisexpress/F5/VS. Put a break point in the filter and see if it's getting set. Do some debugging and let me know why it's not working for you. | http://blogs.msdn.com/b/webdev/archive/2014/07/29/profile-and-time-your-asp-net-mvc-app-all-the-way-to-azure.aspx | CC-MAIN-2015-27 | refinedweb | 974 | 58.79 |
I've got this school assignment that I must do, but I have certain problems with it.
(I'm programming use the programing language C, btw)
[Please do not flame me, I'm new and I'm probably asking some very newbie questions :) ]
The assignment is as follows:
1) I am to make a small program that in which the user is to input some text and the program outputs the same text, but removes 'white spaces' (tabs \t, new lines \n, double spaces, etc).
2) the second assignment is basically the same this as the first one, accept the user inputs a string that represents C programing language code and removes all the comments.
The problem is I don't know how to do that. :( We've been introduced to the %s which inputs a string the user enters, but it stops on the first space and doesn't go further. I know that, but how do I enable the program to accept the whole thing, with white spaces?
For example, my program should do the following:
user input: This is a /n sample /t code .
program output: This is a sample code.
(don't worry about my program exceeding the array limit, it's not an issue here)
Alright, now here's my code:
#include <stdio.h> #include <stdlib.h> int main() { char niz[50]; int i=0; printf ("String plz \n"); scanf ("%s", niz); getchar(); for (i=0; i<50; i++) { if ( niz[i]=='\0') break; printf ("%c", niz[i]); } printf ("\n TEST %c", niz[5]); return 0; }
Thanks for everyone in advance! | http://forum.codecall.net/topic/39203-newbie-questions-regarding-inputing-a-sentence/ | crawl-003 | refinedweb | 266 | 74.12 |
Hi,
This is an exercise I solved it, I want to know, is my solve is the best solve or there is notes, if there is a notes, I'm glade to hear it:
The Exercise:
Make a program that calculates the sum, mean, minimum, and maximum of a series of numbers. Example: numbers: 10, 12, 10, 14 The sum is 46, the mean is 11.5, the minimum is 10, the maximum is 14.
My solve:
#include <iostream> using namespace std; void main() { float sum, mean, minimum, maximum; float numbers[4]={10,12,10,14}; sum=numbers[0]+numbers[1]+numbers[2]+numbers[3]; cout << "Sum = " << sum << endl; mean=sum/4; cout << "Mean = " << mean << endl; }
how can I find minimum and maximum from array? | https://www.daniweb.com/programming/software-development/threads/282945/c-excercise-and-my-solve | CC-MAIN-2018-43 | refinedweb | 125 | 60.99 |
XML Report Definition
The Standalone Report Designer supports trdp, trbp, trdx file formats that contain report and report book definitions serialized in XML.
XML Reports Versions
A report definition file specifies the Telerik Reporting XML namespace for the version of the report definition schema that is used by the Telerik Reporting XML serializer (Standalone Report Designer) to identify the XML content.
Upgrade XML Reports
The Standalone Report Designer can open report container files created for a previous namespace. If the report is changed and saved the upgraded report definition is converted and saved with the newer schema. This is the only way to upgrade an XML report definition but it's not required because the report viewers, the report server and the ReportProcessor can handle all previous XML report versions. The report definition itself is not upgraded when uploaded on the Report Server.
The previous statements are valid only for reports authored in Standalone Report Designer. The compiled type reports authored in Visual Studio are upgraded with Upgrade Wizard. For more information, see Overview.
How to: Identify the report definition schema version
The schema version is used by the Standalone Report Designer to identify supported report definitions. The Standalone Report Designer supports the current XML schema version at the time of the designer release and all previous ones.
Open the report definition:
For trdx extension: use an application such as Notepad in which you can view the XML.
For trdp and trbp extensions:
Make a backup of the report definition.
Open the report definition with archiving program that supports zip.
Right-click the report.
Select Open with... option.
Choose a zip manager. For example, the free 7-Zip application.
Use an application such as Notepad in which you can view the XML to open the definition.xml file.
Check the xmlns attribute part of the Report element It should look like this:. The above xmlns attribute means that this definition is introduced in 2017 R3 SP1. For more information see the following section.
XML Schema Versioning
The XML schema versioning prior to 2017 R3 is incremental. To check when specific XML schema version is introduced see the following table:
From 2017 R3 on, the version numbering corresponds with the product release it was introduced in. The format is:[year]/[release].[sp]
For example, the version introduced in 2017 R3 will look as following: | https://docs.telerik.com/reporting/designing-reports/report-designer-tools/desktop-designers/standalone-report-designer/xml-report-definition | CC-MAIN-2022-40 | refinedweb | 393 | 56.45 |
Today we had a requirement to do some pretty strange stuff in SQL which required us to call an encryption library in SQL server. This is something I had not done before, so I thought I would blog about it.
There are several steps involved.
The 1st part is straight forward enough, the following code gives an example
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4: using Microsoft.SqlServer.Server;
5: using System.Data;
6: using System.Data.Sql;
7: using System.Data.SqlTypes;
8: using Encrypt;
9:
10: public class StoredProcedures
11: {
12:
13: [Microsoft.SqlServer.Server.SqlFunction()]
14: public static string Enc(SqlString password, SqlString encStringOut)
15: {
16: Encryption enc = new Encryption();
17: return enc.Encrypt(password.ToString(), encStringOut.ToString());;
18: }
19:
20: [Microsoft.SqlServer.Server.SqlFunction()]
21: public static string Dec(SqlString password, SqlString encStringOut)
22: {
23: Encryption enc = new Encryption();
24: return enc.Decrypt(password.ToString(), encStringOut.ToString()); ;
25: }
26: }
So thats easy enough. Compile this job done.
So next we need to do the SQL server work. So firstly I copied the SQLServerEncryption.Dll to the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn directory of the SQL server machine.
I also copied the Dll generated (SQLServerEncryption.Dll) to the C:\ drive on the SQL server machine, as it makes the Dll registration code that needs to be run for SQL a bit easier.
So we’ve copied to \binn and C:\ so far, so now we need to register the Dll with SQL server. So lets look at that
Firstly we need to allow CLR types in the SQL server installation. Which is either done using the following SQL
EXEC dbo.sp_configure ‘clr enabled’,1 RECONFIGURE WITH
Or if you have issues doing it that way use the SQL Server Surface Area Configuration, use the “Surface Area Configuration For Features” link, and then CLR integration from the presented treeview. Once this is done we can register the CLR Dll with SQL, as follows
create assembly SQLServerEncryption from ‘c:SQLServerEncryption.dll’ WITH PERMISSION_SET = SAFE
Now that weve done that, all thats left to do is create a normal SQL server function that uses the CLR Dll. Which is simply done as follows
ALTER FUNCTION [dbo].[ENCRYPT](@password [nvarchar](255), @encStringOut [nvarchar](255))
RETURNS [nvarchar](255) WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [SQLServerEncryption].[StoredProcedures].[Enc]
And that it you can now use the CLR Function as you like. For example
dbo.ENCRYPT(‘xxxx’,’sb_SQL’). | https://www.codeproject.com/Articles/37377/SQL-Server-CLR-Functions | CC-MAIN-2017-04 | refinedweb | 416 | 59.5 |
Problem:"] As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”, return its length 5.
Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters.
Solution:
We can use BFS to solve this problem. It’s a breadth first search. Put the first word in a queue.
Then, while the queue is not empty, check all possible combinations of the word changing one letter.
If the word exists in the dictionary, check if it is the word you’re looking for, if its not, put it in the queue with the count of the word you’re checking right now plus 1.
If it was the word you’re looking for, return the current word’s count.
Implementation:
public class CrazyForCode { public int ladderLength(String start, String end, Set<String> dict) { if (start == null || end == null | | dict == null || dict.size() == 0) { return 0; } Queue<String> queue = new LinkedList<String>(); queue.offer(start); dict.remove(start); int length = 1; while (!queue.isEmpty()) { int count = queue.size(); for (int i = 0; i < count; i++) { String current = queue.poll(); for (int j = 0; j < current.length(); j++) { for (char c = 'a'; c <= 'z'; c++) { if (c == current.charAt(j)) { continue; } String temp = replace(current, j, c); if (temp.equals(end)) { return length + 1; } if (dict.contains(temp)) { queue.offer(temp); dict.remove(temp); } } } } length++; } return 0; } private String replace(String s, int index, char c) { char[] chars = s.toCharArray(); chars[index] = c; return new String(chars); } }
contact jay permanent | http://www.crazyforcode.com/word-ladder-problem/ | CC-MAIN-2016-50 | refinedweb | 259 | 77.43 |
****I'm stuck as to what my next step should be?? I also want to know if I'm on the right track. I've tried searching for some type of sample program as I am sure there are plenty, but when I start to write it doesn't seem to make sense. Any sort of help is appreciated. Thank you.
*************************
Write a program to help a cafe automate its breakfast billing system. The program should do the following:
• Show the customer the different breakfast items offered by the restaurant. The items are in a file so it can easily be changed. The name of the file is MenuData.txt.
• Allow the customer to select more than one item from the menu.
• Calculate and print the bill.
Use a struct called menuItemType that has the follwing members: a string called menuItem and a double called menuPrice.
Use an array called menuList to store the menu which is read in from the file. Use a constant global variable to set the number of items in the menu so it can easily be changed if the number of items changes.
The program must contain the following functions:
• getData: Load the data from the file into the array menuList.
• showMenu: Display the menu to the customer. The customer must be told how to select items.
• printCheck: Calculate and print the check. A 5% tax is added to the total.
Output should be formatted to two decimal places. The name of each item must be left-justified. You may assume a user selects only one item of a particular type.
Sample Output
Thank you for eating at Our Restaurant
Bacon and Egg $2.45
Muffin $0.99
Coffee $0.50
Tax $0.20
Amount Due $4.14
************************************************
This is what I have so far. I didn't think it was too long to post it all.
#include <iostream> using namespace std; struct menuItemType { char menuItem[21]; double menuPrice; }; const int numitems = 8; int main () { int i = 0; menuItemType.menuList [listLength]; while ( i < listLength) { cout << i + 1 << " " << menuList [i] menuItem << " " << menuList [i] menuPrice << endl; i++; } system ("pause"); return 0; } void showMenu () { } void getData () { fstream file; char ch; for (int i = 0; i < listLength; i ++) { file.get(menuList [i].menuItem, 21); file >> menuList [i].menuPrice; file.get(ch); } } void printCheck () { } | https://www.daniweb.com/programming/software-development/threads/145624/stuck-writing-a-fairly-simple-program | CC-MAIN-2018-13 | refinedweb | 384 | 85.28 |
This content has been marked as final. Show 30 replies
15. Re: Conversion Error Occurred807575 Jul 29, 2004 5:07 PM (in response to 807575)i am also having a Conversion Error occured similar to this. However, my error is not cuased by bound fields. I can bind fields just fine, as long as I only have one table in a RowSet. What I did was JOINed 3 tables in one RowSet. SELECT statements work fine, but I can't update. that damn Conversion Error is in my way. what is going on? i actually made a separate thread for this about half an hour ago. please help! thanks!
16. Re: Conversion Error Occurred807575 Jul 29, 2004 5:31 PM (in response to 807575)One other quick note on my example above:
Set the listbox to 'auto-submit on change' and the Conversion Error Occurred message will pop up every time you select a different row in the list (a different Master record). Reselect the original master record in the listbox and the messages will go away.
I just created a simple application using a SQL Server database. This is the code from page1.java:
public class Page1 extends AbstractPageBean {
// <editor-fold
private int __placeholder;
private HtmlForm form1 = new HtmlForm();
public HtmlForm getForm1() {
return form1;
}
public void setForm1(HtmlForm hf) {
this.form1 = hf;
}
private HtmlSelectOneListbox listbox1 = new HtmlSelectOneListbox();
public HtmlSelectOneListbox getListbox1() {
return listbox1;
}
public void setListbox1(HtmlSelectOneListbox hsol) {
this.listbox1 = hsol;
}
private UISelectItems listbox1SelectItems = new UISelectItems();
public UISelectItems getListbox1SelectItems() {
return listbox1SelectItems;
}
public void setListbox1SelectItems(UISelectItems uisi) {
this.listbox1SelectItems = uisi;
}
private JdbcRowSetXImpl triprequestRowSet = new JdbcRowSetXImpl();
public JdbcRowSetXImpl getTriprequestRowSet() {
return triprequestRowSet;
}
public void setTriprequestRowSet(JdbcRowSetXImpl jrsxi) {
this.triprequestRowSet = jrsxi;
}
private IntegerConverter listbox1Converter = new IntegerConverter();
public IntegerConverter getListbox1Converter() {
return listbox1Converter;
}
public void setListbox1Converter(IntegerConverter ic) {
this.listbox1Converter = ic;
}
private HtmlOutputText outputText1 = new HtmlOutputText();
public HtmlOutputText getOutputText1() {
return outputText1;
}
public void setOutputText1(HtmlOutputText hot) {
this.outputText1 = hot;
}
private HtmlOutputText outputText2 = new HtmlOutputText();
public HtmlOutputText getOutputText2() {
return outputText2;
}
public void setOutputText2(HtmlOutputText hot) {
this.outputText2 = hot;
}
private JdbcRowSetXImpl tripsegmentRowSet = new JdbcRowSetXImpl();
public JdbcRowSetXImpl getTripsegmentRowSet() {
return tripsegmentRowSet;
}
public void setTripsegmentRowSet(JdbcRowSetXImpl jrsxi) {
this.tripsegmentRowSet = jrsxi;
}
private HtmlMessage inlineMessage1 = new HtmlMessage();
public HtmlMessage getInlineMessage1() {
return inlineMessage1;
}
public void setInlineMessage1(HtmlMessage hm) {
this.inlineMessage1 = hm;
}
private HtmlOutputText outputText3 = new HtmlOutputText();
public HtmlOutputText getOutputText3() {
return outputText3;
}
public void setOutputText3(HtmlOutputText hot) {
this.outputText3 = hot;
}
private HtmlInputText textField1 = new HtmlInputText();
public HtmlInputText getTextField1() {
return textField1;
}
public void setTextField1(HtmlInputText hit) {
this.textField1 = hit;
}
private HtmlMessage inlineMessage2 = new HtmlMessage();
public HtmlMessage getInlineMessage2() {
return inlineMessage2;
}
public void setInlineMessage2(HtmlMessage hm) {
this.inlineMessage2 = hm;
}
private HtmlOutputText outputText4 = new HtmlOutputText();
public HtmlOutputText getOutputText4() {
return outputText4;
}
public void setOutputText4(HtmlOutputText hot) {
this.outputText4 = hot;
}
private HtmlInputText textField2 = new HtmlInputText();
public HtmlInputText getTextField2() {
return textField2;
}
public void setTextField2(HtmlInputText hit) {
this.textField2 = hit;
}
private HtmlMessage inlineMessage3 = new HtmlMessage();
public HtmlMessage getInlineMessage3() {
return inlineMessage3;
}
public void setInlineMessage3(HtmlMessage hm) {
this.inlineMessage3 = hm;
}
private HtmlOutputText outputText5 = new HtmlOutputText();
public HtmlOutputText getOutputText5() {
return outputText5;
}
public void setOutputText5(HtmlOutputText hot) {
this.outputText5 = hot;
}
private HtmlInputTextarea textArea1 = new HtmlInputTextarea();
public HtmlInputTextarea getTextArea1() {
return textArea1;
}
public void setTextArea1(HtmlInputTextarea hit) {
this.textArea1 = hit;
}
private HtmlMessage inlineMessage4 = new HtmlMessage();
public HtmlMessage getInlineMessage4() {
return inlineMessage4;
}
public void setInlineMessage4(HtmlMessage hm) {
this.inlineMessage4 = hm;
}
private HtmlCommandButton button1 = new HtmlCommandButton();
public HtmlCommandButton getButton1() {
return button1;
}
public void setButton1(HtmlCommandButton hcb) {
this.button1 = hcb;
}
// </editor-fold>
public Page1() {
// <editor-fold
try {
triprequestRowSet.setDataSourceName("java:comp/env/jdbc/travelRequest_dev");
triprequestRowSet.setCommand("SELECT ALL dbo.TripRequest.RequestID, dbo.TripRequest.RequestStatusID, dbo.TripRequest.PreparedByID, dbo.TripRequest.TripTypeID, dbo.TripRequest.BillToDept, dbo.TripRequest.RequestDate, dbo.TripRequest.ShortDescription, dbo.TripRequest.PeopleAndCompany, dbo.TripRequest.Benefit, dbo.TripRequest.Comments FROM dbo.TripRequest");
tripsegmentRowSet.setDataSourceName("java:comp/env/jdbc/travelRequest_dev");
tripsegmentRowSet.setCommand("SELECT ALL dbo.TripSegment.TripSegmentID, dbo.TripSegment.RequestID, dbo.TripSegment.TravelDate, dbo.TripSegment.TravelFrom, dbo.TripSegment.TravelTo, dbo.TripSegment.AirlineID, dbo.TripSegment.FlightNbr, dbo.TripSegment.FlightTime, dbo.TripSegment.RentalCarAgencyID, dbo.TripSegment.RentalCarSizeID, dbo.TripSegment.Hotel FROM dbo.TripSegment WHERE dbo.TripSegment.RequestID=?");
} catch (Exception e) {
log("Page1 Initialization Failure", e);
throw e instanceof javax.faces.FacesException ? (FacesException) e : new FacesException(e);
}
// </editor-fold>
// Additional user provided initialization code
try {
triprequestRowSet.execute();
triprequestRowSet.next();
tripsegmentRowSet.setObject(1, triprequestRowSet.getObject("REQUESTID"));
} catch (Exception ex) {
throw new FacesException(ex);
} // end try catch
}
protected webapplication4.ApplicationBean1 getApplicationBean1() {
return (webapplication4.ApplicationBean1)getBean("ApplicationBean1");
}
protected webapplication4.SessionBean1 getSessionBean1() {
return (webapplication4.SessionBean1)getBean("SessionBean1");
}
/**
* Bean cleanup.
*/
protected void afterRenderResponse() {
tripsegmentRowSet.close();
triprequestRowSet.close();
}
public void listbox1_processValueChange(ValueChangeEvent vce) {
// User event code here...
try {
tripsegmentRowSet.setObject(1, listbox1.getValue());
} catch (Exception ex) {
throw new FacesException(ex);
} // end try catch
}
}
17. Re: Conversion Error Occurred807575 Jul 31, 2004 9:07 AM (in response to 807575)Just fyi, I am going to work w/Haroon first to better understand what's going on here (you are all running into something... but it works fine for me.... and for our QA folks.... so there's something missing from the equation somewhere).
So hang in there and we'll figure it out....
v
18. Re: Conversion Error Occurred807575 Aug 2, 2004 12:48 AM (in response to 807575)V, nice to hear you're working on this. Thanks. It is a show stopper.
I did find one workaround, though: I just changed all my fields to read only and that got rid of the problem. But, gosh, that kind of nulifies the idea of a web application and turns it into a simple web page, huh?
FYI, here's my configuration data:
Desktop:
Windows XP version 5.1 service pack 1 with all the latest patches.
Pentium 4 2GHz processor
1 GB memory
Networked Server:
MS 2000 Server
SQL Server 2000 version 8.00.194, Language English US, 1 processor, Security:Authentication: SQL Server and Windows
Studio Creator:
version 2004Q2 with all the latest updates (build 040621)
Sun Java 1.4.2_04
VM 1.4.2_04-b05
DB URL: jdbc:sun:sqlserver://2000Dev1:1433;DatabaseName=travelRequest_dev;SelectMethod=cursor
DB Driver: com.sun.sql.jdbc.sqlserver.SQLServerDriver
Let me know if I can give you any more info to solve this.
19. Re: Conversion Error Occurred807575 Aug 2, 2004 6:30 PM (in response to 807575)Hi all!
Ok - I worked w/Haroon this morning andI think I understand what's going on here! Let me try to explain.... first I'll summarize the scenario at hand:
=================================
Start w/page with 3 components:
- textfield
- button
- message list
Add a rowset to the page, and bind the textfield to one of the columns in that rowset
Now run. The data shows in the textfield, but when I type something else into the textfield and click the button, a conversion error is shown in the message list.
I haven't added a converter or anything - what's going on? Shouldn't this work?
===========================
Answer : No, but it would be nice if you got a better error message. Now I'll try to explain why!
Textfield is a JSF input component (as is a dropdown, etc). By default, when a page is "submitted" (via button click), in the JSF lifecycle they will inherently go through validation and conversion.
In this case, the textfield is bound to a rowset which by default is set to CONCUR_READ_ONLY (the default concurrency property). So it cannot accept changes (because the rowset won't allow it), and hence an error was thrown durring the conversion stage. Granted, If it had given you an error stack that included something like "rowset does not allow current operation" that would have been helpful :) I'll see if we can do something there (might be deep inside JSF, not sure yet).
So, what do you need to do to get it to work? You have 2 choices:
1) Change the concurrency property to CONCUR_UPDATABLE and then all will be fine
2) Set the immediate property on the button so that it will bypass the conversion/validation phases. For example, you will see that in the AppModel sample, we set the immediate property on the cancel buttons because really, who cares if the stuff isn't valid etc - we're just gonna throw it away anyway. But you should do this only when you are sure you don't want ANY of the validation/conversion to occur for the page. In this scenario, I think it was correctly refusing to update the values in the rowset (although it didn't give a clear enough error message) - so that's a feature :)
Let me know if you have more q's!
Val
20. Re: Conversion Error Occurred807575 Aug 5, 2004 9:38 PM (in response to 807575)v, I tried doing exactly as you outlined, but it doesn't fix the problem.
I built an app with a text field, a button and a message list. I bound the text field to a Microsoft SQL Server database table. I set the datasource to CONCUR_UPDATEABLE.
If I modify the value in the text field and press the button, I still get a "textField1 Conversion error occurred" message. If I remove my changes and put the field back to its original value the error message goes away.
I tried this using three different field types, Integer (with an Integer Converter), Char and VarChar. All of them fail the same way.
I can't get past this problem.
FYI, I also tried the same thing using the embedded Poinbase DB. That runs fine. I do not get the conversion error message. AND, get this: even if I leave the datasource set to CONCUR_READ_ONLY I do not get the error message.
This is all done using the standard datasource driver classes that come with JSC.
The JSC Components are behaving differently based on the underlying database (SQL Server or Pointbase) that the fields are bound to.
I've included the .java code and my system configuration on previous messages on this thread if you need to see them.
Please let me know if I can give you more information on this.
21. Re: Conversion Error Occurred807575 Aug 6, 2004 5:57 AM (in response to 807575)PROBLEM SOLVED
I stopped using the SQL Server driver that came with Creator.
Instead, I switched to using the jtds driver from sourceForge and the problem went away.
22. Re: Conversion Error Occurred807575 Aug 6, 2004 4:16 PM (in response to 807575)Thanks SB for posting your solution - I will ask QA to double check your scenario on SQL Server with our included drivers (Haroon and I were using Oracle for our verification).
Does that driver work at design time as well (server navigator, query editor, etc)? That would be nice to know.
So we have the complete picture, could you please post the sql to create your sql server table you were having trouble with so we are sure we're using the exact same datatypes for our testing?
Glad you're back in business!
v
23. Re: Conversion Error Occurred807575 Aug 6, 2004 4:29 PM (in response to 807575)I tried to recreate the problem using SQLServer that SueBob mentioned, and could not.
It worked fine for me.
When concurrency is: CONCUR_READABLE
I get the conversion error.
When the concurrency is: CONCUR_UPDATEABLE
I don't get the conversion error.
That is how it should be, I think, except for a more user friendly message.
Using JSC drivers.
24. Re: Conversion Error Occurred807575 Aug 6, 2004 4:30 PM (in response to 807575)Also see the tutorial "About DataTable Components" which will show you more "how to"s
hth,
v
25. Re: Conversion Error Occurred807575 Oct 27, 2004 4:46 PM (in response to 807575)Hi!
I from Costa Rica, and my problem is the same "Conversion Error Occured".
I'm using an Oracle Database (with driver ojdbc.jar). I have one page using a datatable which presents no problem with resultset's, I mean, I can do many queries to the database and the datatable works very good. But I have other page with textfields bind to database, when I do the first query The textfield works good and their values are from the database(that it's very good) BUT qhen I try to do other query with other criteria and press the SUBMIT button I see in the page the next text: "txt_num_person:Conversion Error Occurred".
So I tried deleting some textfields and I put some OutputText and the error goes away.
Now my page is working very good with this change, but I need to put in the page the option to insert, delete, etc so it's means that I have to put textfields instead of outputText, and if I do that the error will come back to me!.
I need some help, please.
My e-mail is: wendy@decsacr.com
THANKS!!!!!!
26. Re: Conversion Error Occurred807575 Oct 27, 2004 8:46 PM (in response to 807575)Hi Wendy,
First let's figure out which textfield is the problem.
Add MessageComponents next to each textfield, and associate them together (see the About Message Components tutorial for details at )
This will show you which textfield(s) are having the problem.
Then you will need to examine what type the database is expecting - to do this, go to the server navigator, browse to the table you are binding to, and click on the columns - look at the property sheet. This will tell you the type it is expecting.
Finally, go back to the textfields and associate the appropriate converter - see the table below:
JDBC Type (which we call SQL Type) --> Java Type:
=========================================
CHAR --> java.lang.String
VARCHAR --> java.lang.String
LONGVARCHAR --> java.lang.String
NUMERIC --> java.math.BigDecimal
DECIMAL --> java.math.BigDecimal
BIT --> boolean
BOOLEAN --> boolean
TINYINT --> byte
SMALLINT --> short
INTEGER --> int
BIGINT --> long
REAL --> float
FLOAT --> double
DOUBLE --> double
BINARY --> byte[]
VARBINARY --> byte[]
LONGVARBINARY --> byte[]
DATE --> java.sql.Date
TIME --> java.sql.Time
TIMESTAMP --> java.sql.Timestamp
CLOB --> java.sql.Clob
BLOB --> java.sql.Blob
ARRAY --> java.sql.Array
DISTINCT --> (mapping of underlying type)
STRUCT --> java.sql.Struct
REF --> java.sql.Ref
DATALINK --> java.net.URL
JAVA_OBJECT --> (underlying Java class)
Source: JDBC 3.0 Specification, Appendix B
hth,
v
27. Re: Conversion Error Occurred807575 Oct 28, 2004 5:46 PM (in response to 807575)Hi v,
Thanks for your help.
Actually I had tried with the converter type, but it wasn't work to me. When I tried with this way its happen the next:
1. I have a textfield which it isn't bind to a database. Because in this text will be the criteria for the query.
2. So, when the user put some values in that textfield and press SUBMIT button appears the correct result, its means that I don't have problem with this.
3. BUT when the user try to do an other query (with other criteria) press the CLEAN button. This button has the function to "clean" all the textfields that were full with the previous query. The line is:
textfield1.setValue(" ");
When the page try to do this, in that moment the error come.
I don know if you can understand me?
But it is so weird, because when I put the OutputText instead of Textfields my page works very good!
Please, Help me!!!!
Thanks!!!
Wendy
Costa Rica
28. Re: Conversion Error Occurred807575 Oct 29, 2004 6:46 AM (in response to 807575)Ah - I think you want to set the "immediate" property on the clean button - this will make it so JSF will skip the validation/conversion parts of the lifecycle (which is attempting to convert your settings and failing).
You would also typically want to do this on a "cancel" button as well, since if the user is cancelling an action there's no reason to do any validation/conversion....
I think that should do it!
v
29. Re: Conversion Error Occurred807575 Nov 6, 2004 1:10 AM (in response to 807575)I Guess I�ve got the same problem, till now Does anybody solve this problem ?
Marlos | https://community.oracle.com/message/8435225 | CC-MAIN-2019-35 | refinedweb | 2,646 | 56.66 |
I have a text file which has data in it in the following format:
string string char int double string
Each field is separated by a tab character. The last string of every line contains multiple words. The file can have up to 50 lines (I am guessing if I can do it for 2 lines I can do it for any number of line). The last line of the file has a keyword announcing the end of the file.
I searched the internet, my notes, and textbook for the past 8 hours to figure this out, but it seems like I'm really dumb (at the moment, at least). It must be something relatively easy, but I can't figure it out.
I have to read the data from the text file in such a manner that I can list them later in different forms (e.g., maybe I want to show all the strings in the first and second column, maybe only the string in the second column and the double, etc.).
#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main () { vector<string> lines; //vector to hold all the lines string line; //string to hold intermediary line ifstream myfile ("example.txt"); if (myfile.is_open()) //if the file is open { while ( getline (myfile,line ).good () ) { getline (myfile,line); //get one line from the file lines.push_back(line); /* checking vector size. not what is expected. only every other line is saved. grrrrr!!!! */ cout << "vector size: " << lines.size()<< endl; } /* this for loop is here to test if the vector has saved all the lines from the while above. IT HASN'T. ONLY LINES 2,4,6,8.... ARE SAVED. I DO NOT KNOW WHY! */ for (int i=0; i<lines.size() ;i++ ) { cout << lines[i] << endl; } myfile.close(); //closing the file } else cout << "Unable to open file"; //if the file is not open output return 0; }
If you can give me a BIG HINT on how to do this I would greatly appreciate it. (I probably need more than a hint considering the amount of time I've spent on this and the results, or the lack of, that I came with. Oh, and most of the code above is from the forums. I think I understand the general idea, but, as they say: easy to learn, hard to master.
Thanks a lot! | https://www.daniweb.com/programming/software-development/threads/398659/how-to-read-info-from-a-text-file-to-be-used-later | CC-MAIN-2020-24 | refinedweb | 396 | 82.24 |
IoT Push Notifications: Arduino, Firebase, and Android
IoT Push Notifications: Arduino, Firebase, and Android
This quick and easy tutorial will show you how to implement push notifications for IoT apps.
Join the DZone community and get the full member experience.Join For Free
This tutorial describes how to implement IoT push notifications. Using IoT push notifications, we can send notifications to other devices. In this case, we want to send IoT push notifications from a smart object (like an Arduino MKR1000) to a mobile smartphone (i.e. Android smartphone). This project integrates different eco-systems (IoT and Android) and can have several implementations. For example, we can send a push notification to our smartphone when an alert occurs:
- Gas leakage.
- Motion detection.
- Higher or lower temperature.
- General failure of systems.
As an example to show how to use IoT notifications, we will use a motion detection sensor. In other words, there is an Arduino MKR1000 connected to a sensor (PIR sensor). When the sensor triggers an event, then MKR1000 makes a call to a Firebase server using the Firebase API. The smart object sends an IoT push notification to an Android smartphone. We can use the same to send notifications to other devices, like iOS and so on.
The idea, that stands behind this project, is shown below:
As you can see, this project uses the Firebase API in a different way, mixing different worlds!
In the last article, we described how to use the Firebase API to create a push notification, and in this article, we want to expand it and integrate with Arduino.
Moreover, we have already seen in the last post how to create an Android app that handles push notification and how to configure it in the Firebase console. If you are new to Firebase, I suggest reading the previous post so that you have a clear idea how things work.
This project uses the app we developed in the previous post. You can download it if you want to test the project.
Arduino MKR1000 PIR Project. The sketch is very simple:); }
We have to read the signal on the input pin and check if it is 1. If it is 1, then we have detected a motion and we can send the notification.
MKR1000 Wi-Fi Connection
Before sending a notification, we have to connect Arduino MKR1000 to the Internet using Wi-Fi. We can slightly modify the code above and add the Wi-Fi connection:
#include <SPI.h> #include <WiFi101.h> int inputPin = 2; int pirState = LOW; char ssid[] = "Vodafone-xxxxx"; // your network SSID (name) char pass[] = "yyyyyyyy"; // your network password int status = WL_IDLE_STATUS; WiFiClient client; void setup() { pinMode(inputPin, INPUT); Serial.begin(9600); //: sending IoT push notification to a smartphone.
Sending IoT Push Notifications to:
- Authenticate our client.
- Create the message body in JSON.
- Send the message to a smartphone.
It is necessary to send some header HTTP parameters and a JSON message. The first thing is to set the Firebase host:
Host: fcm.googleapis.com
then, to authenticate our client we use a secret key, you get from Firebase console:
Authorization: key=AIzaSyC1mHfa_G89CDoNoq2zWhh1iL9---------
then we have to set the content type:
Content-Type: application/json
and finally we specify the HTTP method and the service we want to invoke:
POST /fcm/send HTTP/1.1
The body is in JSON format and is very simple:
{ "to":"your_phone_key", "notification": { "body": "test message", "title" : "Title" } }
That’s all!! We have to make this request using Arduino HTTP library: }} | https://dzone.com/articles/iot-push-notifications-arduino | CC-MAIN-2020-05 | refinedweb | 584 | 64.1 |
README
ld-reduxld-redux
A library to integrate launch darkly with react redux :clap:
Launch Darkly is a great tool for feature flagging and a/b testing. It has a fully capable client-side javascript sdk, so why this package?
If you use react redux and you want to store your feature flags as part of your redux state, this package will do that for you. It does the heavy lifting of:
- Fetching your flags from launch darkly.
- Storing it in your redux state.
- Camel casing your keys so you can use them in code with the dot operator. The keys by default are dash separated so you can't do this out of the box with the official sdk.
- Server Sent Event works as well so your app will respond live to feature flag changes without the users having to refresh the browser!
Breaking changes in v3.1Breaking changes in v3.1
ld-redux v3.1.* is NOT backwards compatible! The init method now accepts dispatch instead of store. Follow the quickstart example below to see this.
InstallationInstallation
yarn add ld-redux
QuickstartQuickstart
In your client bootstrap, initialise the launch darkly client by invoking the init method:
import createStore from '<your-project>/store'; import ldRedux from 'ld-redux'; // standard redux createStore const store = createStore(); // do this once ldRedux.init({ clientSideId: 'your-client-side-id', dispatch: store.dispatch, }); render( <Provider store={store}> <Router routes={routes} history={browserHistory}/> </Provider>, document.getElementById('reactDiv') );
Include ldReducer as one of the reducers in your app:
import { combineReducers } from 'redux'; import ldRedux from 'ld-redux'; import reducers from '<your-project>/reducers'; export default combineReducers({ ...reducers, LD: ldRedux.reducer(), // Note: the LD key can be anything you want });
Use the flag:
import React, {Component} from 'react'; import {connect} from 'react-redux'; const mapStateToProps = (state) => { const {featureFlagKey} = state.LD; // Note: the key LD must be the same as step 2. return { featureFlagKey, }; }; @connect(mapStateToProps) export default class Home extends Component { render() { return ( <div> { /* look ma, feature flag! */ this.props.featureFlagKey ? <div> <p>Welcome to feature toggling!</p> </div> : 'nothing' } </div> ); } }
APIAPI
init({clientSideId, dispatch, flags, useCamelCaseFlagKeys, user, subscribe, options})init({clientSideId, dispatch, flags, useCamelCaseFlagKeys, user, subscribe, options})
The init method accepts an object with the above properties.
clientSideId,
dispatch are mandatory.
The
flags property is optional. This is an object containing all the flags you want to use and subscribe to in your app.
If you don't specify this, ld-redux will subscribe to all flags in your ld environment.
// standard redux createStore const store = createStore(); const flags = { 'feature-flag-key': false }; // only subscribe to this one flag // do this once ldRedux.init({ clientSideId: 'your-client-side-id', dispatch: store.dispatch, flags, });
The
subscribe property is optional. This defaults to true which means by default you'll get automatic live updates
of flag changes from the server. You can turn this off and manually subscribe to flag changes through the ldClient
object if for some reason you don't want to get live updates.
The
user property is optional. You can initialise the sdk with a custom user by specifying one. This must be an object containing
at least a "key" property. If you don't specify a user object, ldRedux will create a default one that looks like this:
const defaultUser = { key: uuid.v4(), // random guid ip: ip.address(), custom: { browser: userAgentParser.getResult().browser.name, device } };
For more info on the user object, see here.
The
useCamelCaseFlagKeys property is optional. This defaults to true which means by default the flags that are stored
in redux will be camel cased. If this property is false, no transformation on the flag name will be done.
The
options property is optional. It can be used to pass in extra options such as Bootstrapping.
For example:
ldRedux.init({ clientSideId, dispatch, flags, options: { bootstrap: 'localStorage', } });
reducer()reducer()
This is ld-redux's reducer. You must include this reducer in your app as per step 2 above with any key of your choice. You then use this key to retrieve your flags from redux's state.
window.ldClientwindow.ldClient
Internally the ldRedux.init method above initialises the js sdk and stores the resultant ldClient object in window.ldClient. You can use this object to access the official sdk methods directly. For example, you can do things like:
// track goals window.ldClient.track('add to cart'); // change user context window.ldClient.identify({key: 'someUserId'});
For more info on changing user context, see the official documentation.
isLDReadyisLDReady
You no longer need to deal with
isLDReady. However if you need to, it is still available in the store. You can access it via
the LD state like so:
const mapStateToProps = (state) => { const {isLDReady} = state.LD; // Note: the key LD must be the same as step 2. return { isLDReady, }; };
This is useful to solve "flickering" issues above the fold on your front page caused by a flag transitioning from a default false value to true.
ExampleExample
Check the example for a fully working spa with react, redux and react-router. Remember to enter your client side sdk in the client bootstrap file before running the example! | https://www.skypack.dev/view/ld-redux | CC-MAIN-2022-05 | refinedweb | 851 | 58.69 |
Hacking mock: Mock.assert_api(...)
Mock is a great module to use in testing, I use it pretty much all the time. But one thing I have nerver felt great about is the syntax of it's
call_args (and
call_args_list): it is a 2-tuple of the positional arguments and the keyword arguments, e.g.
(('arg1', 'arg2'), {'kw1': None, 'kw2': None}). This does show you exactly how the mock object was called, but the problem I have is that it's more restrictive then the signature in python:
def func(foo, bar, baz=None): pass func(0, 1, 2) func(0, 1, baz=2) func(0, bar=1, baz=2) func(foo=0, bar=1, baz=2)
In this example all the calls to
func() are exactly the same from python's point of view. But they will all be different in mock's
call_args attribute. To me this means my test will be too tightly coupled to the exact implementation of the code under test. This made me wonder how it could be better.
Firstly I started out writing a function which would take the
call_args tuples and know the function signature. This obviously isn't very nice as you need a new function for each signature. But this lead me on to adding the
.assert_api() method to the mock object itself. I've been using this method for a while and am still not disappointed in it, so tought I should write about it. Here's how to use it:
mobj = mock.Mock(api='foo,bar,baz') do_stuff() mobj.assert_api(foo=0, bar=1, baz=2)
It seems to me this is a fairly good compromise to an extra method on the mock object (and attribute, not shown) and nice concise way of asserting if a function was called correctly.
There are a number of side effects, mainly due to my implementation. The major one is that it consumes
.call_args_list! This means each time you call
.assert_api() the first item disappears from
.call_args_list. Again, I like this as it allows me easily to check multiple calls by just doing multiple
.assert_api() calls.
Another side effect, of less importance, is a new attribute "
api" on the mock object, I can imagine people disliking that one. But it's never been in my way and means you can just assign to it instead of using the keyword argument when creating the mock. I find this handy in combination with patch decorators where the syntax to fine-tune the mock is rather heavy to my liking.
The last strange thing is
.assert_api_lazy(), which is just a horribly bad name. It ignores any arguments which are present in the call on the mock object, but where not passed in as part of the
api='...' parameter. It's effectively saying you only want to check a few of the arguments and don't care about the others.
Finally here is the code, for simplicity here implemented (and unchecked) as a subclass of
Mock:
class MyMock(Mock): def __init__(api=None, **kwargs): Mock.__init__(self, **kwargs) self.api = api def _assert_api_base(self, **kwargs): """Return call_kwargs dict for assert_api and assert_api_lazy WARNING, this consumes self.call-args_list """ if self.call_args_list: call_args, call_kwargs = self.call_args_list.pop(0) else: raise AssertionError('No call_args left over') call_args = list(call_args) if self.api is None: raise AssertionError('self.api is not initialised') for p in self.api.split(','): if call_args: call_kwargs[p] = call_args.pop(0) return call_kwargs def assert_api(self, **kwargs): """WARNING, this consumes self.call_args_list""" call_kwargs = self._assert_api_base(**kwargs) assert kwargs == call_kwargs, \ 'Expected: %s\nCalled with: %s' % (kwargs, call_kwargs) def assert_api_lazy(self, **kwargs): """WARNING, this consumes self.call_args_list""" call_kwargs = self._assert_api_base(**kwargs) for k in call_kwargs.copy().iterkeys(): if k not in kwargs: del call_kwargs[k] assert kwargs == call_kwargs, \ 'Expected: %s\nCalled with (truncated): %s' % (kwargs, call_kwargs)
I'd be interested in feedback! It's definitely not perfect, but I do like the syntax of
m=Mock(api='...'); ...; m.assert_api(...). One problem I can think of is that it won't deal gracefully with default arguments on the api yet, e..g.:
def func(foo, bar=42): pass func(foo, 42) func(foo)
These two calls are identical, but
.assert_api() won't see them as the same. This hasn't bothered me yet, which is why I haven't looked into it. But I guess it should be considered for a general-purpose implementation of this idea.
New comments are not allowed. | http://blog.devork.be/2010/04/hacking-mock-mockassertapi.html | CC-MAIN-2019-22 | refinedweb | 743 | 75.1 |
asn1_read_value man page
asn1_read_value — API function
Synopsis
#include <libtasn1.h>
int asn1_read_value(asn1_node root, const char * name, void * ivalue, int * len);
Arguments
- asn1_node root
pointer to a structure.
- const char * name
the name of the element inside a structure that you want to read.
- void * ivalue
vector that will contain the element's content, must be a pointer to memory cells already allocated (may be NULL).
- int * len
number of bytes of *value: value[0]..value[len-1]. Initialy holds the sizeof value.
Description
Returns the value of one element inside a structure. If an element is OPTIONAL and this returns ASN1_ELEMENT_NOT_FOUND, it means that this element wasn't present in the der encoding that created the structure. The first element of a SEQUENCE_OF or SET_OF is named "?1". The second one "?2" and so on. If the root provided is a node to specific sequence element, then the keyword "?CURRENT" is also acceptable and indicates the current sequence element of this node.
Note that there can be valid values with length zero. In these case this function will succeed and len will be zero. if value is returned, ASN1_ELEMENT_NOT_FOUND if name is not a valid element, ASN1_VALUE_NOT_FOUND if there isn't any value for the element selected, and ASN1_MEM_ERROR if The value vector isn't big enough to store the result, and in this case len will contain the number of bytes needed.: | https://www.mankier.com/3/asn1_read_value | CC-MAIN-2017-22 | refinedweb | 234 | 57.27 |
You understand the basics of domain-specific languages and now you're ready to begin creating and refining them for your projects. In this third article in his series Venkat Subramaniam shows you how to create both internal and external DSLs using Java code. He explains the difference between the two types of DSL and why Java is a better choice for creating one type than the other. He also introduces the various options for parsing external DSLs -- as plain text, as XML, or using an industrial-strength language recognition tool such as ANTLR or openArchitectureWare.
Using semicolons or a pair of parentheses in code is second nature to those of us who are accustomed to C-derived languages. Our pinkies place semicolons involuntarily, and our eyes easily gloss over them. In DSLs, however, the accumulation of parentheses and semicolons is just so much noise, having a negative affect on fluency.
One way to decrease the noise level in your DSLs is trade in your semicolons for dots (
.) and using method chaining. In addition to making your code more fluent, method chaining also helps with context, by removing the need to repeat an object reference. The JSON example in Part 2 of this series illustrates the value of method chaining. (See "Creating DSLs in Java, Part 2," Listing 9). You can also use the static import feature in Java 5 to eliminate object or class references. The EasyMock example in "Creating DSLs in Java, Part 2," Listing 5, illustrates this.
In this article we'll see what happens when we apply these techniques to create a fluent, context-aware interface using Java code. The first DSL we'll build is an internal DSL written using the Java language syntax.
Internal DSLs in Java
Let's assume you want to send out some emails. You need a class that will simply allow you to specify the from, to, subject, and message data. You don't want to bother about object state or even create objects. You can start out with a traditional Java API. Study the API first, then we'll refactor it for more fluency. (Only the interface is shown because the implementation details aren't relevant to the example.)
Listing 1. Mailer: A traditional Java API
package dsl.example; public class Mailer { public void from(String fromAddress) {} public void to(String toAddress) {} public void subject(String theSubject) {} public void message(String body) {} public void send() {} }
To use this class, you would write something like this:
Listing 2. Creating a new Mailer and sending mail
Mailer mailer = new Mailer(); mailer.from("build@example.com"); mailer.to("example@example.com"); mailer.subject("build notification"); mailer.message("some details about build status"); mailer.send();
A more fluent Mailer
So far there are still quite a few steps between you and sending mail. That may be fine for a programmer, but not for a DSL user. What can we do to make this API fluent, and more like a DSL?
First, each of the methods of
Mailer, except the
send() method, can return itself, so we can chain the calls, as shown in Listing 3.
Listing 3. Method chaining in the Mailer API
package dsl.example; public class Mailer { public Mailer from(String fromAddress) { return this; } public Mailer to(String toAddress) { return this; } public Mailer subject(String theSubject) { return this; } public Mailer message(String body) { return this; } public void send() {} }
You would use this modified version as shown in Listing 4.
Listing 4. Sending mail with a new Mailer
new Mailer() .from("build@example.com") .to("example@example.com") .subject("build notification") .message("some details about build status") .send();
That's a notch better; however, it would be nice to eliminate the use of
new. After all, as a user of this DSL your main interest is in sending out emails, not in creating objects. We want to eliminate as much verbosity from the DSL as possible.
Listing 5. Mailer DSL, third iteration
package dsl.example; public class Mailer { public static Mailer mail() { return new Mailer(); } public Mailer from(String fromAddress) { return this; } public Mailer to(String toAddress) { return this; } public Mailer subject(String theSubject) { return this; } public Mailer message(String body) { return this; } public void send() {} }
Here's how the above DSL works:
Listing 6. Mailer sends mail!
Mailer.mail() .from("build@example.com") .to("example@example.com") .subject("build notification") .message("some details about build status") .send();
If you're using Java 5, you can perform a static import of the
import static dsl.example.Mailer.mail;
Once you add the static import, you don't need the class reference to call the
Listing 7. Mailer: A fluent, context aware DSL
mail() .from("build@example.com") .to("example@example.com") .subject("build notification") .message("some details about build status") .send();
The three-times refactored DSL in Listing 7 shows exactly how much fluency you can realize using Java code today. You are stuck with the parentheses and the ending semicolon. You can go a lot further with dynamic languages like JRuby and Groovy -- and not (as you might think) because these languages are typeless or have relaxed typing. On the contrary, it is the relaxed syntax of these languages that makes them more fluent. The syntax of dynamic and more modern languages requires less ceremony. I'll show you what I mean by that in the final article in this series. | http://www.javaworld.com/article/2077891/scripting-jvm-languages/creating-dsls-in-java--part-3--internal-and-external-dsls.html | CC-MAIN-2014-15 | refinedweb | 900 | 55.34 |
face
Interview Tips - Java Interview Questions
Interview Tips Hi,
I am looking for a job in java/j2ee.plz give me interview tips. i mean topics which i should be strong and how to prepare. Looking for a job 3.5yrs experience
Create Human Face using Graphics
Create Human Face using Graphics
In this section, you will learn how to create human face using Graphics. A Graphics provides contexts that allow...;Java Applet Demo</h1>
<applet code=HumanFace.class width=500
Java Programming Tips, Articles and Notes
Java Programming Language simple tips to use Java effectively
This section is not very structured and discussing the random topics of the
Java Programming Language and which is useful in learning the Java Language.
Java Programming
Linux tutorials and tips
Linux is of the most advanced operating system. Linux is being used to host websites and web applications. Linux also provide support for Java and other programming language. Programmers from all the over the world is developing change the face, change the face
How to change the face
You have a chance to learn how to change the face
of the person to another face. It has very simple technique to make this
effect
How to make an angry face, make an angry face, angry face
How to make an angry face
We have this example to teach you a simple method to
make an angry face... as I have done here.
This an angry face.
Look here
Java program
Java program How to write for drawing a face in java
Java program
Java program How to write code in order to draw a face in java
How to make a Chimpanzee face.
How to make a Chimpanzee face.
I have tried here to make a chimpanzee fame... as given below.
Face: Select pen tool (P key) and "FDC3AA"
How to make a alien face mask, make a alien face mask, alien face mask
How to make a alien face mask
Use this example to make a alien face mask, which
is played by the children.
New File: Take a new file with any size.
Draw
java - Java Interview Questions
Friend,
Please visit the following links:
How to design a face of the lady.
Photoshop : How to design a face of the lady.
How to design a face of the lady.
....
Face: Now we have to make face, So select
pen tool (P key) and point your pen LOOPS - Java Beginners
JAVA LOOPS Hi
I need a Java program that can toss a coin over... static int face;
public static void flip(){
face = (int...;
if (face == HEADS){
faceName = "Heads";
countH
java - Java Beginners
links:
Thanks
Introduction to Dojo and Tips
Introduction to Dojo
and Tips
This tips is light towards people with some JavaScript... need to use some of the features found in dojo. In this tips, learn about
java programming problem - Java Beginners
/java/java-tips/data/strings/96string_examples/example_count.shtml
http.../java-tips/data/strings/96string_examples/example_countVowels.shtml
follow...java programming problem Hello..could you please tell me how can I
the ?Smile? button you get a smiling face. If you push the ?Sad? button you get a sad face.
The program must consist of three classes:
? FaceDriver :
o The driver class for the program. Its only task is to create a new Face object
Human face using applet programming - Applet
Human face using applet programming import java.applet.*;
import java.awt.*;
public class Chatterjee extends Applet
{
public void init... is rectangle change to arc on clicking...or it should turn into smilimg face
Human face using applet programming - Applet
Human face using applet programming import java.awt.*;
import java.applet.*;
public class HumanFace extends Applet{
private int mouseX, mouseY;
private boolean mouseclicked = false;
public void init(){
}
public void
java - Java Beginners
://
Thanks
RoseIndia Team...java Java always provides default constructor to ac lass is it true... constructor.If we don't create any constructor for a class java itself creates
How to make a blooming Face.
How to make a blooming Face.
This tutorial will teach to a simple way to give a blooming
face effect. It is an easy step by step guide to learn easily. I am sure that you can
JAVA NEED TO CREATE A PROJECT WHERE IN HAVE TO DEVELOPE A SITE
1> TAKE PICTURE FROM CAMERA AND FIX ON THE PORTAL
2> CHOOSE SPECKS AND FIX ON THE FACE PHOTO
THERE WOULD BE AROUND 12-15 SPECKS SO IN THE PORTAL
java project
java project i would like to get an idea of how to do a project by doing a project(hospital management) in java.so could you please provide me with tips,UML,source code,or links of already completed project with documentation
JAVAPRGM - Java Beginners
-project.shtml example program for java IDE.
Hi Friend,
Please visit the following links:
10 Tips for Writing Effective Articles
10 Tips for Writing Effective Articles
... be yourself convinced about what you are writing. Few tips that will help you... of a bonus with their paid services or products.
These few simple tips can help
java program - Java Beginners
java program I worte out this program that was supposed to simulate a die rolling and then the program printing out each roll, the program also printing the number of of times each face came up/the percentage of the times. I
All iPhone Tips and Tricks
All iPhone Tips and Tricks
If you are looking for some cool iPhone 3G tips n tricks... provide you the best, coolest and hottest iPhone tips, tweaks, secrets that you
problem with main - Java Beginners
*;
public class YellowFace extends JApplet
{
public static final int FACE_DIAMETER = 200;
public static final int X_FACE = 100;
public static final int Y_FACE = 50;
public static final int EYE_WIDTH = 10;
public static
LOOP PROGRAM - Java Beginners
a Java program that uses looping to toss a coin over and over until it comes up head...;
private static int face;
public static void flip(){
face = (int...;
if (face == HEADS){
faceName = "Heads";
countH
:
Design Patterns Training
themselves robust to face
the confronts in future needs. In order to achieve this target... or assessors more
effectively. Design pattern is a indispensable part of Java and J2ee
java code compling error - Java Beginners
java code compling error i have face below problem,when compiling the program?
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
please send how can i solve
Outsourcing Communication Tips,Useful Cultural Tips in Offshore Outsourcing,Communication and Culture Tips
Communication and Culture Tips in Offshore Outsourcing Relationships
Introduction
Many offshore outsourcing and other business arrangements run into difficulties due to communication problems. The trend is very prominent in both
java
java what is java
java - Java Beginners
java swings - JavaMail
/java-tips/GUI/layouts/90independent-managers.shtml swings Hi sir,i am doing a project on swings,i don't have any...://
http
IT Training in India
who would be able to make themselves robust to face the confronts in future...;
Our Corporate Training Courses
Core Java...
objects in a relational database using following common Java idiom
Java Exception - Handle Exceptions in Java
Java Exception - Handle Exceptions in
Java
What is Exception in Java? How to handle the Exceptions in Java programming
language. This section on exception interfaces implementation
java interfaces implementation hai
I have defined one inter face like Maths taking methods like add(), sub(), mul()in interface
I take different implementation classes for add() method and sub()and mul()
when i trying
Java Layout
Java Layout
In java a layout manager class implements the LayoutManager interface. It is used... Orientation Tips on Choosing a Layout Manager Third-Party Layout
Fleet Management Tips
People who are just entering into fleet business here are
some fleet management tips that can help your company sustain in the competition
and at the same... for the servicing of vehicle.
Following these fleet management tips can help a fleet
owner
Java
Java how to draw class diagrams in java
java
java explain object oriented concept in java
Java
Java Whether Java is Programming Language or it is SOftware
java
java what are JAVA applications development tools
java
java why to set classpath in java
java
java give a simple example for inheritance in java
java
java Does java allows multiline comments
java
java What is ?static? keyword
java
java write a java program using filenotfoundexception
java
java difference between class and interface
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/82256 | CC-MAIN-2015-22 | refinedweb | 1,426 | 61.87 |
With Andreas plugging away at reStructuredText Integration into Zope, I'm thinking of some extra deliverables. I'm not sure how deep we want to put ReST support in at the moment, considering that while the spec is pretty solid the codebase is still a moving target, but I would like to add and help work on the following proposed deliverables to the project:
1. reStructuredText support in the Zope Help System.
2. reStructuredText support for Product README handling.
3. Ensuring that Page Templates and Python Scripts can access the
reStructuredText.HTML() function.
#1 looks like it would require adding a ReSTHelpTopic class in the
HelpSys package which could probably mimic (or even sublass) the
HelpSys.HelpTopic.STXTopic class. Then support would have to be added
into ``ProductContext.registerHelp()`` to map certain file suffixes to
the ReSTHelpTopic ('.rst', etc).
#2 could probably be handled the same way (look for a 'README.rst'
file), but may be served better if the contents of the README.txt could
be introspected enough to detect format. :\
#3 is easy, I just want to make sure it's not forgotten. We just have
to decide the right one way to do it: expose it in
'Products.PythonScripts.standard' where all of the other DTML
formatters are exposed, or out of its own namespace (ie:
tal:content="structure python:modules['reStructuredText'].HTML(foo)").
Or both ways.
--
Jeffrey P Shell
_______________________________________________
Zope-Dev maillist - [EMAIL PROTECTED]
** No cross posts or HTML encoding! **
(Related lists - )
[Zope-dev] Proposed Additional reStructuredText Deliverables
Jeffrey P Shell Mon, 11 Nov 2002 21:31:34 -0800
- Re: [Zope-dev] Proposed Additional reStructuredText Delive... Jeffrey P Shell
- Re: [Zope-dev] Proposed Additional reStructuredText D... Andreas Jung
- Re: [Zope-dev] Proposed Additional reStructuredTe... Jeffrey P Shell | https://www.mail-archive.com/zope-dev@zope.org/msg11911.html | CC-MAIN-2016-44 | refinedweb | 292 | 57.87 |
Inside a framework - How the Cycle.js DOM driver works
Jan van Brügge
・9 min read
Often, we use a framework without really knowing how it works internally. Sometimes we contribute to that framework without having any clue about the inner workings.
For me, this was the case with Cycle.js. I was even invited to be a Core Team Member without having any clue how the DOM part of it worked besides "it uses virtual DOM under the hood".
Lately I stumbled across severe issues in the DOM driver that (together with older issues) convinced me to deep dive into it and rewrite it basicly from scratch.
In this article I want to show you the main algorithm and the data structures that make the DOM driver efficient, but still easy to use.
The main problem - isolation
A Cycle.js component is just a pure function from some inputs (the sources) to some outputs (the sinks). This looks like this:
function Counter(sources) { const increment$ = sources.DOM.select('.increment') .events('click').mapTo(+1); // On every click on the .increment // button emit a 1 const decrement$ = sources.DOM.select('.decrement') .events('click').mapTo(-1); // Same but with -1 const state$ = xs.merge(increment$, decrement$) .fold((last, curr) => last + curr, 0) // Starting with 0, add up all // numbers on the stream const view$ = state$.map(count => div([ span(['Count: ' + count]), button('.increment'), button('.decrement') ])); return { DOM: view$ }; }
But if you call that function twice:
function main(sources) { const sink1 = Counter(sources); const sink2 = Counter(sources); const view$ = xs.combine(sink1.DOM, sink2.DOM) .map(children => div(children)); return { DOM: view$ }; }
You get this:
Why? Because if you take a look at the DOM, you see that there are two elements with the
.increment class, so either one triggers the emission of events:
You can solve this issue by using
isolate() which scopes the events to their components:
function main(sources) { - const sink1 = Counter(sources); - const sink2 = Counter(sources); + const sink1 = isolate(Counter, 'counter1')(sources); + const sink2 = isolate(Counter, 'counter2')(sources); const view$ = xs.combine(sink1.DOM, sink2.DOM) .map(children => div(children)); return { DOM: view$ }; }
Building the bridge between APIs
The goal of us is to build the bridge between the declarative API of the DOM driver including isolation and the native DOM API of the browser.
For this we need to know how the browser processes events. When an event is emitted on an element it first runs through the capture phase. This means the event runs top down from the
<html> to the
<button> in our case, triggering the event listeners that specified
useCapture: true.
Then, the more well known bubbling phase. Now the event runs bottom up through the DOM tree, triggering all event listeners that were not triggered in the capture phase.
So for our isolation we want to stop the events from propagating outside of the current scope. Sadly we can't use
stopPropagation, because the capture phase always starts at the root of the DOM tree, not the root of our isolation scope.
We want the bubbling phase to look like this:
Implementing a custom event propagation algorithm
As we already said, we can't use the native event bubbling of the DOM. To make our live a bit easier, we will just attach an native event listener at the root of our cycle app, and use the bubbling to catch all events that happen in the DOM with just one listener (yes, there are events that do not bubble, but I will exclude them for sake of simplicity here).
This root event listener looks like this:
root.addEventListener('click', function(event) { const element = event.target; // do something });
We know the element where the event happened, but not in which isolation scope this element is, as the DOM does not know anything about isolation. This means we need a mapping from element to isolation scope.
But remember how I said before, the only thing I know about the DOM driver is, that it uses virtual DOM under the hood? How do we get the actual DOM nodes, and not the vnodes?
Hooking into the VDOM
Snabbdom, the virtual DOM implementation that Cycle.js uses, allows to create modules that can hook into the DOM node create/update/delete live cycle. A basic module looks like this:
const myModule = { create: function(emptyVnode, vnode) { // invoked whenever a new virtual node is created // the actual DOM element is under vnode.elm }, update: function(oldVnode, vnode) { // invoked whenever a virtual node is updated }, delete: function(vnode) { // invoken whenever a DOM node is removed } };
So if we attach the isolation scope information to the vnode, we can use the
create hook to save the scope together with a reference to the DOM node.
Attaching the scope information
If we take a look at the
isolate() API again, we can see that it is a higher order function, so a function that takes a function as input and (in our case) returns a new function:
const isolatedComponentFunction = isolate(Component, scope);
If we imagine the inner workings of isolate and ignore all other drivers except DOM, it would look a bit like this:
function isolate(Component, scope) { return function IsolatedComponent(sources) { // Return isolated component const isolatedSource = sources.DOM.isolateSource(sources.DOM, scope); const sinks = Component({ ...sources, DOM: isolatedSource }); return { ...sinks, DOM: sources.DOM.isolateSink(sink.DOM, scope) }; } }
So we have two points of attack,
isolateSource and
isolateSink. Also, as you can see,
sources.DOM is an object, not a plain stream, so we can use it store information. We can use
isolateSink to add this stored information to the virtual dom nodes created by the user. This could look like this:
class DOMSource { constructor(namespace) { this.namespace = namespace; } isolateSource(source, scope) { return new DOMSource(this.namespace.concat({ type: 'total', scope })); } isolateSink(vnode$, scope) { return vnode$ .map(node => ({ ...node, data: { ...node.data, isolate: this.namespace.concat(scope) } })); } }
Now we can use a Snabbdom module to hook into the DOM creation and keep track of namespaces and elements:
class IsolateModule { constructor() { this.namespaceMap = new Map(); } createModule() { const self = this; return { create(empty, vnode) { if(vnode.data && vnode.data.isolate) { self.namespaceMap.set(vnode.elm, vnode.data.isolate); } }, delete(vnode) { self.namespaceMap.delete(vnode.elm); } }; } }
Using the information to distribute events
To get our desired API of
sources.DOM.events(eventType), we have to implement a function called
events on our DOM source. This function has to register its event type in a central place that we will call the event delegator. Why? Because that is where we will implement the custom event bubbling functionality. This register function has to return a stream of future events that the function can return to the user. We will also add a
select function that just adds a css selector to the namespace so element can be filtered for those later.
class DOMSource { constructor(eventDelegator, namespace) { this.namespace = namespace; this.eventDelegator = eventDelegator; } events(eventType) { return this.eventDelegator.registerListener(this.namespace, eventType); } select(selector) { return new DOMSource( this.eventDelegator, this.namespace.concat({ type: 'selector', scope: selector }) ); } isolateSource(source, scope) { /* ... */ } isolateSink(vnode$, scope) { /* ... */ } }
How can we implement
registerListener? How can we return a stream of events even if they have not happened yet? The answer to this question is a subject. A subject is like beginning of a conveyor belt. Its output is a stream of events, but you can put events onto the stream via function calls.
class EventDelegator { constructor(isolateModule) { this.isolateModule = isolateModule; } registerListener(namespace, eventType) { const subject = xs.create(); // our subject // TODO: save subject with namespace in some data structure return subject; } }
We want to save all listener subjects in a central data structure. This data structure should be able to give me a subject when I give it the namespace. Our first impulse would be to use a
Map again, but this is not possible due to the namespace being an array:
let test = new Map(); test.set([1,2,3], "test"); test.get([1,2,3]); // undefined
The problem is, that Javascript does not check if the arrays are equal but identical. This means, that this would work:
let test = new Map(); const arr = [1,2,3]; test.set(arr, "test"); test.get(arr); // "test"
So, we need a different data structure here.
Trees to the rescue
As our application is a tree of components, just as the DOM is a tree of nodes, our isolation scopes will also be like a tree, where each subtree shares the parent's namespace plus additionally has scopes of its own. So we can implement a tree that can carry an element at every node, plus has children that refer to scopes. See the type signatures for such a tree:
type Node = [Element | undefined, InternalTree]; interface InternalTree { [scope: string]: Node; }
As you can see, a
Node is an Element (or
undefined) and an object containing the scopes as keys and again Nodes as Values. As you can see, this is a recursive definition. To make it easier to grasp, here is an example drawing of one such tree:
The implementation details of this tree is not that important, but if you are interested you can see it on GitHub.
Finishing our listener registration
With this tree we can finally implement
registerListener.
class EventDelegator { constructor(isolateModule) { this.isolateModule = isolateModule; this.listenerTree = new SymbolTree(); } registerListener(_namespace, eventType) { let namespace = _namespace.filter(scope => scope.type !== 'selector'); let map = this.listenerTree.get(namespace); if(map && map.get(eventType)) { return map.get(eventType); } if(!map) { map = new Map(); this.listenerTree.insert(namespace, map); } const subject = xs.create(); // our subject const arr = map.get(eventType) || []; map.set(eventType, arr.concat({ namespace: _namespace, selector: _namespace.filter(scope => scope.type === 'selector').join(' '), subject }); return subject; } getListeners(namespace, eventType) { const map = this.listenerTree.get( namespace.filter(scope => scope.type !== 'selector'), ); return map ? map.get(eventType) : []; } }
Writing our own event bubbling
Now we have registered our listeners, but they are still not receiving any events. Time for us to write our own event bubbling implementation.
For this, let's recap where we start at the beginning of each event.
root.addEventListener('click', function(event) { const element = event.target; // do something });
With our current data structures we can expand this pice of code a bit:
root.addEventListener('click', function(event) { const element = event.target; const namespace = isolateModule.getNamespace(element); const namespaceRoot = isolateModule.getRootElement(namespace); const listeners = eventDelegator.listenerTree.get(namespace); //TODO: Capture phase, starting at root element, ending at element //TODO: Bubbling phase, starting at element, ending at root });
Ideally we would be able to get the bubbling path from the event, and in fact this might be the case in the future with the
event.path property, but at the moment we have to contruct the bubbling path ourselfs. Each element has a property
parentNode, so we can just start at the
element and work upwards to the
namespaceRoot.
let arr = []; let curr = element; while(curr && curr !== namespaceRoot) { arr.push(curr); curr = curr.parentNode; } arr.push(namespaceRoot); for(let i = arr.length - 1; i >= 0; i--) { // do bubble step }
Now we can walk through the array to simulate our bubbling. But this implementation has a big flaw: It allocates an array on every run. This array is not needed afterwards so it will be discarded and eventually garbage collected. If we use an event that happens frequently, like
mousemove, this could be a real performance bottleneck.
Recursion to the rescue
Instead of first remembering all elements and then iteration over them, we can also use recursion to walk up the DOM tree, but without allocating an array! For the capture phase, we want to first walk to the topmost element, and then on our way back down we want to execute our bubble logic. The trick is, to go into the recursive call first and then do the logic.
function bubble(elm, event) if(elm && elm !== namespaceRoot) { bubble(elm.parentNode, event); } // do bubble step }
As you can see, the recursive implementation is not only more performant, but also a lot easier to read. Implementing each bubble step is now fairly easy, we take the css selectors from the listener and check if the element matches this selector.
function doBubbleStep(elm, event) { for(let i = 0; i < listeners.length; i++) { if(elm.matches(listeners[i].selector)) { listeners[i].subject.shamefullySendNext(event); } } }
Conclusion
Implementing the DOM driver was a fun challenge. As part of a framework, you expect it to be performant but also easy to use. The implementation should not leak to the user and we have to work in the confines of the APIs we are given.
You can find the whole code of the new DOM driver on the GitHub PR.
If you have questions about the article or the implementation on GitHub, feel free to ask them! | https://dev.to/jvanbruegge/inside-a-framework---how-the-cyclejs-dom-driver-works-3deb | CC-MAIN-2019-43 | refinedweb | 2,131 | 56.55 |
Suppose we have two lowercase strings s and t, they are of the same length. We can select one character from s and another from t and swap them. We can do this operation any number of times we want. Finally, we have to check whether it's possible to make the two strings same or not.
So, if the input is like s = "abcd" t = "cdab", then the output will be True
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from collections import Counter def solve(s, t): fre = Counter(s+t) for cnt in fre.values(): if cnt % 2: return False return True s = "abcd" t = "cdab" print(solve(s, t))
"abcd", "cdab"
True | https://www.tutorialspoint.com/program-to-check-two-strings-can-be-equal-by-swapping-characters-or-not-in-python | CC-MAIN-2022-21 | refinedweb | 126 | 76.76 |
#include <SHMIOP_Acceptor.h>
#include <SHMIOP_Acceptor.h>
Inheritance diagram for TAO_SHMIOP_Acceptor:
0
Constructor.
Destructor.
[virtual]
Implements TAO_Acceptor.
[private]
Create a SHMIOP profile representing this acceptor.
Add the endpoints on this acceptor to a shared profile.
Implement the common part of the open*() methods.
[private, virtual]
Parse protocol specific options.
Set the MMAP options the MEM_Stream this acceptor creates will use.
[protected]
A local endpoint.
The concrete acceptor, as a pointer to it's base class.
Acceptor strategies.
Cache the information about the endpoint serviced by this acceptor.
Should we use GIOP lite??
Determine the prefix (include path name) of the mmap file.
Determine the minimum size of mmap file. This dictate the maximum size of a CORBA method invocation.
ORB Core.
The GIOP version for this endpoint. | https://www.dre.vanderbilt.edu/Doxygen/5.4.3/html/tao/strategies/classTAO__SHMIOP__Acceptor.html | CC-MAIN-2022-40 | refinedweb | 126 | 55.2 |
Hi guys,for anyone reason i decide to make a simple DLL and linking with another executable just for know how do this things.
So this is the code of DLL.
I know that this code is not according with MSDN especifications but it's work:
int somar(int x,int y){ return x + y; } int subtrair(int x,int y){ return x + y; } int mutiplicar(int x,int y){ return x + y; } int dividir(int x,int y){ return x / y; }
Then i wrote this simple code for test my dll.
#include <stdio.h> int main(int argc,char *argv){ printf("%d",soma(10,20)); return 1; }
If i use cl compiler from microsoft i get error that the symbol is not find if i compile with gcc i get the same.
The only way that i found to use this function from my dll is using LoadLibrary and GetProcAddress but i dont want this way.
Anyone can help me? | http://forum.codecall.net/topic/80251-linking-my-dll-with-executable-file/?forcePrint=1 | CC-MAIN-2019-43 | refinedweb | 161 | 64.04 |
Question:
How do I remove a namespace from a cluster? We have one namespace which has been allocated space on the disk and we are not using it. We want to use that data for other namespaces. Can removal of namespace be done dynamically without taking the whole cluster down?
namespace ns1 { memory-size 21474836480 replication-factor 2 allow-versions false single-bin false default-ttl 2592000 storage-engine device { device /dev/sdb load-at-startup true data-in-memory false write-block-size 131072 } }
Answer:
For server versions 3.13.0.1 (with updated clustering protocol) and above
Confirm that you have upgraded to the Paxos v5 clustering protocol. See [1] for reference.
Admin> show config like paxos-protocol ~~~~~~~~~~~~~~~~~~~~Service Configuration~~~~~~~~~~~~~~~~~~~~ NODE : 192.168.100.xxx:3000 192.168.100.yyy:3000 paxos-protocol: v5 v5
Removing (and adding) of a namespace can then be done by rolling restart of the Aerospike cluster nodes:
- Stop Aerospike service
sudo service aerospike stop
Update Aerospike configuration by removing (or adding if relevant) the appropriate namespace configuration in the
aerospike.conffile.
Start Aerospike service.
Repeat steps 1-3 on all nodes in the cluster keeping 5-10 second window between each nodes restarts to avoid any race condition on multiple nodes trying to join the cluster at the same time.
Workaround for server versions prior to 3.13.0.1
Unfortunately, there is no way to add or remove a namespace without taking the whole cluster down if you are running server versions prior to 3.13.0.1. We would recommend upgrading to a newer version [1]. However, to avoid downtime, you should be able to change the namespace to data-in-memory and do a rolling restart to claim the space taken by the namespace. You could also make sure the namespace will not be used further by blocking all write requests against it by setting both allow-xdr-writes and allow-nonxdr-writes to false:
Change the configuration of the namespace as such:
Recommended configuration change is as follows:
namespace ns1 { memory-size 1G allow-xdr-writes false allow-nonxdr-writes false storage-engine memory }
Perform a rolling restart on your cluster.
At a later time, when you can afford downtime, remove the above from all configs and do a full the cluster shutdown (stop all nodes, then restart all nodes).
Note:
[1] See here for upgrade instructions:
- Adding a new namespace - How do I add a new namespace?
- Adding a new
strong-consistencynamespace - How do I add a strong consistency namespace?
Timestamp
06/06/2017 | https://discuss.aerospike.com/t/remove-namespace-removing-namespace/723 | CC-MAIN-2019-09 | refinedweb | 427 | 51.38 |
ACPP(5) ACPP(5)
acpp - the ANSI C language preprocessor
The ANSI C language preprocessor, acpp, is invoked as the first pass of
any ANSI C compilation when the cc(1) command is issued with the -acpp or
-oldcpp option. Thus, acpp's output is designed to be in a form
acceptable as input to the next pass of the C compiler. The use of the
acpp command is not recommended, since the functionality of acpp has been
moved into the C front-end and acpp may not be supported in future
releases. See m4(1) for a general macro processor.
This preprocessor is a version of GNU cpp. To see which version, use
acpp -v. The source code to the preprocessor is distributed in 4Dgifts.
This is intended only as a general statement of the preprocessor's
capabilities. For a more precise statement, see the C language standard
(reference cited at the end of this manual page).
The following options are recognized directly by acpp:
-P Preprocess the input without producing the line control
information used by the next pass of the C compiler. The
compiler driver, cc defines appropriate symbols.
-Dname
-Dname=def
Define name with value def as if by a #define. If no =def is
given, name is defined with value 1. The -D option has lower
precedence than the -U option. That is, if the same name is used
in both a -U options and a -D option, the name will be undefined
regardless of the order of the options.
-Idir Change the algorithm for searching for #include files whose names
do not begin with / to look in dir before looking in the
directories on the standard list. Thus #include files whose
names are enclosed in "" will be searched for first in the
directory of the file with the #include line, then in the
directories named in -I options, and last in directories on a
standard list. For #include files whose names are enclosed in
<>, the directory of the file with the #include line is not
searched. If -I is given with no dir, acpp is instructed to
suppress the search of the standard list of include directories
(this form is obsolete, use -nostdinc instead)). This standard
list consists only of /usr/include.
-Uname undefines name, which is only useful if name is defined via -D or
is a predefined name. The order of the -D and -U options is not
significant: the undefines are done after all the -D's and
predefines are applied.
Page 1
ACPP(5) ACPP(5)
-pedantic
All ANSI constraints are obeyed when this is supplied. Howver,
only one #else, or #endif with extra tokens after the name is
reported per included file to reduce the number of error reports
on older header files.
-traditional
Allows dollar($) in identifiers and makes acpp behave like a
traditional C preprocessor as defined in The C Reference Manual.
-M The names of directly included files are printed on standard
output.
-C Comments are retained in the output of acpp.
-nostdinc
The standard places are not searched for include files. Use -I
to specify directories to search.
Ordinarily, only options mentioned on the cc(1) man page are of interest.
However acpp has the following options not recognized by cc which can be
applied with the cc flag prefix -Wp,. For example, to apply the
acpp-only option -Wall, use cc -Wp,-Wall.
-p All ANSI C constraints are obeyed. If supplied twice, #ident
preprocessing directives produce a warning. Any option starting
with -p is considered to mean -pedantic (see above).
-o out_fname
The output is written to out_fname instead of stdout.
-traditional
Allows dollar($) in identifiers and makes acpp behave like a
traditional C preprocessor as defined in Kernighan & Ritchie, First
Edition.
-trigraphs
Turns on processing of trigraphs.
-B Means there is a different, longer, list of default directories to
search. And C++ // is understood as a introducing a comment.
-+ Means there is a different, longer, list of default directories to
search. And C++ // is understood as a introducing a comment.
-Wtrigraphs
Warns if any trigraphs are encountered in the text.
Page 2
ACPP(5) ACPP(5)
-Wcomments
Warns if a comment start is found within a comment.
-Wcomment
Warns if a comment start is found within a comment.
-Wall
is the same as having both -Wtrigraphs and -Wcomments.
-M The names of directly included files are printed on standard output.
-MM The names of included files at all nesting levels are printed on
standard output.
-d Instead of writing the preprocessed file out, write the names and
values of all preprocessor macros defined.
-v prints the GNU CPP version number.
-C Comments are retained in the output of acpp.
-$ Dollar signs are allowed in identifiers.
-nosplice
Turn backslash newline into newline when outputting defines, but
don't consider them to end the macro definition.
-nostdinc
The standard places are not searched for include files. Use -I to
specify directories to search.
-u Inhibits predefinition of values. If not supplied, the names mips
and unix are predefined. cc -ansi passes -u to acpp.
-w Turns off warning messages.
-showdefines
Show each #define (#undef) followed by the line number and file name
where it is appears. The first few defines shown are the predefines
built-in to cpp and passed on the command line (for these the line
number and file name are meaningless). This facility is to assist
you in the special situation where you have a #define (#undef) and
you are having difficulty determining which source file the it is
in. Use any standard text tool to inspect the result file.
Example:
cc -ansi -E -Imyincludedir -Wp,-showdefines myfile.c >myresult
- As a file name, - is treated as a file name (stdin or stdout).
Page 3
ACPP(5) ACPP(5)
Some special names are understood by acpp. The name __LINE__ is defined
as the current line number (as a decimal integer) as known by acpp, and
__FILE__ is defined as the current file name (as a C string) as known by
acpp. The name __DATE__ is defined as the date of translation of the
source file (a character string literal of the form the names of the
months are the same as those generated by the asctime(3) function, and
the first character of dd is a space character if the value is less than
10). The name __TIME__ is defined as the time of translation of the
source file (a character string literal of the form generated by the
asctime(3) function). They can be used anywhere (including in macros)
just as any other defined name.
To distinguish itself from cpp(1), acpp defines the macro __ANSI_CPP__,
setting its value to one.
All acpp directive lines start with any number of blanks and tabs
followed by #. Any number of blanks and tabs are allowed between the #
and the directive. The directives are:
#define name token-string
Replace subsequent instances of name with token-string.
#define name( arg, ..., arg ) token-string
Notice that there can be no space between name and the (. Replace
subsequent instances of name followed by a (, a list of commaseparated
sets of tokens, and a ) followed, acpp re-starts its scan for names to expand at the
beginning of the newly created token-string. The # preprocessing
token turns the immediately following argument in token-string into
a string literal (i.e., enclosed in double quotes) which contains
the spelling of the argument (see the example below). The ##
preprocessing token causes the preceeding preprocessing token to be
concatenated with the following preprocessing token into a single
preprocessing token available for further replacement. Either or
both of the preprocessing tokens may be substituted macro arguments.
As an example of the # and ## operators, the sequence
#define quote(arg) # arg
#define glue_to_b(a) a ## b
quote(foo)
glue_to_b(b_follows_me)
creates the output
"foo"
b_follows_meb
Page 4
ACPP(5) ACPP(5)
#undef name
Cause the definition of name (if any) to be forgotten from now on.
No additional tokens are permitted on the directive line after name.
#ident "string"
The string and the directive are silently swallowed. No output is
produced for this directive.
#pragma
The directive and whatever follows it on the line is passed to the
output in a slightly modified form which is not documented. The
form may change in a future release.
#pragma once
If this directive appears in an included file, the file will never
be included again, even if there is another #include of this file.
No tokens or comments are permitted after the ``once'' keyword.
Using #pragma once is more efficient than using macro wrappers,
because the included file is not rescanned, but it may not be
portable to third-party preprocessors.
#include "filename"
#include <filename>
Include at this point the contents of filename (which will then be
run through acpp). When the <filename> notation is used, filename
is only searched for in the standard places. See the -I option
above for more detail. No additional tokens are permitted on the
directive line after the final " or >.
#line integer-constant filename
Causes acpp to generate line control information for the next pass
of the C compiler. Integer-constant is the line number of the next
line and filename is the file from which it comes. If "filename" is
not given, the current file name is unchanged. No additional tokens
are premitted on the directive line after the optional filename.
#endif
Ends a section of lines begun by a test directive (#if, #ifdef, or
#ifndef). Each test directive must have a matching #endif. No
additional tokens are permitted on the directive line. To reduce
the volume of error reports on older header files, acpp reports only
one instance of additional tokens per included file.
#ifdef name
The lines following will appear in the output if and only if name
has been the subject of a previous #define without being the subject
of an intervening #undef. No additional tokens are permitted on the
directive line after name.
Page 5
ACPP(5) ACPP(5)
#ifndef name
The lines following will appear in the output if and only if name
has not been the subject of a previous #define. No additional
tokens are permitted on the directive line after name.
#if constant-expression
Lines following will appear in the output if and only if the
constant-expression evaluates to non-zero. utility of #ifdef and #ifndef in a #if directive.
Only these operators, integer constants, and names which are known
by acpp should be used in constant-expression. In particular, the
sizeof operator is not available.
To test whether either of two symbols, foo and fum, are defined,
use:
#if defined(foo) || defined(fum)
#elif constant-expression
This is equivalent to a #else with a #if expression, and is often
more convenient than a nested #else #if constant-expression #endif
#endif.
#else
The lines following will appear in the output if and only if the
preceding test directive evaluates to zero. No additional tokens
are permitted on the directive line. To reduce the volume of error
reports on older header files, acpp reports only one instance of
additional tokens per included file.
The test directives and the possible #else directives can be nested.
#error preprocessing-tokens
The preprocessing tokens are emitted and an error is signaled to cc.
#ident
This System V directive is silently accepted and ignored unless
-pedantic is supplied twice, in which case a warning is issued for
each #ident encountered.
#sccs
This is a BSD-only directive. Use of it is an error.
standard directory list for #include files, /usr/include
Page 6
ACPP(5) ACPP(5)
Two often-used capabilities of the older C preprocessor cpp(1) have a
different syntax in acpp(5). These are enclosing a macro argument in
double-quotes, and concatenating tokens. See the discussion of #define
for the new syntax.
cc(1), line(1), m4(1), cpp(1)
American National Standard for Information Systems - Programming Language
- C, ANSI X3.159-1989.
PPPPaaaaggggeeee 7777 | http://nixdoc.net/man-pages/IRIX/man5/acpp.5.html | CC-MAIN-2018-05 | refinedweb | 2,003 | 55.54 |
I have created a Project having many activities. One activity is to record the video, that is working fine. I can see the recorded video in my specified folder without restart my tablet.
But when I try to find all the videos in that folder in some other activity using query, see code below. Then I can't see my recorded video until I restart my tablet. I can see just old recorded videos before starting my tablet. I couldn't understand this strange behavior.
Can anyone put some light on this issue??
Thanks.
private void initVideosId() { // getting the videos id in Video Folder of SD Card
try {
// Here we set up a string array of the thumbnail ID column we want
// to get back
String[] proj = { _ID };
//Querying for the videos in VideoGallery folder of SD card
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri, proj, // Which columns to return
MEDIA_DATA + " like ? ", // WHERE clause; which rows to
// return (all rows)
new String[] { "%VideoGallery%" }, //());
}
}
If you stored the file on external storage, you need to use
MediaScannerConnection to get the
MediaStore to index that file, such as:
MediaScannerConnection.scanFile( this, new String[] {file.getAbsolutePath()}, null, new OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { // do something if you want } }); | https://codedump.io/share/ViIcOwAzFR8L/1/recorded-video-is-not-visible-in-my-other-activity-untill-i-reboot-my-tablet-asus-transformer | CC-MAIN-2017-51 | refinedweb | 216 | 62.17 |
Object-Oriented Programming or OOP can be a tough concept to understand for beginners. And that’s mainly because it is not really explained in the right way in a lot of places. Normally a lot of books start by explaining OOP by talking about the three big terms — Encapsulation, Inheritance and Polymorphism. But the time the book can explain these topics, anyone who is just starting would already feel lost.
So, I thought of making the concept a little easier for fellow programmers, Data Scientists and Pythonistas. The way I intend to do is by removing all the Jargon and going through some examples. I would start by explaining classes and objects. Then I would explain why classes are important in various situations and how they solve some fundamental problems. In this way, the reader would also be able to understand the three big terms by the end of the post.
In this series of posts named **Python Shorts **, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work.
This post is about explaining OOP the laymen way.
Put simply, everything in Python is an object and classes are a blueprint of objects. So when we write:
a = 2 b = "Hello!"
We are creating an object a of class
int holding the value 2 And and object b of class
str holding the value “Hello!”. In a way, these two particular classes are provided to us by default when we use numbers or strings.
Apart from these a lot of us end up working with classes and objects without even realizing it. For example, you are actually using a class when you use any scikit Learn Model.
clf = RandomForestClassifier() clf.fit(X,y)
Here your classifier
clf is an object and fit is a method defined in the class
RandomForestClassifier
So, we use them a lot when we are working with Python. But why really. What is it with classes? I could do the same with functions?
Yes, you can. But classes really provide you with a lot of power compared to functions. To quote an example, the
str class has a lot of functions defined for the object which we can access just by pressing tab. One could also write all these functions, but that way, they would not be available to use just by pressing the tab button.
This property of classes is called encapsulation. From Wikipedia — encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object’s components.
So here the
str class bundles the data(“Hello!”) with all the methods that would operate on our data. I would explain the second part of that statement by the end of the post. In the same way, the
RandomForestClassifier class bundles all the classifier methods(
fit,
predict etc.)
Apart from this, Class usage can also help us to make the code much more modular and easy to maintain. So say we were to create a library like Scikit-Learn. We need to create many models, and each model will have a
fit and
predict method. If we don’t use classes, we will end up with a lot of functions for each of our different models like:
RFCFit RFCPredict SVCFit SVCPredict LRFit LRPredict and so on.
This sort of a code structure is just a nightmare to work with, and hence Scikit-Learn defines each of the models as a class having the
fit and
predict methods.
So, now we understand why to use classes and how they are so important, how do we really go about using them? So, creating a class is pretty simple. Below is a boilerplate code for any class you will end up writing:
class myClass: def __init__(self, a, b): self.a = a self.b = b def somefunc(self, arg1, arg2): #SOME CODE HERE
We see a lot of new keywords here. The main ones are
class,
__init__ and
self. So what are these? Again, it is easily explained by some example.
Suppose you are working at a bank that has many accounts. We can create a class named
Account that would be used to work with any account. For example, below I create an elementary toy class
Account which stores data for a user — namely
account_name and
balance. It also provides us with two methods to
deposit/
withdraw money to/from the bank account. Do read through it. It follows the same structure as the code above.
class Account: def __init__(self, account_name, balance=0): self.account_name = account_name self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self,amount): if amount <= self.balance: self.balance -= amount else: print("Cannot Withdraw amounts as no funds!!!")
We can create an account with a name Rahul and having an amount of 100 using:
myAccount = Account("Rahul",100)
We can access the data for this account using:
But, how are these attributes balance and account_name already set to 100, and “Rahul” respectively? We never did call the
__init__ method, so why did the object gets these attribute? The answer here is that
__init__ is a magic method(There are a lot of other magic methods which I would expand on in my next post on Magic Methods), which gets run whenever we create the object. So when we create myAccount , it automatically also runs the function
__init__
So now we understand
__init__, let us try to deposit some money into our account. We can do this by:
And our
balance rose to 200. But did you notice that our function deposit needed two arguments namely
self and
amount, yet we only provided one, and still, it works.
So, what is this
self? The way I like to explain
self is by calling the same function in an albeit different way. Below, I call the same function deposit belonging to the class account and provide it with the myAccount object and the amount. And now the function takes two arguments as it should.
And our
myAccount balance increases by 100 as expected. So it is the same function we have called. Now, that could only happen if
self and
myAccount are exactly the same object. When I call
myAccount.deposit(100) Python provides the same object myAccount to the function call as the argument self. And that is why
self.balance in the function definition really refers to
myAccount.balance.
We know how to create classes, but still, there is another important problem that I haven’t touched upon yet.
So, suppose you are working with Apple iPhone Division, and you have to create a different Class for each iPhone model. For this simple example, let us say that our iPhone’s first version currently does a single thing only — Makes a call and has some memory. We can write the class as:
class iPhone: def __init__(self, memory, user_id): self.memory = memory self.mobile_id = user_id def call(self, contactNum): # Some Implementation Here
Now, Apple plans to launch iPhone1 and this iPhone Model introduces a new functionality — The ability to take a pic. One way to do this is to copy-paste the above code and create a new class
iPhone1 like:
class iPhone1: def __init__(self, memory, user_id): self.memory = memory self.mobile_id = user_id self.pics = [] def call(self, contactNum): # Some Implementation Here def click_pic(self): # Some Implementation Here pic_taken = ... self.pics.append(pic_taken)
But as you can see that is a lot of unnecessary duplication of code and Python has a solution for removing that code duplication. One good way to write our
iPhone1 class is:
Class iPhone1(**iPhone**): def __init__(self,**memory,user_id**): **super().__init__(memory,user_id)** self.pics = [] def click_pic(self): # Some Implementation Here pic_taken = ... self.pics.append(pic_taken)
And that is the concept of inheritance. As per
Wikipedia
: Inheritance is the mechanism of basing an object or class upon another object or class retaining similar implementation. Simply put,
iPhone1 has access to all the variables and methods defined in class
iPhone now.
In this case, we don’t have to do any code duplication as we have inherited(taken) all the methods from our parent class
iPhone. Thus we don’t have to define the call function again. Also, we don’t set the mobile_id and memory in the
__init__ function using
super.
But what is this
super().__init__(memory,user_id)?
In real life, your
__init__ functions won’t be these nice two-line functions. You would need to define a lot of variables/attributes in your class and copying pasting them for the child class (here
iPhone1) becomes cumbersome. Thus there exists
super(). Here
super().__init__() actually calls the
__init__ method of the parent
iPhone Class here. So here when the
__init__ function of class
iPhone1 runs it automatically sets the
memory and
user_id of the class using the
__init__ function of the parent class.
Where do we see this in ML/DS/DL? Below is how we create a
PyTorch
model. This model inherits everything from the
nn.Module class and calls the
__init__ function of that class using the super call.
class myNeuralNet(nn.Module): def __init__(self): **super().__init__()** # Define all your Layers Here self.lin1 = nn.Linear(784, 30) self.lin2 = nn.Linear(30, 10) def forward(self, x): # Connect the layer Outputs here to define the forward pass x = self.lin1(x) x = self.lin2(x) return x
But what is Polymorphism? We are getting better at understanding how classes work so I guess I would try to explain Polymorphism now. Look at the below class.
import math class Shape: def __init__(self, name): self.name = name def area(self): pass def getName(self): return self.name class Rectangle(Shape): def __init__(self, name, length, breadth): super().__init__(name) self.length = length self.breadth = breadth def area(self): return self.length*self.breadth class Square(Rectangle): def __init__(self, name, side): super().__init__(name,side,side) class Circle(Shape): def __init__(self, name, radius): super().__init__(name) self.radius = radius def area(self): return pi*self.radius**2
Here we have our base class
Shape and the other derived classes —
Rectangle and
Circle. Also, see how we use multiple levels of inheritance in the
Square class which is derived from
Rectangle which in turn is derived from
Shape. Each of these classes has a function called
area which is defined as per the shape. So the concept that a function with the same name can do multiple things is made possible through Polymorphism in Python. In fact, that is the literal meaning of Polymorphism: “Something that takes many forms”. So here our function area takes multiple forms.
Another way that Polymorphism works with Python is with the
isinstance method. So using the above class, if we do:
Thus, the instance type of the object
mySquare is
Square,
Rectangle and
Shape. And hence the object is polymorphic. This has a lot of good properties. For example, We can create a function that works with an
Shape object, and it will totally work with any of the derived classes(
Square,
Circle,
Rectangle etc.) by making use of Polymorphism.
Why do we see function names or attribute names starting with Single and Double Underscores? Sometimes we want to make our attributes and functions in classes private and not allow the user to see them. This is a part of Encapsulation where we want to “restrict the direct access to some of an object’s components”. For instance, let’s say, we don’t want to allow the user to see the memory(RAM) of our iPhone once it is created. In such cases, we create an attribute using underscores in variable names.
So when we create the
iPhone Class in the below way, you won’t be able to access your phone
memory or the
privatefunc using Tab in your ipython notebooks because the attribute is made private now using
_.
But you would still be able to change the variable value using(Though not recommended),
You would also be able to use the method
_privatefunc using
myphone._privatefunc(). If you want to avoid that you can use double underscores in front of the variable name. For example, below the call to
print(myphone.__memory) throws an error. Also, you are not able to change the internal data of an object by using
myphone.__memory = 1.
But, as you see you can access and modify these
self.__memory values in your class definition in the function setMemory for instance.
I hope this has been useful for you to understand classes. There is still so much to classes that remain that I would cover in my next post on magic methods. Stay Tuned. Also, to summarize, in this post, we learned about OOP and creating classes along with the various fundamentals of OOP:
Encapsulation: Object contains all the data for itself.
Inheritance: We can create a class hierarchy where methods from parent classes pass on to child classes
Polymorphism: A function takes many forms, or the object might have multiple types.
To end this post, I would be giving an exercise for you to implement as I think it might clear some concepts for you. Create a class that lets you manage 3d objects(sphere and cube) with volumes and surface areas. The basic boilerplate code is given below:
import math class Shape3d: def __init__(self, name): self.name = name def surfaceArea(self): pass def volume(self): pass def getName(self): return self.name class Cuboid(): pass class Cube(): pass class Sphere(): pass
I will put the answer in the comments for this article.
If you want to learn more about Python , I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out. . | https://mlwhiz.com/blog/2020/11/24/object-oriented-programming/ | CC-MAIN-2021-25 | refinedweb | 2,325 | 65.52 |
Sencha
+ Post New Thread
Hello,
I think Component class would benefit for implementing HasEnabled interface (there'd be no API change, since Component already has...
In GXT 3.0.0-beta3, there appears to be a bug in TriggerFieldDefaultAppearance.render() if the value contains a single-quote. The problem is that the...
Grid column could not be sorted while a row with null value.
How could i do?
Could i add a custom comparator?
Hi,
I use two TextButtons (with previous/next functionality) with only an icon - no text.
I remark that as a user I'm unable to visually detect...
I'm pretty sure this was also happening before stretchmax broke in beta4.
Structure:
Hbox with a VBox of buttons in it. The Vbox sizes itself too...
Required Information
Version(s) of Ext GWT
Ext GWT 3.0 Release Candidate
Browser versions and OS
IE Version 8.0.7601.17514, Windows 7...
Hi
Attached the screenshot, checkbox near column name is not displayed in IE 7, but its showing correctly from IE8 version.,
Regards
Santhosh
This can be reproduced from the online demos
Go to a given cell and make a...
If I have a grid with an expander, the inline editor isn't working. It worked with beta3, but with beta4 or RC I get the following stack trace...
Within the class HttpProxy, the load method checks for a "Post" call. It should also be looking for "Put".
@Override
public void load(final C...
Test case:
I was filling app the grid with 600 rows. The first column is a RowNumberer.
The rendering got stuck for about 30 sec.
When removed...
Required Information
Version(s) of Ext GWT
«Ext GWT 3.0 Release Candidate 2»
Browser versions and OS
(and desktop environment, if... by:...
In most GUI toolkits I could try (Windows, Swing, Qt, GTK+...), except, I admit, SWT (strangely), the list / grid component has a quite uniform...
I think this issue smells like a bug.
package local.test.client;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;...
It looks like this fix introduced another problem:
These three Radio's are member of the same ToggleGroup.
When I nicely (left-)click the icons...
Version of Ext GWT
3.0 Release Candidate 2
Browser versions and OS
Internet Explorer 8, FF11, Chrome 18 running on Windows 7 Professional SP1
... | https://www.sencha.com/forum/forumdisplay.php?84-Sencha-GXT-Bugs/page49&order=desc | CC-MAIN-2015-48 | refinedweb | 393 | 69.99 |
Get the highlights in your inbox every week.
Introduction to Bash arrays
You don't know Bash: An introduction to Bash arrays
Enter the weird, wondrous world of Bash arrays.
Subscribe now
Although software engineers regularly use the command line for many aspects of development, arrays are likely one of the more obscure features of the command line (although not as obscure as the regex operator
=~). But obscurity and questionable syntax aside, Bash arrays can be very powerful.
Wait, but why?
Writing about Bash is challenging because it's remarkably easy for an article to devolve into a manual that focuses on syntax oddities. Rest assured, however, the intent of this article is to avoid having you RTFM.
A real (actually useful) example
To that end, let's consider a real-world scenario and how Bash can help: You are leading a new effort at your company to evaluate and optimize the runtime of your internal data pipeline. As a first step, you want to do a parameter sweep to evaluate how well the pipeline makes use of threads. For the sake of simplicity, we'll treat the pipeline as a compiled C++ black box where the only parameter we can tweak is the number of threads reserved for data processing:
./pipeline --threads 4.
The basicsThe first thing we'll do is define an array containing the values of the
--threadsparameter that we want to test:
allThreads=(1 2 4 8 16 32 64 128)
In this example, all the elements are numbers, but it need not be the case—arrays in Bash can contain both numbers and strings, e.g.,
myArray=(1 2 "three" 4 "five") is a valid expression. And just as with any other Bash variable, make sure to leave no spaces around the equal sign. Otherwise, Bash will treat the variable name as a program to execute, and the
= as its first parameter!
Now that we've initialized the array, let's retrieve a few of its elements. You'll notice that simply doing
echo $allThreads will output only the first element.
To understand why that is, let's take a step back and revisit how we usually output variables in Bash. Consider the following scenario:
type="article"
echo "Found 42 $type"
Say the variable
$type is given to us as a singular noun and we want to add an
s at the end of our sentence. We can't simply add an
s to
$type since that would turn it into a different variable,
$types. And although we could utilize code contortions such as
echo "Found 42 "$type"s", the best way to solve this problem is to use curly braces:
echo "Found 42 ${type}s", which allows us to tell Bash where the name of a variable starts and ends (interestingly, this is the same syntax used in JavaScript/ES6 to inject variables and expressions in template literals).
So as it turns out, although Bash variables don't generally require curly brackets, they are required for arrays. In turn, this allows us to specify the index to access, e.g.,
echo ${allThreads[1]} returns the second element of the array. Not including brackets, e.g.,
echo $allThreads[1], leads Bash to treat
[1] as a string and output it as such.
Yes, Bash arrays have odd syntax, but at least they are zero-indexed, unlike some other languages (I'm looking at you,
R).
Looping through arrays
Although in the examples above we used integer indices in our arrays, let's consider two occasions when that won't be the case: First, if we wanted the
$i-th element of the array, where
$i is a variable containing the index of interest, we can retrieve that element using:
echo ${allThreads[$i]}. Second, to output all the elements of an array, we replace the numeric index with the
@ symbol (you can think of
@ as standing for
all):
echo ${allThreads[@]}.
Looping through array elements
With that in mind, let's loop through
$allThreads and launch the pipeline for each value of
--threads:
for t in ${allThreads[@]}; do
./pipeline --threads $t
done
Looping through array indices
Next, let's consider a slightly different approach. Rather than looping over array elements, we can loop over array indices:
for i in ${!allThreads[@]}; do
./pipeline --threads ${allThreads[$i]}
done
Let's break that down: As we saw above,
${allThreads[@]} represents all the elements in our array. Adding an exclamation mark to make it
${!allThreads[@]} will return the list of all array indices (in our case 0 to 7). In other words, the
for loop is looping through all indices
$i and reading the
$i-th element from
$allThreads to set the value of the
--threads parameter.
This is much harsher on the eyes, so you may be wondering why I bother introducing it in the first place. That's because there are times where you need to know both the index and the value within a loop, e.g., if you want to ignore the first element of an array, using indices saves you from creating an additional variable that you then increment inside the loop.
Populating arrays.
Some useful syntax
But before diving into the code, we need to introduce some more syntax. First, we need to be able to retrieve the output of a Bash command. To do so, use the following syntax:
output=$( ./my_script.sh ), which will store the output of our commands into the variable
$output.
The second bit of syntax we need is how to append the value we just retrieved to an array. The syntax to do that will look familiar:
myArray+=( "newElement1" "newElement2" )
The parameter sweep
Putting everything together, here is our script for launching our parameter sweep:
allThreads=(1 2 4 8 16 32 64 128)
allRuntimes=()
for t in ${allThreads[@]}; do
runtime=$(./pipeline --threads $t)
allRuntimes+=( $runtime )
done
And voilà!
What else you got?
In this article, we covered the scenario of using arrays for parameter sweeps. But I promise there are more reasons to use Bash arrays—here are two more examples.
Log alerting
In this scenario, your app is divided into modules, each with its own log file. We can write a cron job script to email the right person when there are signs of trouble in certain modules:
# List of logs and who should be notified of issues
logPaths=("api.log" "auth.log" "jenkins.log" "data.log")
logEmails=("jay@email" "emma@email" "jon@email" "sophia@email")
# Look for signs of trouble in each log
for i in ${!logPaths[@]};
do
log=${logPaths[$i]}
stakeholder=${logEmails[$i]}
numErrors=$( tail -n 100 "$log" | grep "ERROR" | wc -l )
# Warn stakeholders if recently saw > 5 errors
if [[ "$numErrors" -gt 5 ]];
then
echo "$emailBody" | mailx -s "$emailSubject" "$emailRecipient"
fi
done
API queries
Say you want to generate some analytics about which users comment the most on your Medium posts. Since we don't have direct database access, SQL is out of the question, but we can use APIs!
To avoid getting into a long discussion about API authentication and tokens, we'll instead use JSONPlaceholder, a public-facing API testing service, as our endpoint. Once we query each post and retrieve the emails of everyone who commented, we can append those emails to our results array:
endpoint=""
allEmails=()
# Query first 10 posts
for postId in {1..10};
do
# Make API call to fetch emails of this posts's commenters
response=$(curl "${endpoint}?postId=${postId}")
# Use jq to parse the JSON response into an array
allEmails+=( $( jq '.[].email' <<< "$response" ) )
done
Note here that I'm using the
jq tool to parse JSON from the command line..
But wait, there's more!
Since we covered quite a bit of array syntax in this article, here's a summary of what we covered, along with some more advanced tricks we did not cover:
One last thought
As we've discovered, Bash arrays sure have strange syntax, but I hope this article convinced you that they are extremely powerful. Once you get the hang of the syntax, you'll find yourself using Bash arrays quite often.
Bash or Python?
Which begs the question: When should you use Bash arrays instead of other scripting languages such as Python?
To me, it all boils down to dependencies—if you can solve the problem at hand using only calls to command-line tools, you might as well use Bash. But for times when your script is part of a larger Python project, you might as well use Python.
For example, we could have turned to Python to implement the parameter sweep, but we would have ended up just writing a wrapper around Bash:
import subprocess
all_threads = [1, 2, 4, 8, 16, 32, 64, 128]
all_runtimes = []
# Launch pipeline on each number of threads
for t in all_threads:
cmd = './pipeline --threads {}'.format(t)
# Use the subprocess module to fetch the return output
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
output = p.communicate()[0]
all_runtimes.append(output)
Since there's no getting around the command line in this example, using Bash directly is preferable.
Time for a shameless plug
This article is based on a talk I gave at OSCON, where I presented the live-coding workshop You Don't Know Bash. No slides, no clickers—just me and the audience typing away at the command line, exploring the wondrous world of Bash.
This article originally appeared on Medium and is republished with permission.
11 Comments, Register or Log in to post a comment.
Fabulous!
Not only did you cover a subject or problem well, but you also provided real life working examples for explaining to readers where a particular function/feature is useful! This is a tactic often overlooked by most writers or speakers. Not only this, but you also provided the data lacking bias towards Python!
Thanks Roger!
Thanks for the great article!
One minor correction is needed. Your description of the behavior of ${arr[@]:s:n} as "Retrieve elements at indices n to s+n" should be "Retrieve elements at indices s to s+(n-1)". Or maybe more clearly, "Retrieve n elements beginning at index s"
Good call, I'll make sure to fix that
I like the way you have used the real world examples to make things more clear. Comparison with Python, similarity with JavaScript, are a few good ways you have used to attract programmers to try out some under-used things like bash arrays (particularly when bash is now available on almost every os, including windows).
Thanks Subrat!
I have been using BASH arrays for 9 years now, since 2009. I wanted CLI menu-based tool to manipulate/login my wireless routers and I used arrays to load router records from flat-text file (I am not concerned of security issues, it is stored in root account). It reached 2900 lines of code but is very functional and I can ssh and use menu-based app.
There is another small bug in the text. Basically, the situation is similar to the difference between $* and "$@". If you evaluate arrays to get all elements with * symbol, then it's ok to write ${array[*]}. But in case of @ symbol, it always has to be used with double quotes such as "${array[@]}". It's not so critical until there are elements with space symbol, because then you'll lose a real value of a particular element.
Here is an example:
$ array1=(1 "two three" 4 five)
$ for i in ${array1[*]}; do echo ${i}; done
1
two
three
4
five
$ for i in ${array1[@]}; do echo ${i}; done
1
two
three
4
five
$ for i in "${array1[@]}"; do echo ${i}; done
1
two three
4
five
nice yes.. pl mention this output too.. just for the sake of it:
for i in "${array1[*]}"; do echo ${i}; done
1 two three 4 five
You use an example of type="article".
Recommendation: "help type" in a bash shell and note that this is a shell builtin, so it would be better to name the shell variable containing the word "article" something else.
I've posted a review here:
where I come down on the side of functions. I've been too long function advocate to do otherwise, but I do encourage folks to take advantage of adding arrays to their practice, and _then_ think about functions.
The article leads to my "Commonplace" book, largely devoted to the bash shell. Also, I've published "Shell Functions" on leanpub, but it's badly in need of revision. | https://opensource.com/article/18/5/you-dont-know-bash-intro-bash-arrays | CC-MAIN-2020-50 | refinedweb | 2,084 | 67.89 |
On 14/02/2018 13:53, Andy Shevchenko wrote:
On Tue, Feb 13, 2018 at 7:45 PM, John Garry <john.ga...@huawei.com> wrote:On some platforms (such as arm64-based hip06/hip07), access to legacy ISA/LPC devices through access IO space is required, similar to x86 platforms. As the I/O for these devices are not memory mapped like PCI/PCIE MMIO host bridges, they require special low-level device operations through some host to generate IO accesses, i.e. a non- transparent bridge.
AdvertisingThrough the logical PIO framework, hosts are able to register address ranges in the logical PIO space for IO accesses. For hosts which require a LLDD to generate the IO accesses, through the logical PIO framework the host also registers accessors as a backend to generate the physical bus transactions for IO space accesses (called indirect IO). When describing the indirect IO child device in APCI tables, the IO resource is the host-specific address for the child (generally a bus address). An example is as follows: Device (LPC0) { Name (_HID, "HISI0191") // HiSi LPC Name (_CRS, ResourceTemplate () { Memory32Fixed (ReadWrite, 0xa01b0000, 0x1000) }) } Device (LPC0.IPMI) { Name (_HID, "IPI0001") Name (LORS, ResourceTemplate() { QWordIO ( ResourceConsumer, MinNotFixed, // _MIF MaxNotFixed, // _MAF PosDecode, EntireRange, 0x0, // _GRA 0xe4, // _MIN 0x3fff, // _MAX 0x0, // _TRA 0x04, // _LEN , , BTIO ) }) Since the IO resource for the child is a host-specific address, special translation are required to retrieve the logical PIO address for that child. To overcome the problem of associating this logical PIO address with the child device, a scan handler is added to scan the ACPI namespace for known indirect IO hosts. This scan handler creates an MFD per child with the translated logical PIO address as it's IO resource, as a substitute for the normal platform device which ACPI would create during device enumeration.
Hi Andy,
+ unsigned long sys_port;+ :)Could do, being the same thing. Maybe people prefer -1UL as it saves having to figure out what ULONG_MAX is :)
+ return -EFAULT;+/*Shouldn't be a kernel-doc?
Right, I'll make it /**
+ * acpi_indirect_io_set_res - set the resources for a child device + * (MFD) of an "indirect IO" host.In that case this would be one line w/o period at the end.+ * );
***
+ count = acpi_dev_get_resources(adev, &resource_list, NULL, NULL); + if (count <= 0) { + dev_err(child, "failed to get resources\n"); + return count ? count : -EIO; + } + + resources = kcalloc(count, sizeof(*resources), GFP_KERNEL); + if (!resources) { + acpi_dev_free_resource_list(&resource_list); + return -ENOMEM; + } + count = 0; + list_for_each_entry(rentry, &resource_list, node) + resources[count++] = *rentry->res; + + acpi_dev_free_resource_list(&resource_list);It has similarities with acpi_create_platform_device(). I guess we can utilize existing code.
For sure, this particular segment is effectively same as part of acpi_create_platform_device():For sure, this particular segment is effectively same as part of acpi_create_platform_device():
struct platform_device *acpi_create_platform_device(struct acpi_device *adev,struct platform_device *acpi_create_platform_device(struct acpi_device *adev,
struct property_entry *properties) { struct platform_device *pdev = NULL; struct platform_device_info pdevinfo; struct resource_entry *rentry; struct list_head resource_list; struct resource *resources = NULL; int count; /* If the ACPI node already has a physical device attached, skip it. */ if (adev->physical_node_count) return NULL; if (!acpi_match_device_ids(adev, forbidden_id_list)) return ERR_PTR(-EINVAL); ***> INIT_LIST_HEAD(&resource_list); count = acpi_dev_get_resources(adev, &resource_list, NULL, NULL); if (count < 0) { return NULL; } else if (count > 0) { resources = kzalloc(count * sizeof(struct resource), GFP_KERNEL); if (!resources) { dev_err(&adev->dev, "No memory for resources\n"); acpi_dev_free_resource_list(&resource_list); return ERR_PTR(-ENOMEM); } count = 0; list_for_each_entry(rentry, &resource_list, node) acpi_platform_fill_resource(adev, rentry->res, &resources[count++]); acpi_dev_free_resource_list(&resource_list); } <**** memset(&pdevinfo, 0, sizeof(pdevinfo)); /* * If the ACPI node has a parent and that parent has a physical So is your idea to refactor this common segment into a helper function?
+ /*;Perhaps, ret = ... if (ret) break; } if (ret) { kfree(resources); dev_err(child, "translate IO range failed(%d)\n", ret); return ret; } *res = resources; *num_res = count; return 0;
seems fine
?+} + +/* + * acpi_indirect_io_setup - scan handler for "indirect IO" host. + * @adev: "indirect IO" host ACPI device pointer + *?Right, but I thought for arrays that we should use address of x rather than x itself,));Casting to void * is pointless. In both cases.
I rechecked this. The casting to void * was there to mask another issue which I've now fixed.I rechecked this. The casting to void * was there to mask another issue which I've now fixed.
+ mfd_cell->name = name; + mfd_cell->acpi_match = acpi_match; + + ret = acpi_indirect_io_set_res(&child->dev, &adev->dev, + &mfd_cell->resources, + &mfd_cell->num_resources); + if (ret) { + dev_err(&child->dev, "set resource failed (%d)\n", ret); + goto free_mfd_resources; + } + count++; + } + + pdev = acpi_create_platform_device(adev, NULL); + if (IS_ERR_OR_NULL(pdev)) { + dev_err(&adev->dev, "create platform device for host failed\n");+ ret = PTR_ERR(pdev);So, NULL case will return 0. Is it expected?
Should error in that case also, so I'll change.
+; + +free_mfd_resources: + while (cell_num--) + kfree(mfd_cells[cell_num].resources); + kfree(mfd_cells); +free_range: + kfree(range); + + return ret; +}One question, what a scope of use of this function? Is it ->probe() time? If it's so, can we use devm_* variants?
It is called from a scan handler, so prior to device probing.
Thanks, John | https://www.mail-archive.com/linux-kernel@vger.kernel.org/msg1609976.html | CC-MAIN-2018-09 | refinedweb | 815 | 53.1 |
Kubernetes: five steps to well-behaved apps
There.
But driving at highway speed means keeping your hands on the wheel and obeying the rules of the road. Kubernetes has its own rules, and applications that adhere to best practices with respect to certain key touch points are much less likely to wipe out and take a few neighboring lanes of traffic with them. In this post I am going to briefly discuss five important design features that will affect how well your application behaves when running on kubernetes: configuration, logging, signal handling, health checks, and resource limits. The treatment of each topic will be necessarily high level, but I will provide links to more detailed information where it will be useful.
Configure from env vars
Configuration is data required by a process at startup that varies between deployments. Config should be loaded from environment variables with sane defaults. There are a few reasons to follow this advice. Reading env vars with defaults is easy and a basic feature of every general-purpose language. It’s also portable and there are standard ways to initialize a container’s environment whether you’re running on kubernetes, Docker Engine, Docker Compose, etc. On kubernetes you can interpolate env var values into templates using a tool like helm, or load them from ConfigMaps or Secrets previously installed into the cluster. Lastly environment variables are observable, in the dashboard or from the command line, and
kubectl describe pods mypod is less work to type than
kubectl exec mypod -- cat /etc/myapp/config.py.
The kubernetes documentation has a good section on setting environment variables for a container. For background see the config topic in the Twelve-Factor App manifesto, and don’t miss Kelsey Hightower’s excellent hands-on explanation.
Log to stdout and stderr
Every server app produces a stream of log events which describe what it is doing, and sometimes what went wrong. A well-behaved kubernetes app writes these events to stdout and stderr, and does not concern itself with routing or managing log stream delivery. Logs written to the standard streams are observable on the console locally during development, and through the dashboard or command line when the container is running in the cluster. On Google Kubernetes Engine you can easily configure fluentd to capture log streams and deliver them to stackdriver for long-term storage, searching and analysis. A well-behaved kubernetes app should specifically not write to local log files. Doing so creates state in the container filesystem that has to be managed, either by mounting the log directory to a host volume so the data is persistent, or by running a shipper like rsyslog inside the container.
For more background see the logging topic in the Twelve-Factor App manifesto, and this overview of the logging architecture in kubernetes.
Handle SIGTERM
Pods in kubernetes get restarted for any number of reasons, including shuffling resources around or just running
kubectl delete pods mypod. When the system wants to kill a pod it first sends SIGTERM and then waits a set number of seconds before sending SIGKILL. This period is known as the termination grace period and is a property of the podSpec that can be overridden from the kubectl command line. If your process doesn’t implement a handler for SIGTERM then it will be SIGKILLed. Processes that are killed are immediately removed from etcd and the API, without waiting for the process to actually terminate on the node. Bottom line: if you have anything you need to do to ensure graceful shutdown then you need to implement a handler for SIGTERM.
There are two other things that are very important to keep in mind: the first may seem obvious and it is that if you have more than one container in a pod they will all be signaled on shutdown and you need to have the right strategy for each depending on what it is doing. The second is less obvious, and actually is a bit of a trap: only the process running as PID 1 in a container is going to be signaled. If you use the non-exec form of CMD in your Dockerfile, for example, then your thing is running as
/bin/sh -c thing and it isn’t PID 1 and won’t get signaled. Instead use the exec form
CMD ["/usr/local/bin/thing"] or use the exec form of ENTRYPOINT. For additional info see this good overview of pod termination in the kubernetes documentation.
Implement readiness and liveness probes
Kubernetes works best when it knows the health status of every container in the system. The kubelet needs this information in order to restart containers that have failed, and to keep service endpoints up to date. To determine the health of a container kubernetes relies on two signals: liveness and readiness. Liveness measures whether a container is running or not, and readiness measures whether a running container is able to accept traffic. Specific tests for liveness and readiness can be configured for a container object. There are several options from executing external commands to making tcp and http requests.
If you don’t define liveness and readiness probes for your containers then the system will rely on the default signal, which is whether the container’s PID 1 still exists. If that process terminates then the kubelet finds out about it from the container runtime (i.e. Docker) and schedules a restart. For almost all long-running applications of any complexity this default behavior is insufficient. Your container’s PID 1 could be up but stuck in a loop, or blocked on some other broken bit and unable to do its job. Note that you should always define both a liveness and readiness probe, though it is possible these probes may use the same test for some apps. See the kubernetes documentation for a good explanation of creating liveness and readiness probes.
Set resource limits
A big part of kubernetes’ job is scheduling pods to run on nodes. A node in a cluster is an environment with constrained resources: memory, cpu, and ephemeral storage all represent things that have to be shared by containers running on the node (host network ports too, but we won’t talk about them here). For each of these resource types kubernetes defines the concept of a request and a limit. A request tells the system how much of a particular resource a container uses normally, and is an input to scheduling. A limit specifies the maximum amount of the resource a container is allowed to use, and may cause the hosting pod to be evicted from a node under constrained conditions.
The benefit of setting requests for every container is to allow kubernetes to do a better job of fitting pods onto nodes. The benefit of setting limits is as an additional health check: containers will not have the ability to go off the rails and consume all of memory, cpu or storage, thus forcing the scheduler to start moving things around to find available resources. If you don’t define requests and limits your containers are subject to the defaults, which are under the control of your cluster administrator. Defaults can be set per namespace, making it possible to divide the total resources in a cluster between different teams or different applications. The kubernetes documentation contains an overview of configuring requests and limits, and the same for managing defaults starts here.
Twelve-Factor all the things
I’ll close by mentioning the Twelve-Factor App manifesto, which I linked to twice above. This document represents a set of design guidelines and patterns for implementing applications that are deployable, scalable, observable, and work well within cloud-native environments. If you’re intending to write applications to run on kubernetes you can’t go far wrong following the recommendations outlined in it. | https://medium.com/@betz.mark/kubernetes-five-steps-to-well-behaved-apps-a7cbeb99471a | CC-MAIN-2019-09 | refinedweb | 1,314 | 57.61 |
Ecto is an official Elixir project providing a database wrapper and integrated query language. With Ecto we’re able to create migrations, define schemas, insert and update records, and query them.
Table of Contents
Adapters
Ecto supports different databases through the use of adapters. A few examples of adapters are:
- PostgreSQL
- MySQL
- SQLite
For this lesson we’ll configure Ecto to use the PostgreSQL adapter.
Getting Started
Through the course of this lesson we’ll cover three parts to Ecto:
- The Repository — provides the interface to our database, including the connection
- Migrations — a mechanism to create, modify, and destroy database tables and indexes
- Schemas — specialized structs that represent database table entries
To start we’ll create an application with a supervision tree.
$ mix new friends --sup $ cd friends
Add the ecto and postgrex package dependencies to your
mix.exs file.
defp deps do [ {:ecto_sql, "~> 3.2"}, {:postgrex, "~> 0.15"} ] end
Fetch the dependencies using
$ mix deps.get
Creating a Repository
A repository in Ecto maps to a datastore such as our Postgres database. All communication to the database will be done using this repository.
Set up a repository by running:
$ mix ecto.gen.repo -r Friends.Repo
This will generate the configuration required in
config/config.exs to connect to a database including the adapter to use.
This is the configuration file for our
Friends application
config :friends, Friends.Repo, database: "friends_repo", username: "postgres", password: "", hostname: "localhost"
This configures how Ecto will connect to the database. You may need to configure your database to have a matching credentials.
It also creates a
Friends.Repo module inside
lib/friends/repo.ex
defmodule Friends.Repo do use Ecto.Repo, otp_app: :friends, adapter: Ecto.Adapters.Postgres end
We’ll use the
Friends.Repo module to query the database. We also tell this module to find its database configuration information in the
:friends Elixir application and we chose the
Ecto.Adapters.Postgres adapter.
Next, we’ll setup the
Friends.Repo as a supervisor within our application’s supervision tree in
lib/friends/application.ex.
This will start the Ecto process when our application starts.
def start(_type, _args) do # List all child processes to be supervised children = [ Friends.Repo, ] ...
After that we’ll need to add the following line to our
config/config.exs file:
config :friends, ecto_repos: [Friends.Repo]
This will allow our application to run ecto mix commands from the commandline.
We’re all done configuring the repository! We can now create the database inside of postgres with this command:
$ mix ecto.create
Ecto will use the information in the
config/config.exs file to determine how to connect to Postgres and what name to give the database.
If you receive any errors, make sure that the configuration information is correct and that your instance of postgres is running.
Migrations
To create and modify tables inside the postgres database Ecto provides us with migrations. Each migration describes a set of actions to be performed on our database, like which tables to create or update.
Since our database doesn’t have any tables yet, we’ll need to create a migration to add some.
The convention in Ecto is to pluralize our tables so for application we’ll need a
people table, so let’s start there with our migrations.
The best way to create migrations is the mix
ecto.gen.migration <name> task, so in our case let’s use:
$ mix ecto.gen.migration create_people
This will generate a new file in the
priv/repo/migrations folder containing timestamp in the filename.
If we navigate to our directory and open the migration we should see something like this:
defmodule Friends.Repo.Migrations.CreatePeople do use Ecto.Migration def change do end end
Let’s start by modifying the
change/0 function to create a new table
people with
name and
age:
defmodule Friends.Repo.Migrations.CreatePeople do use Ecto.Migration def change do create table(:people) do add :name, :string, null: false add :age, :integer, default: 0 end end end
You can see above we’ve also defined the column’s data type.
Additionally, we’ve included
null: false and
default: 0 as options.
Let’s jump to the shell and run our migration:
$ mix ecto.migrate
Schemas
Now that we’ve created our initial table we need to tell Ecto more about it, part of how we do that is through schemas. A schema is a module that defines mappings to the underlying database table’s fields.
While Ecto favors pluralize database table names, the schema is typically singular, so we’ll create a
Person schema to accompany our table.
Let’s create our new schema at
lib/friends/person.ex:
defmodule Friends.Person do use Ecto.Schema schema "people" do field :name, :string field :age, :integer, default: 0 end end
Here we can see that the
Friends.Person module tells Ecto that this schema relates to the
people table and that we have two columns:
name which is a string and
age, an integer with a default of
0.
Let’s take a peek at our schema by opening
iex -S mix and creating a new person:
iex> %Friends.Person{} %Friends.Person{age: 0, name: nil}
As expected we get a new
Person with the default value applied to
age.
Now let’s create a “real” person:
iex> person = %Friends.Person{name: "Tom", age: 11} %Friends.Person{age: 11, name: "Tom"}
Since schemas are just structs, we can interact with our data like we’re used to:
iex> person.name "Tom" iex> Map.get(person, :name) "Tom" iex> %{name: name} = person %Friends.Person{age: 11, name: "Tom"} iex> name "Tom"
Similarly, we can update our schemas just as we would any other map or struct in Elixir:
iex> %{person | age: 18} %Friends.Person{age: 18, name: "Tom"} iex> Map.put(person, :name, "Jerry") %Friends.Person{age: 18, name: "Jerry"}
In our next lesson on Changesets, we’ll look at how to validate our data changes and finally how to persist them to our database.
Caught a mistake or want to contribute to the lesson? Edit this page on GitHub! | https://elixirschool.com/en/lessons/ecto/basics/ | CC-MAIN-2021-25 | refinedweb | 1,019 | 58.69 |
service-bus-java-manage-with-claims-based-authorization
Getting Started with Servicebus - Service Bus With Claim Based Authorization - in Java
Azure Service Bus basic scenario sample. - Create namespace with a queue and a topic - Create 2 subscriptions for topic using different methods. - Create send authorization rule for queue. - Create send and listener authorization rule for Topic. - Get the keys from authorization rule to connect to queue. - Send a "Hello" message to queue using Data plan sdk for Service Bus. - Send a "Hello" message to topic using Data plan sdk for Service Bus. - Delete namespace
Running this Sample
To run this sample:
Set the environment variable
AZURE_AUTH_LOCATION with the full path for an auth file. See how to create an auth file.
git clone cd service-bus-java-manage-with-claims-based-authorization. | https://azure.microsoft.com/da-dk/resources/samples/service-bus-java-manage-with-claims-based-authorization/ | CC-MAIN-2018-17 | refinedweb | 132 | 51.04 |
5. Network - TCP sockets¶
The building block of most of the internet is the TCP socket. These sockets provide a reliable stream of bytes between the connected network devices. This part of the tutorial will show how to use TCP sockets in a few different cases.
5.1. Star Wars Asciimation¶.
5.2. HTTP GET request¶.
5.3. Simple HTTP server¶
The following code creates an simple HTTP server which serves a single webpage that contains a table with the state of all the GPIO pins:
import machine pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] () | http://docs.micropython.org/en/v1.9/esp8266/esp8266/tutorial/network_tcp.html | CC-MAIN-2022-05 | refinedweb | 106 | 74.08 |
The Mirroring config documentation on World should describe the network parts pretty well on a high level.
API wise, mirroring uses the same functions as the Export feature (found in the EPiServer.Core.Transfer namespace) to create an export package with your content. So to understand Mirroring under the bonnet, you need to examine Exporting.
There's a blog post describing a custom mirroring provider, which outlines some of the namespaces and events involved when mirroring.
There's also a blog post outlining some of the namespaces and events involved when exporting.
Not sure if that helps you along, but there you go.
Hello,
I've had a client request on how version 2.0 of mirroring works. I've found quite a few articles on how to set it up but I've not found anything that gives an overview of what it does under the bonnet. I'm not after anything too low level just a high level understanding on how it works and what it does.
Is anyone able to help?
Thanks in advance,
Mark | https://world.episerver.com/forum/legacy-forums/Episerver-CMS-6-R2/Thread-Container/2013/12/Mirroring-20-Information/ | CC-MAIN-2020-45 | refinedweb | 178 | 75.2 |
Dark and light themes(colors schemes) for React
I took both dark and light color themes from Notion and applied them to my React app. The goal was to create a universal color palette format to make colors easy when starting a new project. Let's see how it went.
Here's my productivity app after stealing Notion colors. It has a different style to Notion, but the colors still fit Increaser, and I would assume this color palette would work for other types of apps too.
export type ThemeName = "dark" | "light"
import { DefaultTheme } from "styled-components" import { HSLA } from "ui/colors/HSLA" import { generatePaleteCollorGetter } from "ui/colors/palette" const primaryLightness = 52 const backgroundHue = 0 const backgroundSaturation = 0 const backgroundLightness = 10 export const regularTextAlpha = 0.9 export const darkTheme: DefaultTheme = { name: "dark",( backgroundHue, backgroundSaturation, backgroundLightness + 3 ), background: new HSLA( backgroundHue, backgroundSaturation, backgroundLightness ), text: new HSLA(0, 0, 100, 0.81), textSupporting: new HSLA(0, 0, 61), textSupporting2: new HSLA(0, 0, 100, 0.44), textSupporting3: new HSLA(0, 0, 100, 0.28), backgroundGlass: new HSLA(0, 0, 100, 0.06), backgroundGlass2: new HSLA(0, 0, 100, 0.13), overlay: new HSLA(backgroundHue, backgroundSaturation, 1, 0.8), outlinedHover: new HSLA(0, 0, 16), white: new HSLA(0, 0, 100), getPaletteColor: generatePaleteCollorGetter(56, 52), }, shadows: { small: "rgb(15 15 15 / 20%) 0px 0px 0px 1px, rgb(15 15 15 / 20%) 0px 2px 4px", mediud: "rgb(15 15 15 / 10%) 0px 0px 0px 1px, rgb(15 15 15 / 20%) 0px 3px 6px, rgb(15 15 15 / 40%) 0px 9px 24px;", }, }
import { DefaultTheme } from "styled-components" import { HSLA } from "ui/colors/HSLA" import { generatePaleteCollorGetter } from "ui/colors/palette" const primaryLightness = 52 export const regularTextAlpha = 0.9 export const lightTheme: DefaultTheme = { name: "light",(60, 11, 98), background: new HSLA(0, 0, 100), text: new HSLA(60, 6, 20), textSupporting: new HSLA(45, 19, 8, 0.6), textSupporting2: new HSLA(45, 8, 20, 0.65), textSupporting3: new HSLA(45, 8, 81), backgroundGlass: new HSLA(45, 8, 20, 0.08), backgroundGlass2: new HSLA(45, 8, 20, 0.16), overlay: new HSLA(0, 0, 0, 0.4), outlinedHover: new HSLA(0, 0, 88), white: new HSLA(0, 0, 100), getPaletteColor: generatePaleteCollorGetter(52, 48), }, shadows: { small: "rgb(15 15 15 / 10%) 0px 0px 0px 1px, rgb(15 15 15 / 10%) 0px 2px 4px", mediud: "rgb(15 15 15 / 5%) 0px 0px 0px 1px, rgb(15 15 15 / 10%) 0px 3px 6px, rgb(15 15 15 / 20%) 0px 9px 24px", }, }
The theme structure has a name - it could be either dark or light. There could be a need for more shadows, but for now, let's have only two - a small one for cards and a medium for popover menus. Both themes have the same shadows, except the dark theme is more opaque. To make the theme universal, we use functional names like primary or secondary instead of purple or yellow. The only exception is the white color.
First, we have primary and attention colors with hover. Primary is the color we use for interactive elements, while attention is more of a call to action, for example, on the landing page. After that, we have a color for success and failure that are green and red. Background and foreground colors fill most of the app space. For example, here, we use the background color for the main page content and foreground for the sidebar.
Then we have four types of text. Every other color gets less prominent. Here we use the text color for the title of the page, the supporting color for inactive navigation items, the second supporting color for the title of the card, and the third supporting color for placeholders in inputs.
Two background colors will not be enough, especially for a dark theme. We also use two glass colors, where the second one is more opaque. Here we use the first color for interactive elements hovers and the second one for the radio group at the top. Then we have an overlay color to focus the user on the modal and the outlineHover for elements like these buttons.
I didn't take palette colors from Notion and instead used a function that generates a color from an index. I have a video in the description explaining this approach.
Usually, components don't need to know the theme name, except in a few situations like this card, which doesn't need to use foreground in the light theme.
import React from "react" import styled, { css } from "styled-components" import { defaultBorderRadiusCSS } from "ui/borderRadius" import { getCSSUnit } from "ui/utils/getCSSUnit" interface Props { width?: React.CSSProperties["width"] padding?: React.CSSProperties["padding"] } export const Card = styled.div<Props>` background: ${({ theme }) => theme.name === "light" ? theme.colors.background.toCssValue() : theme.colors.backgroundGlass.toCssValue()}; box-shadow: ${({ theme }) => theme.shadows.small}; ${defaultBorderRadiusCSS}; ${({ width }) => width && css` width: ${getCSSUnit(width)}; `} ${({ padding }) => css` padding: ${getCSSUnit(padding ?? 20)}; `} ` | https://radzion.com/blog/notion-colors/ | CC-MAIN-2022-40 | refinedweb | 810 | 54.32 |
How to Build a Self Executable Jar File
I’m always looking for ways to simplify the management of Java services. Recently, I’ve learned how to create a self-executing jar file without the need for an extra bash script. Having one file helps when you’re handing off your service to be deployed by opsy folks. Here’s how.
Create a main class. For this post, the ubiquitous Hello World:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
Create a manifest file which defines your main class:
$ echo Main-Class: HelloWorld > MANIFEST.MF
Next, compile your class(es):
javac HelloWorld.java
Assemble a jar file:
java -cvmf MANIFEST.MF hello.jar HelloWorld.class
Create a small bash script to execute the jar (
stub.sh):
#!/usr/bin/java -jar
You can optionally also include JAVA_OPTS in this bash script:
#!/usr/bin/java -Xms256m -Xmx512m -jar
Finally, munge the bash script and jar together into a new file:
cat stub.sh hello.jar > hello.sh
Make the file executable:
chmod +x hello.sh
Now you can execute the file:
./hello.sh | https://digitalsanctum.com/2012/11/18/how-to-build-a-self-executable-jar-file/ | CC-MAIN-2021-25 | refinedweb | 187 | 58.89 |
Opened 4 years ago
Closed 4 years ago
#12207 closed enhancement (fixed)
Add Tool to Render HVIFs to PNG
Description
As discussed on the HDS mailing list, this new tool is required for the HDS application server to be able to render HVIF files instead of have manually rendered PNG icons uploaded separately from the HVIFs. It has to be able to be executed on the linux platform. Andrew (me) is actively working on this.
Attachments (3)
Change History (12)
comment:1 by , 4 years ago
comment:2 by , 4 years ago
comment:3 by , 4 years ago
I'll clean up the coding style, if Andrew doesn't have the time / isn't familiar with it.
comment:4 by , 4 years ago
Hi @waddlesplash & @axeld. I am keen to follow those coding styles. I did run the python script and thought that it would have picked up on "most problems", but obviously there's more! I will take a look at those in the next couple of days and see if I can get it into line.
comment:5 by , 4 years ago
To point out the coding style issues:
- src/tools/Jamfile: The SubIncludes are sorted alphabetically.
- The '#include's in each group are sorted alphabetically.
- The preferred pointer/reference style is
FILE* streamover
FILE *stream.
- No space after cast operator.
if/
whileconditions should be
foo == <constant>rather than
<constant> == foo.
- When an
if/
elsestatement is only a single line (note: not just a single statement), the block braces should be omitted.
- The maximum number of character columns per line is 80 (tab stops at multiples of 4 columns). Anything longer should be wrapped.
- The
{of a function block should go on a new line (the
if,
for, etc. blocks are fine).
- Local variables:
- Should be lower camel case (aka dromedary case) instead of using underscores.
png_ptr,
info_ptrshould simply be named
pngand
info(or
pngInfo) respectively.
- If possible, variable definitions and initializations should be combined.
- The comments above functions should be converted to doxygen style comments. There's an example in the coding guidelines (search for "/*!")
- Mostly concerning
h2p_write_png(): Instead of nesting
ifs and
elses, the early-error-return style (
if (<error>) return ...;) is preferred for better readability. In C-style code that leads to duplication of deinitialization code. In this case it would be minimal, but if you like you can use RAII helpers -- namely
CObjectDeleter-- from AutoDeleter.h to avoid it altogether. Usage examples: destructor function returning void, destructor function returning non-void (explicit namespace denotation not necessary).
- The use of blank lines is a bit excessive. While their use is encouraged for separating groups of statements, blank lines at the beginning of blocks, after
case ...:lines, or within a sequence of
}s should be omitted.
comment:6 by , 4 years ago
Hello bonefish; thank you for taking the time to go through that patch. I've not used the "RAII" mechanism before so that was quite interesting. When you get a moment, could you please have a look at my updated patch and see if my usage is correct and if you can see any other anomalies. Regards.
comment:7 by , 4 years ago
comment:8 by , 4 years ago
@bonefish; It looks like those files are not HVIF. HVIF has a magic string of "ncif", but those files seem to have a leading 32 bit word of "IMSG". I've created a new patch so that the tool can sniff the file first and also fixed the infinite-looping issue too - thanks.
It doesn't follow our coding style at all, but I guess that's not entirely important for this tool. Otherwise, the patch looks good from a build system perspective (I have not tested the tool itself, though). | https://dev.haiku-os.org/ticket/12207 | CC-MAIN-2019-43 | refinedweb | 626 | 64.81 |
WSDL generation of types in different CLR namespaces
Discussion in 'ASP .Net Web Services' started by Henrik Gøttig, Oct 10, 2005.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
WSDL generation for UDDI question, Sep 23, 2005, in forum: ASP .Net
- Replies:
- 1
- Views:
- 558
WebServices and wsdl generation, Jul 28, 2005, in forum: Java
- Replies:
- 0
- Views:
- 650
Converting Project from 1.1 CLR to 2.0 CLRSenthilVel, Sep 7, 2006, in forum: ASP .Net
- Replies:
- 0
- Views:
- 432
- SenthilVel
- Sep 7, 2006
avoiding XML serialization, different WSDL generation, soap serializationRamunas Urbonas, Jul 20, 2004, in forum: ASP .Net Web Services
- Replies:
- 1
- Views:
- 424
- Dino Chiesa [Microsoft]
- Jul 27, 2004
HTML Generation (Next Generation CGI)John W. Long, Nov 22, 2003, in forum: Ruby
- Replies:
- 4
- Views:
- 395
- John W. Long
- Nov 24, 2003 | http://www.thecodingforums.com/threads/wsdl-generation-of-types-in-different-clr-namespaces.785418/ | CC-MAIN-2014-52 | refinedweb | 174 | 66.74 |
Test the element functions. More...
#include <functionTest.hh>
Test the element functions.
Test function evaluation of FE function at quadrature and non-quadrature points.
Test evaluation of particular shape functions at quadrature points.
Definition at line 31 of file functionTest.hh.
Definition at line 34 of file functionTest.hh.
Explicitly succeds a test.
Definition at line 109 of file testcase.hh.
Internal function to report a failed test (besides increasing the failed counter)
Internal function to do a numerical test.
Internal function to do a test.
Return shape function.
Returns number of failed tests.
Definition at line 102 of file testcase.hh.
Returns number of passed tests.
Definition at line 100 of file testcase.hh.
Returns output stream.
Definition at line 104 of file testcase.hh.
Test for 2D nodal space..
Definition at line 46 of file functionTest.hh.
Definition at line 48 of file functionTest.hh. | http://www.math.ethz.ch/~concepts/doxygen/html/classtest_1_1ElementFunctionTest.html | crawl-003 | refinedweb | 147 | 56.01 |
Creating an Angular NPM Service Library
Updated Version
There’s an updated version of this article here:
Creating an Angular NPM Installable Service Library
We need to publish a library to NPM for our peers. We will be using the Angular Package Format, which should be a good…
developer.fireflysemantics.com
Scenario
We need to publish a library to NPM for our peers.
Side Note
This should be a good way to package any NPM library as Angular supports all the popular package formats like FESM, UMD, etc. and does a good job of laying out your public API.
Approach
New Workspace
ng new my-workspace --create-application=false
cd my-workspace
New Library
ng generate library my-lib
Cleanup
Within
my-lib/src/lib remove everything except for:
my-lib.service.ts
This is the only file that should be in
public-api.ts :
/*
* Public API Surface of my-lib
*/export * from './lib/my-lib.service';
Test Application
ng generate application libtest
cd projects/libtest
Add the Library Service to Test Application
Note that this just works because of the workspace
tsconfig.json configuration :
"paths": {
"my-lib": [ "dist/my-lib"
]}
So our application can just import the service into
app.component.ts like this:
import { MyLibService } from 'my-lib';
Note though that if using VSCode then open up the entire workspace. This is such that the Tooling can see the
tsconfig.json file and thus the path to the library.
To test that our application starts, from the root workspace run:
ng serve -o
Build the Library
First switch off Ivy in
tsconfig.lib.json otherwise Angular will complain when attempting to publish to NPM:
"angularCompilerOptions": { ...
"enableIvy": false
}
How to compile a library without Ivy?
Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share…
stackoverflow.com
Then build the library:
ng build my-lib
Test NPM Publishing
Since this is just a test project we want to see what NPM would package for publishing, instead of actually publishing.
We can do this with:
cd dist/my-lib
npm pack
It will display what files are going to be uploaded and create a tar ball in the current directory.
We can also install this tarball into our test app like this (First we need to be in the workspace directory):
cd ../..
npm install my-lib
Look at the
package.json file and notice that the
my-lib library is now included via a file URL pointing at the tar ball:
"my-lib": "file:dist/my-lib/my-lib-0.0.1.tgz"
We can now develop our service further and when it’s ready to our first publish :
npm publish --access public | https://fireflysemantics.medium.com/creating-an-angular-9-npm-library-1a658ecfa3dc?source=post_internal_links---------5------------------------------- | CC-MAIN-2022-21 | refinedweb | 452 | 63.59 |
Class-based views
In Chapter 1 and at the start of
this chapter -- in listing 2-1 -- you saw how to define a Django
url and make it operate with a Django template without the need of
a view method. This was possible due to the
django.views.generic.TemplateView class, which is
called a class-based view.
Unlike Django view methods backed
by standard Python methods that use a Django
HttpRequest input parameter and output a Django
HttpResponse, class-based views offer their
functionality through full-fledged Python classes. This in turn
allows Django views to operate with object oriented programming
(OOP) principles (e.g. encapsulation, polymorphism and inheritance)
leading to greater re-usability and shorter implementation
times.
Although Django class-based views represent a more powerful approach to create Django views, they are simply an alternative to the view methods you've used up to this point. If you want to quickly execute business logic on Django requests you can keep using view methods, but for more demanding view requirements (e.g. form processing, boilerplate model queries) class-based views can save you considerable time.
Built-in class-based views
The functionality provided by the
django.views.generic.TemplateView class-based view is
real a time saver. While it would have been possible to configure a
url to execute on an empty view method and then send control to a
template, the
TemplateView class allows this process
to be done in one line.
In addition to the
TemplateView class-based view, Django offers many
other built-in class-based views to shorten the creation process
for common Django view operations using OOP-like principles. Table
2-11 illustrates Django's built-in classes for views.
Table 2-11. Built-in classes for views
In the upcoming and final section of this chapter, I'll explain the classes in the top-half of table 2-11 so you can gain a better understanding of the structure and execution process of Django class-based views. The class-based views in bottom half of table 2-11 that involve Django models are described in a separate chapter on Django class-based views models.
Class-based view structure & execution
To create a class-based view you need to create a class that inherits from one of the classes in table 2-11. Listing 2-37 shows a class-based view with this inheritance technique, as well as the corresponding url definition to execute a class-based view.
Listing 2-37 Class-based view inherited from TemplateView with url definition
---------------------------------------------------------------------------- # views.py from django.views.generic import TemplateView class AboutIndex(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): # **kwargs contains keyword context initialization values (if any) # Call base implementation to get a context context = super(AboutIndex, self).get_context_data(**kwargs) # Add context data to pass to template context['aboutdata'] = 'Custom data' return context ---------------------------------------------------------------------------- # urls.py from coffeehouse.about.views import AboutIndex from django.urls import path urlpatterns = [ path('about/index/',AboutIndex.as_view(),{'onsale':True}), ]
I chose to create a view that
inherits from
TemplateView first because of its
simplicity and because you already know the purpose of this class.
The example in listing 2-37 and the first example in this chapter
from listing 2-1 produce nearly identical outcomes.
The difference is, listing 2-1
declares a
TemplateView class instance directly as
part of the url (e.g.
TemplateView.as_view(template_name='index.html')) ),
where as listing 2-37 declares an instance of a
TemplateView sub-class named
AboutIndex.
Comparing the two approaches, you can get the initial feel for the
OOP behavior of class-based views.
The first part in listing 2-37
declares the
AboutIndex class-based view which
inherits its behavior from the
TemplateView class.
Notice the class declares the
template_name attribute
and the
get_context_data() method.
The
template_name
value in the
AboutIndex class acts as a default
template for the class-based view. But in OOP fashion, this same
value can be overridden by providing a value at instance creation
(e.g.
AboutIndex.as_view(template_name='other.html')
to use the
other.html template).
The
get_context_data
method in the
AboutIndex class allows you to add
context data to the class-view template. Notice the signature of
the
get_context_data method uses
**kwargs
to gain access to context initialization values (e.g. declared in
the url or parent class-views) and invokes a parent's class
get_context_data method using the Python
super() method per standard OOP Python practice. Next,
the
get_context_data method adds the additional
context data with the
aboutdata key and returns the
modified
context reference.
Tip See Appendix A - Methods arguments: Default, optional, *args & **kwargs for more details on the use of
**kwargsin Python.
In the second part of listing
2-37, you can see how the
AboutIndex class-based view
is first imported into a
urls.py file and then
hooked-up to a url definition. Notice how the class-based view is
declared on the
url definition using the
as_view() method. In addition, notice how the url
definition declares the url extra option
{'onsale':True} which gets passed as context data to
the class-based view (i.e. in the
**kwargs of the
get_context_data method).
Tip All class-based views use the
as_view()method to integrate into url definitions.
Now that you have a basic understanding of Django class-based views, listing 2-38 shows another class-based view with different implementation details.
Listing 2-38 Class-based view inherited from View with multiple HTTP handling
---------------------------------------------------------------------------- # views.py from django.views.generic import View from django.http import HttpResponse from django.shortcuts import render class ContactPage(View): mytemplate = 'contact.html' unsupported = 'Unsupported operation' def get(self, request): return render(request, self.mytemplate) def post(self, request): return HttpResponse(self.unsupported) ---------------------------------------------------------------------------- #urls.py from coffeehouse.contact.views import ContactPage urlpatterns = [ url(r'^contact/$',ContactPage.as_view()), ]
The first difference in listing
2-38 is the class-based view inherits its behavior from the general
purpose
django.views.generic.View class. As outlined
in table 2-11, the
View class provides the core
functionality for all class-based views. So in fact, the
TemplateView class used in listing 2-37 is a sub-class
of
View, meaning class-based views that use
TemplateView have access to the same functionalities
of class-based views that use
View.
The reason you would chose one class over another to implement class-based views is rooted in OOP polymorphism principles. For example, in OOP you can have a class hierarchy Drink→ Coffee → Latte, where a Drink class offers generic functionalities available to Drink, Coffee and Latte instances, a Coffee class offers more specific functionalities applicable to Coffee and Latter instances, and a Latte class offers the most specific functionalities applicable to only Latte instances.
Therefore if you know beforehand
you need a class-based view to relinquish control to a template
without applying elaborate business logic or custom request &
response handling, the
TemplateView class offers the
quickest path to a solution vs. the more generic
View
class. Expanding on this same principle, once you start working
with Django models and views, you'll come to realize some of the
more specialized class-based views in table 2-11 also offer quicker
solutions than creating a class-based view that inherits from the
general purpose
View class. Now that you know the
reason why you would chose a
View class-based view
over a more specialized class, lets break down the functionality in
listing 2-38.
Notice the class-based view
ContactPage declares two attributes:
mytemplate and
unsupported. These are
generic class attributes and I used the
mytemplate
name to illustrate there's no relation to the
template_name attribute used in listing 2-37 and
TemplateView class-based views. Class-based views
derived from a
TemplateView expect a
template_name value and automatically use this
template to generate a response. However, class-based views derived
from a
View class don't expect a specific template,
but instead expect you to implement how to generate a response,
which is where the
get and
post methods
in listing 2-38 come into play.
The
get method is
used to handle HTTP GET requests on the view, while the
post method is used to HTTP POST requests on the view.
This offers a much more modular approach to handle different HTTP
operations vs. standard view methods that require explicitly
inspecting a request and creating conditionals to handle different
HTTP operations. For the moment, don't worry about HTTP GET and
HTTP POST view handling, this is explored in greater detail in
Django forms where the topic is of greater relevance.
Next, notice both the
get and
post methods declare a
request input, which represents a Django
HttpRequest instance just like standard view methods.
In both cases, the methods immediately return a response, but it's
possible to inspect a request value or execute any business logic
before generating a response, just like it can be done in standard
view methods.
The
get method
generates a response with the
django.shortcuts.render
method and the
post method generates a response with
the
HttpResponse class, both of which are the same
techniques used to generate responses in standard view methods .
The only minor difference in listing 2-38 is both the
render method and
HttpResponse class use
instance attributes (e.g.
self.mytemplate,
self.unsupported) to generate the response, but other
than this, you're free to return a Django
HttpResponse
with any of the variations already explained in this chapter (e.g.
listing 2-24 response alternatives, table 2-6 shortcut
responses)
Finally, the last part in listing
2-38 shows how the
ContactPage class-based view is
imported into a
urls.py file and later hooked up to a
url using the
as_view() method.
To close out the discussion on
class-based views and this chapter, we come to the
django.views.generic.RedirectView class. Similar to
the
TemplateView class-based view which allows you to
quickly generate a response without a view method, the
RedirectView class-based view allows you to quickly
generate an HTTP redirect -- like the ones described in table 2-5
-- without the need of a view method.
The
RedirectView
class supports four attributes described in the following list:
permanent.- Defaults to
Falseto perform a non-permanent re-direct supported by the
HttpResponseRedirectclass described in table 2-5. If set to
True, a permanent re-direct is made with the
HttpResponsePermanentRedirectclass described in table 2-5.
url.- Defaults to
None. Defines a url value to perform the redirect.
pattern_name.- Defaults to
None. Defines a url name to generate a redirect url via the
reversemethod. Note the
reversemethod is explained in the url naming and namespace section earlier in this chapter.
query_string.- Default to
Falseto append a query string to a redirect url. If provided, the
query_stringvalue to the redirect url.
And with this we conclude our exploration into Django views and urls. In the next two chapters, you'll learn about Django templates and Jinja templates. | https://www.webforefront.com/django/classbasedviews.html | CC-MAIN-2021-31 | refinedweb | 1,838 | 53.92 |
Java2D the Groovy way
A small tutorial that will show you how to create eye-catching Java2D drawings without the hassle, thanks to one of Groovy's builders: GraphicsBuilder.
Introduction
Java2D has been available for years, ever since Swing came out, still
creating eye-catching and well-performant drawings is not an easy task
for anyone (unless you happen to be a frenchman that goes by the
nickname Gfx). That is precisely the problem GraphicsBuilder is aiming
to solve. In case you were living under a rock these past years (or
unplugged from the net) dynamic languages have taken center stage, one
of such languages is Groovy. Groovy is one of many languages that run
on the JVM, but what makes it stand over the others is it seamless
integration with the Java language and the Java platform itself.
Because Groovy is a dynamic language you may take advantage of optional typing, in other words, duck typing is a reality, thus reducing a significant amount of lines of code if you know what you are doing, but if you are still too attached to types, don't worry, Groovy is happy with types too. Another interesting bit about Groovy is that it has meta programming capabilities, meaning that you can extend the behavior of a class at runtime, even if it is a final class like java.lang.String (don't worry its safe). Due to these two facts and some other features Groovy allows the builder pattern to be implemented in a simple yet elegant way, and this is where GraphicsBuilder comes into play.
GraphicsBuilder is in a sense a collection of nodes, where each node represents a drawing operation like shapes, paints, transformations and images. A drawing is then composed from a group of operations put together by the builder in the order they where defined, taking into account that some operations accept nesting of others, thus enabling a nice structured hierarchy of operations. This may sound a little bit familiar coming from Swing, as every component is a link in the hierarchy chain. Java2D does all its magic with a Graphics (or Graphics2D) instance, which allows you to draw shapes, set colos and paints, clip the drawing surface to an specific shape or bounds and more; what GraphicsBuilder provides is a thin abstraction layer over those basic operations.
Let's get started, our goal is to draw the following image
Drawing the background
First step would be to draw the background, notice that it is a rectangle with rounded corners, which happens to be one of the basic shapes that Java2D provides. Let me show you the code for it
// define some useful variables
def width = 300
def height = width*3/4
def gb = new GraphicsBuilder()
// group all operations in the same set
def graphicsOperation = gb.group {
// translate the whole group to an arbitrary position
transformations { translate( x: 10, y: 10 ) }
// turn on antialiasing
antialias( 'on' )
// base background shape, it will be reused for clipping
rect( x: 0, y: 0, width: width, height: height, arcWidth: 40, arcHeight: 40,
asShape: true, id: 'background' )
// clip everything outside of the background shape
clip( background )
// draw the actual background
draw( background, borderColor: false ){
// a nice downward diagonal gradient from 'blue' to 'cyan'
gradientPaint( x1: 0, y1: 0, x2: 50, y2: 50,
color1: color('blue'), color2: color('cyan') )
}
}
A couple of things need to be explained here. First we define some useful variables for the image's width and height as they will be reused later, then we group all operations in the same set, making them easier to handle. A global transformation is applied to the whole group, so all nested operations will have an offset of 10 pixels in x-axis and 10 pixels on the y-axis. Antialias is turned on to get smooth edges, then the base shape of the background is created but is not drawn right away (thanks to asShape=true), this is because we will use that shape twice: firstly to clip the drawing area and secondly to draw the actual background. You may notice that the borderColor of the bakground shape has a value of false (it could have been 'none' too), that prevents the border to be drawn, as it may produce some undesired rendering artifacts as can be seen in the following images, the first one has borderColor=false and the second one has the default borderColor (usually black).
Drawing radial lines
On to the next step, drawing the radial lines. It is obvious that we would have to do some math with angles and radii as Java2D doesn't provide a quick shape or facility to do this kind of drawing out of the box, but don't worry GraphicsBuilder does. A rays shape requires a center (cx,cy) and a radius as minimum properties, but you can set others as the number of rays to be drawn (rays), the extent of the angle per ray (extent) and the starting angle (useful for quick rotations). Append the following code after the background draw operation
rays( cx: width/2, cy: height/2, radius: width*2, rays: 30, extent: 0.4, borderColor: false ){
colorPaint( color('black').derive(alpha:0.5) )
}
Which yields the following image
Notice that the final image has a hint of color change coming from the center, we will use a radial gradient to achieve that effect, which serves as an introduction to multipaints. As the name implies, multipaints are a collection of paints that can be applied at the same time to a single shape, in this case we would like a base color and a radial gradient applied to the rays. A radial gradient requires a center (cx,cy), a radius, and at least two stop definitions; a stop takes care of setting where in the gradient a color will be used. We update the rays shape with the following code
rays( cx: width/2, cy: height/2, radius: width*2, rays: 30, extent: 0.4, borderColor: false ){
multiPaint {
colorPaint( color('black').derive(alpha:0.5) )
radialGradient( cx: width/2, cy: height/2, radius: width/3 ){
stop( offset: 0, color: color('white').derive(alpha:0.5) )
stop( offset: 1, color: color('white').derive(alpha:0.0) )
transformations { translate( x: 10, y: 10 ) }
}
}
}
Which give us the following result
Drawing a star
Ah stars, saddly Java2D doesn't provide a base shape for them, wouldn't it be nice if GraphicsBuilder did? sure thing, it does! Stars have similar properties as rays, the only difference being how many points would you like and the inner and outer radii. The next code should do the trick
star( cx: width/2, cy: height/2, or: 30, ir: 15, borderColor: 'white' ){
basicStroke( width: 2 )
multiPaint {
colorPaint( color('white') )
radialGradient( cx: (width/2)+10, cy: (height/2)-10, radius: 50 ){
stop( offset: 0, color: color('cyan').derive(alpha:0.4) )
stop( offset: 1, color: color('gray').derive(alpha:0.0) )
transformations { translate( x: 10, y: 10 ) }
}
}
}
Multipaints are used again to paint a base white color and a cyan/gray based radial gradient, now on to the radial highlitghts of the star, we will use a rays shape again, with a longer extent and a radial gradient as paint. The highlights must be drawn before the star, effectively rendering them behind the star.
// star highlights
rays( cx: width/2, cy: height/2, radius: height*4/5, rays: 5, extent: 0.75,
angle: 45-(360/10*0.5), borderColor: false ){
radialGradient( cx: (width/2)+10, cy: (height/2)-10, radius: height/2 ){
stop( offset: 0, color: color('white').derive(alpha:0.5) )
stop( offset: 1, color: color('gray').derive(alpha:0.0) )
transformations { translate( x: 10, y: 10 ) }
}
}
Notice the extent of the rays is set to 0.75 (it ranges from 0 to 1) and that the angle has been changed too.
Drawing the text
We are in the final step, drawing the words "Groovy" and "Zone", they have nice gradients again and a white border. But there is a trick here, instead of setting a border width value, the white border is actually the same text drawn behind, this is because the font draws the whole outlines of the letters and we are only interested in the contour of the word. So let's draw the base text first
def fontFile = new File("WHOOPASS.TTF")
font( Font.createFont(Font.TRUETYPE_FONT,fontFile).deriveFont(58.0f) )
text( text: 'Groovy', x: (width/5)-5, y: height/10, borderColor: false ){
multiPaint {
colorPaint( color('blue') )
linearGradient( x2: 0, y2: 50 ){
stop( offset: 0, color: color('cyan').derive(alpha:0.3) )
stop( offset: 1, color: color('cyan').derive(alpha:0.8) )
}
}
}
text( text: 'Zone', x: (width/4)+10, y: height*7/10, borderColor: false ){
multiPaint {
colorPaint( color('blue') )
linearGradient( x2: 0, y2: 50 ){
stop( offset: 0, color: color('cyan').derive(alpha:0.8) )
stop( offset: 1, color: color('cyan').derive(alpha:0.3) )
}
}
}
Now to put the final touch, let's draw the white text before the blue one and we are done. Just insert the next snippet betwen the font definition and the first text operation
text( text: 'Groovy', x: (width/5)-5, y: (height/10), borderWidth: 6,
borderColor: 'white' )
text( text: 'Zone', x: (width/4)+10, y: height*7/10, borderWidth: 6,
borderColor: 'white')
And that's it! Feel free to play with colors and other shapes. GraphicsBuilder includes a basic application named GraphicsPad that will help you create your own drawings. Those drawings can be exported into standalone scripts, similar to the one used to create the pictures you see on this tutorial. GraphicsBuilder's doc site includes more information on the available shapes, paints, operations and other stuff you can do with GraphicsBuilder right now.
You'll find the complete script in the resources section, just remember to remove the .txt extension or load it up with GroovyConsole and run it.
I hope you enjoyed reading this tutorial as much as I did writing it. | http://groovy.dzone.com/articles/java2d-groovy-way | CC-MAIN-2014-10 | refinedweb | 1,661 | 55.17 |
- Casting int'** to 'const int * const * const' dosn't work, why?
- A non derivable class question
- hex code to binary code conversion for TINIm400kit
- Bypass Desktop screen and execute an MFC application on logon to Windows
- length of integer or numeric values
- tutorials related to dlls
- WHAT is image processing & how to do it using C
- how to do graphics in 32 bit environment
- how to do graphics in 32 bit environment
- factorial
- Access violation exception in VC 6. while running a tokenizer attempt using vector
- help: %*s in sprintf
- # Ergonomic Mobile Computing
- Market Your Business On Search Engines
- C++ compiler that uses CFront
- quick question about "++"
- format proof application
- Unusual warning
- Catching floating exceptions
- shared_ptr and operator=
- Why this de-referencing does not work?
- Fish Eye processing
- Archive Reading
- Gracefull termination of execution.
- What is this code doing?
- What is this code doing?
- Branch and Bound (NeedHelp)
- C++ - dynamically named structure instances
- Signalhandler and "-ansi -pedantic -Wall"
- CSV to C struct converter
- GCC Compiler Benchmark
- Progress in data processing
- Problem with wctomb...
- Size constraints in C++
- Deployment with Visual Studio 2005 C++
- memory allocation in unix
- question about class instantiation
- pblm in making dll using vc++
- Getting values from a combobox?
- Deriving from STL containers
- Floating-Point
- access to structure members
- how to multiply a string or repeat it
- Problem with gcc build - #including files
- Deriving from STL containers
- problems with system()
- callback confusion!
- Agent Framework
- finding uncommon elements from 2 array
- directly to an application after user login
- Trying to understand if and do/while
- Detecting a USB device
- More on the cosmetics (if-statements)
- can any bdy help me
- Linking static libraries from different MSVC compilers
- global variable declaration in header
- A good compiler please....
- ftp process using createprocess
- Header File (with' -' symbol)
- compiler treatment of const etc
- math
- HELP!! Two questions from <<the c programming language>>
- help for concatenation of string and object.
- I've read K&R, what now?
- jpeg image
- Check the contents of C exe
- error in c
- Dead Code elimination
- problem on medians
- problem on medians
- overloading assignment operator
- Time and date
- warning's meaning
- big Endian code reading problem
- Read ints from file, reverse the order in the array.
- begin() for empty STL container
- About shift one number more than 32.
- Online "flat" ISO C resource wanted.
- Is bitset class is not a STL container?
- do...while loop
- How do I run an exe file from a C++ windows application program?
- accessing physical memory mapped to a pci board
- How to instantiate a class by a string?
- compiler for vista
- Integrated debug library for a C program
- Embeding Images in streams
- Valgrind and STL
- Integrated debug library for a C program
- how can I replace a substring in a string
- Macro question
- Integrated debug library for a C program
- SEDA in C++
- new returning 0
- fstream
- Recruiting Advice
- What does "%" mean in C
- xml read
- image recognition
- Help with a compile problem
- Edit control tab / child windows / tabstop
- Multiply, and add matrix with memory allocation
- returning an array from a class via a method.
- PAM issue related to ix86 machin
- Path of file :filename variable
- manipulating functions
- far pointers...
- normalization of pointers...
- multi block macro
- preprocessor seems interfering namespace defines?
- All possible combinations for seqence
- ICU Unicode library
- "static" objects and functions
- inconsistent behavior with user-defined new and delete
- #include <util/ *.h> -> what's "util"?
- explicit keyword
- Problems with protected variables despite friends
- which one runs faster ??
- SICP playfulness in C?
- Having following errors error C2064: term does not evaluate to a function and C4291
- 2SAT in C
- Problem using CFront 3.03
- How to print in C/C++
- How to print in C
- correcting code for larger 2D arrays help
- How to print in C/C++
- [n00b alert] c question
- 2D array init with memset
- Writing a DOMTree back to a file
- Smart Indent in Visual Studio 2003
- unix internal
- Differences in C++ between struct and class
- C expects one expression ?
- how to replace a string by other string in a text file?
- how to add two no. of 100 digits or more?
- Pointer In C
- image accessing
- doubt on erasing the first element of a vector with reverse_iterator
- Problem with defining operator<< for std::ostream_iterator
- how to remove lines containing 'abc' in a text file?
- cstdlib and stdlib.h problem
- Anagrams
- How to extract words containing 'ab' & 'cd' in a text file?
- Greatest Common Divisor using Extended Euclid's Algorithm
- use of XML file
- Create dll with Turbo C
- small C compiler that will run on Vista
- Greatest Common Divisor using Extended Euclid's Algorithm
- Greatest Common Divisor using Extended Euclid's Algorithm
- SmartPointer & Inheritance & Explicit Constructors
- Compiler giving errors on iosfwd file.
- Looping with 2 dimensional arrays
- question about "++"
- Friend-Based Interfaces
- What's the advantage of using for_each loop?
- more homework help regarding flowcharts
- Read 2d Array from Text File-
- c programme without main() function
- Matlab to C/C++
- 128 bit math
- STL stable_sort sorting issue
- 128 bit math?
- read every other string from a text file
- read and write
- Is this legal? Aesthetically acceptable?
- Why doesn't nothrow work?
- Line break in preprocessor output
- screen scraping a Windows text box
- index operator[] overloading
- Makeup for if-statements?
- best methods to do C,C++ code optimization ?
- Changing the execution path of methods at runtime
- Address of vector question
- GTK+, segmentation fault in gtK-editable_get_chars
- struct / typedef confusion
- Read/Write file in c++
- what do c++/STL programmers do for time programming?
- Create shadow in shadow map with GLee
- UNICODE input for CGI using C
- string query
- obfuscation
- imapi staging image for record iz on CD WINxp
- Migration project from VC6 to VC8(2005)
- question on C language
- interface design in C / C++
- Problem with VS
- typeid(arg).name()
- outputting numbers in ascending order?
- accessing <select type=multiple> values in CGI through c
- initialization of a structure or what?
- disk based dictionary - IO efficiency
- Using Double pointer
- "Backtrace:" error
- equivalent of __leave in linux
- Priority Queues and Structures
- constructor syntax
- is_virtual_base<B, D> - possible?
- TreeCtrl
- Basic Programming
- Runtime error with C program running Cygwin
- for loop
- To recommend a site:
- To recommend a site
- problem of c++
- How to empty the variable buffer in recv() before accepting a string.
- How to empty the variable buffer in recv() before accepting string
- can anybody help me in Prims and kurskal's algorithm
- confused by boost::bind & boost::lambda::bind
- Decimal2binary conversion
- Design Patterns for LRU Cache in C++
- Using protected methods within a derived class?
- Templates and Subclasses C++ help
- Comparing Arrays
- Need reference for stringstream
- "c" is a really bad thread name
- extracting packet info using libipq C library
- converting String to a type name
- Looking for a C system call to copy files
- Looking for a C system call to copy files
- What is a Traits class
- Help needed in creation and order of algorithm.
- error: unqualified id expected question.
- how to limit digits after a decimal
- profiling C code an generating call graphs
- Using one vector to construct another
- C++ Linker Error
- shared_ptr and const
- Cross-compiling and linking 32-bit applications
- Accessing subclasses of objects stored in container class.
- Reallocate an array (pointers)
- Pointer to a Partially-Constructed Object
- Displaying stl map in .net dubugger
- How to link libxml when compiling?
- What is wrong? I can't add...
- Dynamic formula entering(Professionals Only)
- Boost bind confusion
- Is there is a C mail API ?
- Simple gtk+ app, seg fault
- non-virtual call to a virtual function using pointer to member
- Help with files in C - Delete data in C file
- binary files
- linker error in building DLL
- Suggest some starting porjects
- How to implement Matlab fir1 function in C?
- initializing static members of class
- Using destructor
- Indexing files of desktop
- Doubt in COM
- static class constant, declaration or definition?
- Looking for design patterns suggestions.
- Convert (call) VB .NET dll's from C++
- Need help on rogue wave template classes..
- mixing C and C++
- C++ Variables and File Handling
- How protect executable by resource editing?
- shared library disaster
- Extracting part of integer
- Declaring a non-void functions
- finding some problem plz help me
- Using C++ dll with C#
- Creation and manipulation of structures.
- C Term Project( structures, read files) Please Help
- problem here
- How do i Run programs
- overriding the dynamic library
- arrays
- insert RB tree
- cardgame point system
- This pointer question!
- Declaring an 8 bit variable in C
- graphics
- Can there be problems when a class is multiply inherited from 1000s of classes
- Print a string to console without using any print command.
- Alignment of struct members
- Microsoft Word in windows Console Application
- Microsoft Word in windows Console Application
- Segmentation Fault
- Open File
- Searching Files in directories
- some new questions for c
- some new questions for c
- some new questions for c
- icc compiler, object file problem
- Homework help.
- What are macros,virtual functions and what static means?
- what does this mean??
- Comparison between "Pointer and Integer"
- how to read fields of a struct from file
- operator precedence
- units hijnks
- Deleting constant char* created using c_str()
- parameterized translations strings;what is the solution?
- frustrating problem,help please!!!
- This pointer qustion!
- Error - function returns address of local variable
- The preprocessor is just a pass
- Converting pointers
- C compiler internals
- Memory error when I try to get list data from a text file in C
- what is piping in c++
- IO error reading variable in and printing it out.
- the function is not thread-safe? what does it means?
- help: define problem and meaning of {{{ and }}}.
- ANSI CODES
- Delete Anode
- fibonacci series
- terbo c++
- regarding lseek and fread
- pointers?
- lvalue?
- const and extern...
- Binary and C++
- simple constructor query
- why function isn't counting words
- static operator() in functor?
- Dumb STDLib Deprecation Question
- Looking for c++ coders
- How to make function body different depending on the template type? (MPL)
- simple template question
- copying from a file
- how to find the number of occurence of a substring in a string?
- console output - overwriting characters
- question on command line code
- MFC: execution flow not going through CMDIFrameWnd::OnRButtonUp()
- bits required
- casting operators - why doesn't this code work ?
- fuction to divide by three
- Can't start the cpp server in hpux
- counting of bits
- Queue implementation
- inheritance over template class
- Volatile?
- to print permutations...
- how can we use file in binary mode ?
- Looking for experienced C programmers to work in India
- Looking for experienced C / C++ programmers to work in India
- How to print "\n" or '\0'
- Pointers to standard library functions
- How to use nenoseconds in dealy function in C
- How to control I2C on Powerbook G4
- How to control I2C on Powerbook G4
- Reading numbers from a text file
- question
- Warning - comparison between pointer and integer on String
- Templates revisited: Best coding practice
- How to extract a string starting with 'abc' & ending with 'xyz' ?
- operator= inherited from template
- Does std::string do a shallow copy in copy construtor and assign operator ?
- random card game need help in C++
- Slove that problem
- How To Load Dll In Vc++
- question about auto_ptr initialization
- Problems with static libraries
- Is this a good idea? (Error handling with overloaded operators)
- Fibonacci Numbers and Lucas Numbers
- When does static initialization occur?
- A good c/c++ algorithms / design patterns book
- arrays and pointers question
- ICMLA 2007: CALL FOR PAPERS
- ICMLA 2007: CALL FOR PAPERS
- Scientific Notation
- Why should I learn C++?
- ICMLA 2007: CALL FOR PAPERS
- Drawing AVLTree By MFC
- ICMLA 2007: CALL FOR PAPERS
- ICMLA 2007: CALL FOR PAPERS
- ICMLA 2007: CALL FOR PAPERS
- ICMLA 2007: CALL FOR PAPERS
- Book for VC++
- linker error building code with boost filesystem
- Inheritance not letting signature to come through.
- sound_C_under_linux
- printf from DLL
- Address of a constant
- What this means?
- implicit hiding of same-named methods of base class in derived classes - why?
- unformatted IO binary to ASCII to binary
- ptr1 == ptr2 but (int)ptr1 != (int)ptr2
- Port Information in C++
- How export data from Visual C++ to CSV?
- what will happen if we print the following...
- what will happen if we print the following...
- How to print permutations?
- null variable
- efficient way of looking up huge hashes
- Segmentation Error in Code...
- Anyone know of C++ source code spell checker?
- data from text file to doubly Linked List
- list = list->Next = malloc(sizeof(node));
- Mathematical Methods
- ping
- Virtual Member Function
- How do i add image to VC++ program?
- Xerces Vs LibXML VS TinyXML?
- Hot Key in Button
- Allocating memory to nested Structures within a Structure
- reading a text file into a 2d array problem
- Difference between widechartomultibyte and wcstombs
- The default double values get truncated
- Google looking for new recruitment agent
- Why won't this cast?
- FileNotFoundException
- Operation Of Gets
- Why do I get "unresolved external symbol" error only when I compile with "releas" mod
- what is wrong with my code?
- Visual Studio for cross platform (windows/linux) developement?
- Google looking for Great Engineers
- Replace escapeable characters with escape sequence?
- Call VB script using c++ program
- creating a folder in C
- Need help in an undefined reference linker error
- pimpl idiom and singletons
- Reference base class data from derived class?
- _BLOCK_TYPE_IS_VALID - 'by value' destruction problem
- Detecting matching files?
- sorting/searching arrays
- Do you konw how to make exe file with Borland c++ ?
- How to Change the initial dialog in a dialog-based app
- simple question about containers
- Weired compilation with STL <algorithm> header.
- how to delete a file?
- what is #include <stdio.h> and what is scanf("%5d",&a)
- delphi to C migration ..
- Passing templated types as parameter to macro
- What is wrong with my code? (strings)
- Question on dynamic binding
- Using libconfig with Groups
- Q>how to manipulate keyboard
- Get ASCII value for character when higher than 127
- Get ASCII value for character when higher than 127
- floating point to ASCII conversion
- how can we get Addersses of different devices through c on winxp or any platform ?
- how to simulate the passwoed '*'
- invalid conversion from int to file
- Function Pointer.
- Enforce instruction ordering?
- {0} vs {}
- Pointer problem
- Ternary operator ((a>b)?a:b) inside return statement?
- Create function given prototype.
- Vector is deleted after resize()
- C++ Gui Application on both OS X and WinXP
- IDE for beginner
- GPIB address
- File locking on windows
- Determine degree of function.
- Inlining Constructors
- Multidimensional hash functions
- Program Taylor series
- structures help
- Difference in MFC classes
- data structures (fundamental operations on linked list)
- structure alignment rules
- programming
- programming
- diag_printf
- Converting strings to int
- Add polynomials using dll
- Passing Value of a struct into a function
- Confusion in Data type!
- How to write a map to file.
- How to set the Environment Variables
- append output filename
- Problem in Installation of cross compiler GCC2.96+ and GCC 4.2 Beta in Cygwin!!!
- C Or C++ Connectivity With Orcle Database
- What I like most about C++
- Memory : Stack vs Heap
- VC++ button colour change
- VC++ Exception Handling
- C# or C++?
- returning a multi-dimensonal array
- Getting Base* to act as its actual Derived* type
- A "how does it work" type question
- Sweet Loads Down the Throat
- Sweet Loads Down the Throat
- Q: Recoding some masking routine
- calculating 2^601 results in "1.#INF00"
- Problem with list
- VC++/GDI+ Imageattributes.SetColorMatrix
- Manipulator question...
- strcpy in C
- getcwd changes? how can I get current path?
- Creating a file system with FUSE.
- heey can someone help me with these
- Model and Texture but with children
- Help with this C++ Program! (Beginner)
- IO Manipulator: Partial 'uppercase'?
- nonmember functions?
- Custom Allocator Question - Advanced.
- What is the meaning of 'wt' in utf8_fopen
- map vs. set (stl)
- What is the difference between void proba(); and void proba(void); ???
- What this error means?
- Include header files in a single header file?
- why its not consuming memory
- Why using the new keyword at all for memory allocation?
- [Info] Programmers Search Engine
- Convert between PGM @ PPM
- Do i have to have a main function?
- Convert between PGM @ PPM
- Convert between PGM @ PPM
- in newton raphson method
- Converting between const char* and char*
- proper use of (volatile unsigned short *)
- Question about singleton class design for tracing
- get corruption at end of string
- Grid Control
- operator= for a class with a const reference member
- with respect to the memory
- Trying to get contents of an ifstream AND find file size at same time
- wat is .bss segment in object file
- Enable functions in the derived class with the same function name but different return type?
- Template : cannot convert parameter 1 from const * to *const & ?
- address of an array
- Copy constructor question (repost)
- Copy constructor question
- C macro for ellipsis(...)
- Derived::Derived(const Base&) and Derived& operator=(const Base&)
- site for sample c++ programs
- fstream - not creating files / not appending files / etc.
- problem with float
- factorial program
- How To Use System Commands In C
- [c] Efficiently writing large quantities of data to a file
- Derived and base class question
- some C questions
- simple array question
- "Virtual constructor" and slicing
- pointers and beginnings of arrays
- String
- <FRIENDS CLUB>
- Directory Seperation
- lots of little mallocs or one big one? (somewhat naive)
- Deprecated API RWTPtrHashDictionary<K,V>
- Please explain what this expression means
- IOHASDIOUHYIOUHSADIUIILASDFIGISADFGILYGIYSADFGGSAF DJHJSDAFFFFD
- The infamous ^Z problem
- for_each() and two-dimensional array
- Use own icon C++
- How to seek in a file "wb"?????
- recursive
- The future
- Ray tracer language comparison
- portability
- Symbolic manipulation
- class Car - turnIgnitionOn/Off
- Derived::Derived(const Base&) and Derived& operator=(const Base&)
- Urgent need for 2 C++ contract Developers in Mesa, Arizona (Phoenix)
- friend template error in gcc 4.1
- inaccessible base despite public inheritance | https://bytes.com/sitemap/f-308-p-50.html | CC-MAIN-2019-43 | refinedweb | 2,911 | 52.49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.