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 |
|---|---|---|---|---|---|
CodePlexProject Hosting for Open Source Software
Hi,
I have DevExpress ASP.NET MVC Extensions license and I was wondering if I could use those MVC Extensions in creating modules for Orchard CMS.
I tried today to integrate those controls but I received several errors... If you look at the documentation here,
they required those extensions to be registered in the web.config file. In short, here are the steps required :
All those steps could easily be done in a normal MVC Application but how do we do all this in a module... I want to distribute these modules. Any body who wants to use the modules should be able to click install and be done with it. I don't want the users
to register HttpHandlers and Modules...
Can anybody point me in the right direction?
Adding references can be done in your project file. Registering script and stylesheets should be easy, using the corresponding Orchard APIs. For the namespaces you can always put using directives in your views.
The part that I'm more concerned about is the HTTP handler and module. The handler could probably be dealt with by creating a route for it. The module on the other hand I have no idea how to wire. They don't seem to provide any details about what it's doing
either.
It looks like registering HttpModules in the Web.Config is mandatory...
Does Orchard allow us to register HttpModules in the parent websites Web.Config file?
It doesn't, except by modifying web.config... This might be worth a shot:
bertrandleroy wrote:
It doesn't, except by modifying web.config... This might be worth a shot:
bleroy this is a cool feature of asp.net but I can't execute it inside a module. The way it works for me is inside Orchard.Web.
I'm guessing the PreApplicationStartMethod won't work because your dll isn't loaded at application start, Orchard loads it dynamically later.
But it could still be possible to use DynamicModuleHelper at a different point, or even to build a feature into Orchard using that technique that would allow modules to register HttpModules.
The DynamicModuleUtility.RegisterModule Method can only run on PreApplicationStart. If you try in a module generate errors.
I'ld really like to use devexpress controls in orchard modules. Any suggestions?
You will either need to modify the root web/config or to ask DevExpress to build a version of their controls that works in Orchard. Or contribute or file a suggestion to provide a hook for modules to register http modules, but that may not even be technically
possible and if it is it may take a while. Really, DevExpress building an Orchard module looks like the easiest option.
bleroy take a look what devexpress suggests with inheritInChildApplications="false" in web.config here:.
Have to try it.
Sorry, but I don't understand how that solves anything.
I think they are getting confused over the difference between deploying an Application in a sub-folder vs.
MVC area which happens to have its own Web.config - these are two totally different things.
I'm not sure what devexpress is requiring HttpModules for, but with Orchard you can use a FilterProvider / IRequestFilter to wrap around the request for most scenarios that a HttpModule would typically be used for. Unless they're doing something extremely
funky in their HttpModule this should be possible, but it boils down to whether they're prepared to do an Orchard release.
I'd honestly look for something open source that provides the functionality you're after if you want to build something that can be distributed as a module; so you can do your own integration if needed. Since devexpress requires a license it's not exactly
something you could easily distribute anyway...
The solution I have found till now is to create a class library project and a class in it with only this
public static void Start() {
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule));
}
then edit the AssemblyInfo.cs and add
[assembly: PreApplicationStartMethod(typeof(Orchard.Devexpress.PreApplicationStartCode), "Start")]
where Orchard.Devexpress is the namespace and PreApplicationStartCode is the class.
Compile and put the dll in bin directory of Orchard.Web project.
Hope that helps.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/251722 | CC-MAIN-2017-43 | refinedweb | 748 | 58.08 |
Very
...;
In the above code is there any way i can replace all those " " with a single sign
Java
Pop up Very Very Urgent Respected Sir/Madam,
I am R.Ragavendran.. I got your reply.. Thank you very much for the response. Now I am sending the code.. Here When I click "View Database" Button,a small pop up window must
Help Very Very Urgent - JSP-Servlet
Help Very Very Urgent Respected Sir/Madam,
I am sorry..Actually... again..
Actually my code needs the following output:
There is a combo box which... requirements..
Please please Its Very very very very very urgent...
Thanks
Very Very Urgent -Image - JSP-Servlet
Very Very Urgent -Image Respected Sir/Madam,
I am... with some coding, its better..
PLEASE SEND ME THE CODING ASAP BECAUSE ITS VERY VERY URGENT..
Thanks/Regards,
R.Ragavendran... Hi friend,
Code important - Kindly help
very important - Kindly help I am creating web page for form registration to my department ..I have to Reprint the Application Form (i.e Download... sample code
very urgent
very urgent **
how to integrate struts1.3
,ejb3,mysql5.0 in jboss server with
myeclipse IDE
JSP and AJAX- very urgent - Ajax
JSP and AJAX- very urgent Respected Sir/Madam,
I am... GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7...();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject
Switch Statement example in Java
also provides you an example with complete
java source code for understanding... Switch Statement example in Java
This is very simple Java program
Java Util Package - Utility Package of Java
Java Util Package - Utility Package of Java
Java Utility package is one of the most commonly used packages in the java
program. The Utility Package of Java consist
Java util package Examples
Lang and Util Base Libraries
Lang and Util Base Libraries
The Base libraries provides us the fundamental features and functionality of
the Java platform.
Lang and Util Packages
Lang....
Reflection
Reflection enables Java code to discover information... code:
EMPLOYEE DETAILS
Enter Employee ID...
Please please its very urgent..
Thanks/Regards,
R.Ragavendran..
(very urgent) - Design concepts & design patterns
(very urgent) hi friends,
This is my code in html
...;
In the above code is there any way i can
Validating Number Very Urgent - JSP-Servlet
Validating Number Very Urgent Respected Sir/Madam,
I am... of Emp ID text box.. I am sending the code for your kind reference which tends you...('id').value=
document.getElementById('name').value=''
Its Very
Simple Program Very Urgent.. - JSP-Servlet
Simple Program Very Urgent.. Respected Sir/Madam,
I am... for emp_id and emp_name...
Here's the code:
Step 1: Creating home page....
4.The code
var url="getuser.jsp simple reference source - Java Beginners
a Java simple reference source (on line or e-book) where I could quickly find... would like to have a Java reference source for a quick look.
I have got some... you very much anyway.
Spring Bean Example, Spring Bean Creation
:
Spring is simple
Download this example code...Basic Bean Creation
The Spring bean can typically be POJO(Plain Old Java... java bean file
having two methods getMessage() and setMessage() and a default
Open Source Document Management
;
The basic idea behind open source is very simple ? when programmers can read, modify and redistribute source code, the software evolves and improves. Industry leaders...Open Source Document Management
Open Source Document Management
Open Source Installer
, install or update shared components.
Open Source Java Tool... of Java development tools and a few common open source tools that aren't just... - Installer on several Platforms
Quake 3 source code has been released under
Image selection instead of radio button very urgent.. - JSP-Servlet
Image selection instead of radio button very urgent.. Respected Sir/Madam,
I am R.Ragavendran.. Actually in the following using radio... the code:
function trim(stringToTrim) {
return stringToTrim.replace
Ple help me its very urgent
Ple help me its very urgent Hi..
I have one string
1)'2,3,4'
i want do like this
'2','3','4'
ple help me very urgent
What is MySQL
;
MySQL is a open source Relational Database Management System. MySQL is
very fast... applications as it provides good speed and is
very secure. MySQL was developed... of data into database.
Availability of Source
MySQL source code
J2ME Calendar Application
;
Creating a calendar is a very basic example to learn any... on creating
calendar in Java, JavaScript etc. But in this example you will learn how... like as follow..
Source Code of CalenderMIDlet.java
import
Answer me ASAP, Thanks, very important
Answer me ASAP, Thanks, very important Sir, how to fix this problem in mysql
i have an error of "Too many connections" message from Mysql server,, ASAP please...Thanks in Advance help desk
source help desk applications out there. Not the ones where the site hasn?t been... modify their source code. For those reasons, they've gained popularity...Open Source Help Desk
Open Source Help Desk Software
As my help desk... document to the webpage(for which i don t have access to source code
Master Java In A Week
into HTML format from Java source code. It is interesting to know that
Javadoc.... This tutorial is good for
beginners in Java and it will teach you the basics... applications and
embedded devices. Performance of the Java application is
Changing the value of Array in Java
with
Java Source code.
Here we are going to make a program to follows the one...
Changing the Value of Array in Java
This is very simple of one dimensional array program
Open Source Workflow Engines written in Java
Open Source Jobs
you to for example fill out a profile, announce a Open Source related Job, Bounty... transfers.
Open Source Job Schedulers in Java
On some... developers and architects how to integrate Quartz with leading open source Java
Good tutorials for beginners in Java
in details about good tutorials for beginners in Java with example?
Thanks.
Hi, want to be command over Java, you should go on the link and follow...Good tutorials for beginners in Java Hi, I am beginners in Java
util packages in java
util packages in java write a java program to display present date and after 25days what will be the date?
import java.util.*;
import java.text.*;
class FindDate{
public static void main(String[] args
Java Training at Noida
can also get world class Java Training at Noida.
It?s a good chance...
Java Training at Noida
Looking for Java Training classes at Noida? your search ends here. Get world
Learn Java in 24 hours
Learning Java programming language is very simple especially for developers... of the
syntax of Java are similar to that of C and C++ so developers don't find it hard
to code in Java language.
RoseIndia brings you a quick Java guide
Example program to get all the available time zones
to get all the
available time zones using java program. This example is very simple java code
that will list all the available time zones. We have used... zones.Here is the example code of AllTimeZones.java as
follows
Open Source Software
. Open source software
is very useful because source code also distributed along with the executable of
the application. Anyone can modify the source code... is also know as OSS. Simply open source means the
availability of the Source code
Java ArrayList, Java Array List examples
the ArrayList in Java with the example code.
SampleInterfaceImp.java
import...
list.add("Java ");
list.add("is ");
list.add("very ");
list.add("good... as shown below:
Java is very good programming language
Download
iBatis Update -Updating data of a table
",contactId);
Full source code of IbatisUpdate.java is as follows... Source Code
...;
Add, Update and Delete are very common
Give me the source code for this problem
Give me the source code for this problem Ram likes skiing a lot. That's not very surprising, since skiing is really great. The problem with skiing... of different peaks is given by a grid of numbers. Look at this example:
7 2 3 4 5
Open Source Exchange
thing I?ve seen this month, or too good to be true. I haven?t decided which yet...;
DDN Open Source Code Exchange
The DDN site... macro source code subject to the terms outlined below. All of the source code.*"%>
Java source code
Java source code How are Java source code files named
Show input dialog box
Swing Input Dialog Box Example - Swing Dialogs
Input dialog box is very important and interactive
feature of Java Swing. You have been using the System.in for inputting
Hibernate Example Step by Step in Eclipse
the application. Create a new file CreateData .java
and then add the following code...Hibernate Example Step by Step in Eclipse - The easiest way of getting... you step-by-step tutorial of creating first example in
Hibernate 4.2. We have
Open Source Business Model
to a possible open-source approach in running a business company. While very simple...
A few years ago, releasing once-secret source code to the public would have... source authors that I know of aren?t writing their software for the money they hope
Open Source DRM
music listeners
hate DRM, the very idea of using open-source software... and source code for DReaM, an open-source, "royalty-free digital rights management...Open Source DRM
SideSpace releases open source DRM solution
SideSpace
java source code
java source code java source code to create mail server using struts2
attendance management system source code
attendance management system source code sir i want full ateendance management project please send me source code i am asking so many members... answer so please send code it's very urgent
SCJP Module-9 Question-24
Given below the sample code :
public static void addition(List list) {
list.add("0021");
}
public static void main(String[] args) {
List<...);
System.out.println(myList.get(0));
}
What will be the output of the above code ?
1. 21
EJB Hello world example
EJB Hello world example
Creating and testing the "Hello World"
Example is the very first... Source code
Find Your Host Name
of the local
system in a very simple manner. the complete code of the example is as under.
Here is the Code of the Example :
Hostname.java... the
host name of the local system in a very simple example. Here we are just call
First Step towards JDBC!
the databases. For the shake of simplicity, in
very first example Access database... a
thin code of Java wrap around the native code and converts JDBC...?
Java
Database Connectivity or JDBC for short is set of Java API's
Retrieving Tables from a Database
;
In database system it is very important to know about
the tables. To work with this, it is very important to know how to retrieve... for retrieving
tables from a specific database through an example. In relational
attendance management project source code
attendance management project source code sir i want full ateendance management project please send me source code i am asking so many members... answer so please send code it's very urgent
Open Source e-commerce
with the source code freely available for alteration and customization. Using... code and J2EE best practices.
Open Source E... source PHP code allows modifying every aspect of the system to meet business
JavaScript open() method
window"
Download Source Code
...;
This open() method is very useful for the programmers. Here is a case when
this might be very useful. Suppose you are filling some information
Source Code - Java Beginners
Source Code What do I have to add to my original code to make it work
java - Java Beginners
information on Stack or Heap Visit to :
Thanks
http....,
the execution of all those functions remains suspended until the very last function returns | http://www.roseindia.net/tutorialhelp/comment/14258 | CC-MAIN-2014-42 | refinedweb | 1,963 | 66.54 |
0
hey, I promise i'm getting there!!
so my code now seems to be emptying the structures as they are passed between the functions, any thought on how to fix it? also if anyone knows of any good examples of passing by reference, that could apply to this code that would be great
header
#include <math.h> #include <iostream> #include <array> #include <string> #include <time.h> using namespace std; struct team{ string name; int atk; int def; int striker; int keeper; int score; bool progress; };
main
#include "sim-header.h" using namespace std; void setup(team, team, team, team, team, team, team, team); void game(team,team); void group (team, team, team, team); int main(){ team one = {" ",0,0,0,0,0,0}; team two = {" ",0,0,0,0,0,0}; team three = {" ",0,0,0,0,0,0}; team four = {" ",0,0,0,0,0,0}; team five = {" ",0,0,0,0,0,0}; team six = {" ",0,0,0,0,0,0}; team seven = {" ",0,0,0,0,0,0}; team eight = {" ",0,0,0,0,0,0}; cout<<"welcome to the world cup simulator"<<endl; setup (one, two, three, four, five, six, seven, eight); game (one, two); system("PAUSE"); return 0; } void setup (struct team one, struct team two, struct team three, struct team four, struct team five, struct team six, struct team seven, struct team eight){ system("PAUSE"); int t = 1; int kskill = 0; int sskill = 0; int atk = 0; int def = 0; int teamnum = 0; string name; cout<<"please enter the number of teams: 2, 4 or 8"<<endl; cin>>teamnum; while (t<= teamnum){ cout<<"please enter the name of team "<<(t)<<endl; cin>>name; cout<<"please enter the attack score of "<<name<<" (0 - 100) "<<endl; cin>>atk; cout<<"please enter the defence score of "<<name<<" (0 - 100) "<<endl; cin>>def; cout<<"please enter the keeper skill score for "<<name<<" (0 - 100) "<<endl; cin>>kskill; cout<<"please enter the striker skill score for "<<name<<" (0 - 100) "<<endl; cin>>sskill; if (t==1){ one.name = name; one.atk = atk; one.def = def; one.keeper = kskill; one.striker = sskill; }else{ if (t==2){ two.name = name; two.atk = atk; two.def = def; two.keeper = kskill; two.striker = sskill; }else{ if (t==3){ three.name = name; three.atk = atk; three.def = def; three.keeper = kskill; three.striker = sskill;; }else{ if (t==4){ four.name = name; four.atk = atk; four.def = def; four.keeper = kskill; four.striker = sskill;; }else{ if (t==5){ five.name = name; five.atk = atk; five.def = def; five.keeper = kskill; five.striker = sskill;; }else{ if (t==6){ six.name = name; six.atk = atk; six.def = def; six.keeper = kskill; six.striker = sskill;; }else{ if (t==7){ seven.name = name; seven.atk = atk; seven.def = def; seven.keeper = kskill; seven.striker = sskill;; }else{ if (t==8){ eight.name = name; eight.atk = atk; eight.def = def; eight.keeper = kskill; eight.striker = sskill;; } } } } } } } }t++; } system("PAUSE"); cout<< one.name<<" atk "<<one.atk<<" def "<<one.def<<" injury "<<" keeper "<<one.keeper<<" striker "<<one.striker<<endl; cout<< two.name<<" atk "<<two.atk<<" def "<<two.def<<" injury "<<" keeper "<<two.keeper<<" striker "<<two.striker<<endl; cout<< three.name<<" atk "<<three.atk<<" def "<<three.def<<" injury "<<" keeper "<<three.keeper<<" striker "<<three.striker<<endl; cout<< four.name<<" atk "<<four.atk<<" def "<<four.def<<" injury "<<" keeper "<<four.keeper<<" striker "<<four.striker<<endl; cout<< five.name<<" atk "<<five.atk<<" def "<<five.def<<" injury "<<" keeper "<<five.keeper<<" striker "<<five.striker<<endl; cout<< six.name<<" atk "<<six.atk<<" def "<<six.def<<" injury "<<" keeper "<<six.keeper<<" striker "<<six.striker<<endl; cout<< seven.name<<" atk "<<seven.atk<<" def "<<seven.def<<" injury "<<" keeper "<<seven.keeper<<" striker "<<seven.striker<<endl; cout<< eight.name<<" atk "<<eight.atk<<" def "<<eight.def<<" injury "<<" keeper "<<eight.keeper<<" striker "<<eight.striker<<endl; system("PAUSE"); } void game(team a,team b){ srand (time(NULL)); cout<<"game start"<<endl; cout<<a.name<<" "<<a.atk<<" "<<a.def<<" "<<a.keeper<<" "<<a.striker<<endl; cout<<b.name<<" "<<b.atk<<" "<<b.def<<" "<<b.keeper<<" "<<b.striker<<endl; int aTrueAtk = (a.atk + rand() %25); int bTrueAtk = (b.atk + rand() %25); int aTrueDef = (a.def + rand() %25); int bTrueDef = (a.def + rand() %25); int shotsA = aTrueAtk - b.def; int shotsB = bTrueAtk - a.def; int n = 0; int scoreA = 0; int scoreB = 0; while (n<shotsA){ int aTrueSSkill = (a.striker + rand() %25); int aTrueKSkill = (a.keeper + rand() %25); int bTrueSSkill = (b.striker + rand() %25); int bTrueKSkill = (b.keeper + rand() %25); if (aTrueSSkill > bTrueKSkill){ cout<<a.name<<" scores!! "<<endl; scoreA = scoreA + 1; cout<<scoreA<<"-"<<scoreB<<endl; n++; }else{ if (aTrueSSkill < bTrueKSkill){ cout<<b.name<< " saves it!! "<<endl; cout<<scoreA<<"-"<<scoreB<<endl; n++; }else{ cout<< "Chance at a rebound!!!"<<endl; cout<<scoreA<< "-"<<scoreB<<endl; } } } n = 0; while (n<shotsB){ int aTrueSSkill = (a.striker + rand() %25); int aTrueKSkill = (a.keeper + rand() %25); int bTrueSSkill = (b.striker + rand() %25); int bTrueKSkill = (b.keeper + rand() %25); if (bTrueSSkill > aTrueKSkill){ cout<<b.name<<" scores!! "<<endl; scoreB = scoreB + 1; cout<<scoreA<<"-"<<scoreB<<endl; n++; }else{ if (bTrueSSkill < aTrueKSkill){ cout<<a.name<< " saves it!! "<<endl; cout<<scoreA<<"-"<<scoreB<<endl; n++; }else{ cout<< "Chance at a rebound!!!"<<endl; cout<<scoreA<<"-"<<scoreB<<endl; } } } if(scoreA>scoreB){ cout<<a.name<<" wins"<<endl; a.score = (a.score + 3); }else{ if(scoreA==scoreB){ cout<<"it's a draw!"<<endl; a.score = (a.score + 1); b.score = (b.score + 1); }else{ cout<<b.name<<" wins"<<endl; b.score = (b.score + 3); } } } //void group (team a, team b, team c, team d){ // game(team a, team b); // game(team c, team d); // game(team a, team c); // game(team b, team d); // game(team b, team c); // game(team a, team d); // //} | https://www.daniweb.com/programming/software-development/threads/375530/still-passing-structures | CC-MAIN-2017-26 | refinedweb | 930 | 82.41 |
Lesson 4. GIS in Python: Introduction to Vector Format Spatial Data - Points, Lines and PolygonsSpatial data open source python Workshop
Learning Objectives
After completing this tutorial, you will be able to:
- describe the characteristics of 3 key vector data structures: points, lines and polygons.
- open a shapefile in
Pythonusing
geopandas-
gpd.read_file.
- view the
CRSand other spatial metadata of a vector spatial layer in
Python
- access and view the attributes of a vector spatial layer in
Python.
What You Need
You will need a computer with internet access to complete this lesson and the spatial-vector-lidar data subset created for the course.
Download spatial-vector-lidar data subset (~172 MB)
About Vector Data
Vector data are composed of discrete geometric locations (x, y values) known as vertices that define the “shape” of the spatial object. The organization of the vertices determines the type of vector that you are working with. There are three types of vector data:.
. format).!
Import Shapefiles
You will use the
geopandas library to work with vector data in
Python. You will also use
matplotlib.pyplot to plot your data.
import geopandas as gpd import matplotlib.pyplot as plt import os import earthpy as et import os # plot data inline plt.ion() # set working directory os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))
The shapefiles that you will import are:
- A polygon shapefile representing our field site boundary,
- A line shapefile representing roads, and
- A point shapefile representing the location of field sites at the San Joachin field site..
# import shapefile using geopandas sjer_plot_locations = gpd.read_file('data/spatial-vector-lidar/california/neon-sjer-site/vector_data/SJER_plot_centroids.shp')
The CRS UTM zone 18N. The CRS is critical to interpreting the object
extent values as it specifies units., our road, may have a name, length, number of lanes, speed limit, type of road and other attributes stored with it.
You can view the attribute table associated with our geopandas
GeoDataFrame by simply typing the object name into the console (e.g.,
sjer_plot_locations).
Her you’ve used the
.head(3) function to only display the first 3 rows of the attribute table. Remember that the number in the
.head() function represents the total number of rows that will be returned by the function.
# view the top 6 lines of attribute table of data sjer_plot_locations.head(6)
In this case, you have several attributes associated with our points including:
- Plot_ID, Point, easting, geometry, northing, plot_type
Data Tip: The acronym, OGR, refers to the OpenGIS Simple Features Reference Implementation. Learn more about OGR.
The Geopandas Data Structure
Notice that the geopandas data structure is a
data.frame that contains a
geometry column where the x, y point location values are stored. All of the other shapefile feature attributes are contained in columns, similar to what you may be used to if you’ve used a GIS tool such as ArcGIS or QGIS.
Shapefile Metadata & Attributes
When you import the
SJER_plot_centroids shapefile layer into
Python the
gpd.read_file() function automatically stores information about the data as attributes.
.total_bounds methods:
type(sjer_plot_locations)
geopandas.geodataframe.GeoDataFrame
# view the spatial extent sjer_plot_locations.total_bounds
array([ 254738.618, 4107527.074, 258497.102, 4112167.778])
sjer_plot_locations.crs
{'init': 'epsg:32611'}
The CRS for our data is epsg code:
32611. You will learn about CRS formats and structures in a later lesson but for now a quick google search reveals that this CRS is: UTM zone 11 North - WGS84.
sjer_plot_locations.geom_type
0 Point 1 Point 2 Point 3 Point 4 Point 5 Point 6 Point 7 Point 8 Point 9 Point 10 Point 11 Point 12 Point 13 Point 14 Point 15 Point 16 Point 17 Point dtype: object
How Many Features Are in Your Shapefile?
You can view the number of features (counted by the number of rows in the attribute table) and feature attributes (number of columns) in our data using the pandas
.shape method. Note that the data are returned as a vector of two values:
(rows, columns)
Also note that the number of columns includes a column where the geometry (the x, y coordinate locations) are stored.
sjer_plot_locations.shape
(18, 6)
Plot a Shapefile
Next, you can visualize the data in your
Python
geodata.frame object using the
.plot() method. Notice that you can create a plot using the geopandas base plotting using the syntax:
dataframe_name.plot()
The plot is made larger but adding a figsize = () argument.
# plot the data using geopandas .plot() method fig, ax = plt.subplots(figsize = (10,10)) sjer_plot_locations.plot(ax=ax);
You can plot the data by feature attribute and add a legend too. Below you add the following plot arguments to your geopandas plot:
- column: the attribute column that you want to plot your data using
- categorical=True: set the plot to plot categorical data - in this case plot types.
- legend: add a legend
- markersize: increase or decrease the size of the points or markers rendered on the plot
- cmap: set the colors used to plot the data
and fig size if you want to specify the size of the output plot.
fig, ax = plt.subplots(figsize = (10,10)) # quickly plot the data adding a legend sjer_plot_locations.plot(column='plot_type', categorical=True, legend=True, figsize=(10,6), markersize=45, cmap="Set2", ax=ax);
You can add a title to the plot too. Below you assign the plot element to a variable called ax. You then add a title to the plot using
ax.set_title().
# Plot the data adjusting marker size and colors # # 'col' sets point symbol color # quickly plot the data adding a legend ax = sjer_plot_locations.plot(column='plot_type', categorical=True, legend=True, figsize=(10,10), markersize=45, cmap="Set2") # add a title to the plot ax.set_title('SJER Plot Locations\nMadera County, CA', fontsize=16);
Change Plot Colors & Symbols
You can use the cmap argument to adjust the colors of our plot. Below you used a colormap that is a part of the matplotlib colormap library.
Finally you use the marker= argument to specify the marker style.
fig, ax = plt.subplots(figsize = (10,10)) sjer_plot_locations.plot(column='plot_type', categorical=True, legend=True, marker='*', markersize=65, cmap='OrRd', ax=ax) # add a title to the plot ax.set_title('SJER Plot Locations\nMadera County, CA', fontsize=16);
ax = sjer_plot_locations.plot(figsize=(10, 10), column='plot_type', categorical=True, marker='*', markersize=65, cmap='OrRd') # add a title to the plot ax.set_title('SJER Plot Locations\nMadera County, CA', fontsize = 16);
Plot Shapefiles Using matplotlib and geopandas
Above you saw how to quickly plot shapefiles using geopandas plotting. The geopandas plotting is a great option for quickly exploring your data. However it is less customizable than
matplotlib plotting. Below you will learn how to create the same map using
matplotlib to setup the axes.
To plot with
matplotlib you first setup the axes. Below you define the figuresize and marker size in the ax argument. You can adjust the symbol size of our plot using the
markersize argument. You can add a title using
ax.set_title().
You can create a larger map by adjusting the
figsize argument. Below you set it to 10 x 10.
Test your knowledge: Import Line & Polygon Shapefiles
Using the steps above, import the
data/week5/california/madera-county-roads/tl_2013_06039_roads and
data/week5/california/SJER/vector_data/SJER_crop.shp shapefiles into
Python. Call the roads object
sjer_roads and the crop layer
sjer_crop_extent.
Answer the following questions:
- What type of
Pythonspatial object is created when you import each layer?
- What is the
CRSand
extentfor each object?
- Do the files contain, points, lines or polygons?
- How many spatial objects are in each file?
Plot Multiple Shapefiles
You can plot several layers on top of each other using the geopandas
.plot method too. To do this, you:
- define the
axvariable just as you did above to add a title to our plot.
- then you add as many layers to the plot as you want using geopandas
.plot()method.
Notice below
ax.set_axis_off() is used to turn off the x and y axis and
plt.axis('equal') is used to ensure the x and y axis are uniformly spaced.
# import crop boundary sjer_crop_extent = gpd.read_file("data/spatial-vector-lidar/california/neon-sjer-site/vector_data/SJER_crop.shp")
fig, ax = plt.subplots(figsize = (10, 10)) # first setup the plot using the crop_extent layer as the base layer sjer_crop_extent.plot(color='lightgrey', edgecolor = 'black', ax = ax, alpha=.5) # then add another layer using geopandas syntax .plot, and calling the ax variable as the axis argument sjer_plot_locations.plot(ax=ax, column='plot_type', categorical=True, marker='*', legend=True, markersize=50, cmap='Set2') # add a title to the plot ax.set_title('SJER Plot Locations\nMadera County, CA') ax.set_axis_off() plt.axis('equal');
Custom Legends with Geopandas – optional
While you will likely not get to this in our workshop, below is an example of further customizing your geopandas plot.
Currently there is not a perfect way to create a custom legend in Geopandas although that functionality is being considered. An alternative is to plot your data using loops and a dictionary that provides the various attributes that you want to apply to each point type.
# make it a bit nicer using a dictionary to assign colors and line widths plot_attrs = {'grass': ['blue', '*'], 'soil': ['brown','o'], 'trees': ['green','*']} # plot the data fig, ax = plt.subplots(figsize = (12, 8)) # first setup the plot using the crop_extent layer as the base layer sjer_crop_extent.plot(color='lightgrey', edgecolor = 'black', ax = ax, alpha=.5) for ctype, data in sjer_plot_locations.groupby('plot_type'): data.plot(color=plot_attrs[ctype][0], label = ctype, ax = ax, marker = plot_attrs[ctype][1], ) ax.legend(title="Custom Legend") ax.set_title("United States Roads by Type", fontsize=20) ax.set_axis_off() plt.axis('equal');
Share onTwitter Facebook Google+ LinkedIn
| https://www.earthdatascience.org/workshops/gis-open-source-python/intro-vector-data-python/ | CC-MAIN-2018-34 | refinedweb | 1,615 | 57.87 |
Pytrack - name 'machine' is not defined
Re: Pytrack usage?
I got this when I try to upload the code: I use this one:
but the problem I have is with the (lopy-receiver.py) part of the code
I try to formate the code so its easy to read but I fail on that part.
´´´´
import _thread
import socket
import pycom
import utime
from machine import WDT
from machine import RTC
from network import LoRa
Set RTC for timestamping (although it's not currently used)
rtc = machine.RTC()
rtc.ntp_sync("pool.ntp.org")
utime.sleep_ms(750)
print("\nRTC Set from NTP to UTC:", rtc.now())
utime.timezone(7200)
print("Adjusted from UTC to EST timezone", utime.localtime(), "\n")
Set up the LoRa in longer range mode
lora = LoRa(mode=LoRa.LORA, frequency=868000000, tx_power=14, bandwidth=LoRa.BW_125KHZ, sf=7)
l = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
l.setblocking(False)
Set up web socket
wdt = WDT(timeout=5000)
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
s = socket.socket()
s.settimeout(1)
s.bind(addr)
s.listen(1)
print("listening on", addr)
Threaded server
def _serve():
while True:
wdt.feed()
method, route, proto = None, None, None
ts = utime.time()
try: cl, addr = s.accept() except OSError: continue print("client connected from", addr) while True: try: line = cl.readline() print(line) ## Only handle GET requests if line[0:3] == b"GET": method, route, proto = line.split(b" ") if not line or line == b'\r\n': break except MemoryError: cl.send(" ") cl.close() continue ## Boilerplate JSON response response = """HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/javascript\r\n\r\n{
"position": {
"latitude": %f,
"longitude": %f
},
"message": "%s",
"timestamp": %i
}"""
## Crude hack to handle URL routes if route is not None: route = route.split(b"/") route.pop(0) print(route) ## If position.json is requested then receive LoRa message from sender if route[0] == b"position.json": msg = l.recv(64) ## Decode and split out into latitude and longitude if not msg == b"": msg = msg.decode("utf-8") lat, lon = [float(i) for i in msg.split(",")] response = response % (lat, lon, "success", ts) print(response) ## Otherwise, send 404 else: response = """HTTP/1.1 404 Not Found
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Pragma: no-cache
"""
print(response)
## Handles missing routes by sending 404 else: response = """HTTP/1.1 404 Not Found
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Pragma: no-cache
"""
cl.send(response) cl.close()
Start the thread
_thread.start_new_thread(_serve, ())
´´´
@stefan85e Having Pytrack AND Wifi, you have two sources for the time:
a) a NTP server. For that you have to espablish an internet connection. Look at the documentation & examples for WiFi and Internet access, Section, heading: "Connect to a router".
b) GPS. This is a little bit more tricky, since easy to use examples are missing. You can at least use the examples from thy Pytrack existing library and use that to derive the time information.
@xykon said in Pytrack - name 'machine' is not defined:
rtc.init
rtc = machine.RTC()
rtc.init((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.now())
thats a way to do it, but I dont want to set the time my self :)
- Xykon administrators last edited by
@stefan85e You would most likely connect to a router to have an internet connection which allows you to connect to
pool.ntp.org
Of course you can also set the time manually using rtc.init
- Xykon administrators last edited by Xykon
@stefan85e said in Pytrack - name 'machine' is not defined:
The time is wrong... Its from 1970 :)
The RTC holds the time since January 1st 1970... that's just how the RTC works.
In the Pytrack demo code we have the following:
rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org")
But if the module can't connect to pool.ntp.org it cannot set the time. Make sure that your module can reach the ntp server.
- Xykon administrators last edited by
@stefan85e said in Pytrack - name 'machine' is not defined:
@robert-hh So what should I do then!?
I added the lib machine.py and did try upload it
You shouldn't try to upload a
machine.pybecause machine is a built-in micropython module.
I suggest you try @robert-hh's suggestion to replace
rtc = machine.RTC()with
rtc = RTC()
@robert-hh So what should I do then!?
I added the lib machine.py and did try upload it
@stefan85e said in Pytrack - name 'machine' is not defined:
rtc = machine.RTC()
You did not import machine. So this line should read:
rtc = RTC() | https://forum.pycom.io/topic/2966/pytrack-name-machine-is-not-defined | CC-MAIN-2022-33 | refinedweb | 775 | 59.8 |
>>> "Harlan" == Harlan Stenn <address@hidden> writes: Harlan> I'm seeing the following with automake-1.6.3: Harlan> % automake Harlan> ... Harlan> Use of uninitialized value in hash element at automake line 8516 Harlan> Use of uninitialized value in list assignment at automake line 8505 Harlan> Use of uninitialized value in concatenation (.) at automake line 8506 Harlan> : warning: automake does not support bin_PROGRAMS being defined conditionally Harlan> Note the missing "location" of the Makefile.am in the Harlan> last line of the example. Could you explain how to reproduce this? I've tried if COND bin_PROGRAMS = foo endif but this didn't yield any warnings. -- Alexandre Duret-Lutz | http://lists.gnu.org/archive/html/bug-automake/2002-08/msg00036.html | CC-MAIN-2014-42 | refinedweb | 107 | 57.27 |
I run a job every minute to reindex my site's content.
Today, the search engine died, and when I logged in there were hundreds of orphan processes that had been started by cron.
Is there another way using some kind of existing software that will let me execute a job every minute, but that won't launch another instance if that job doesn't return (i.e. because the search engine process has failed)?
The problem isn't really with cron - it's with your job.
You will need to have your job interact with a lock of some description. The easiest way to do this is have it attempt to create a directory and if successful continue, if not exit. When your job has finished and exits it should remove the directory ready for the next run. Here's a script to illustrate.
#!/bin/bash
function cleanup {
echo "Cleanup"
rmdir /tmp/myjob.lck
}
mkdir /tmp/myjob.lck || exit 1
trap cleanup EXIT
echo 'Job Running'
sleep 60
exit 0
Run this in one terminal then before 60 seconds is up run it in another terminal it will exit with status 1. Once the first process exits you can run it from the second terminal ...
EDIT:
As I just learned about flock I thought I'd update this answer.
flock(1) may be easier to use. In this case flock -n would seem appropriate e.g.
flock -n
* * * * * /usr/bin/flock -n /tmp/myAppLock.lck /path/to/your/job
Would run your job every minute but would fail if flock could not obtain a lock on the file.
One way would be to have your reindex script create a lock file so that it can check to see if there's already an instance of the script running. You can also add in some exception handling to see if the search engine is up and running.
A more involved alternative would be to use some sort of task queuer like Resque and Resque-scheduler:
There's also Qu and Sidekiq:
Yes, that's all Ruby orientated, but you can look for "things like resque" in the language of your choice.
Another way to quickly set this up is to have a shell script start when the machine starts up (cron can do this with '@reboot /path/to/my/script.sh',. then restart the cron to start it up) with something like this in it.
@reboot /path/to/my/script.sh
#!/bin/sh
/opt/bin/run-site-index
sleep 60
exec $0
The script keeps running, and is you have only started one - thats how many could be running at once - no more than that. Some smarts in there can also check if the indexer is running, and if not, restart, or otherwise try to fix/notify someone of the issue.
Instead of using cron for this I would build your job more as a service that runs in a loop and sleeps for 60 seconds as the last step, or perhaps sleeps more often for smaller intervals at various points during the process to help spread out the load more evenly.
By posting your answer, you agree to the privacy policy and terms of service.
asked
2 years ago
viewed
659 times
active | http://serverfault.com/questions/376717/how-to-schedule-server-jobs-more-intelligently-than-with-cron?answertab=votes | CC-MAIN-2014-23 | refinedweb | 544 | 78.59 |
Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.
typedef struct point { int x; int y; int z; } point; typedef struct line { int nbPoints; vector<point> points; } line; line myLine; int sizeLine = sizeof(line);// 24 bytes int sizeMyLine = sizeof(myLine);// 24 bytes
Do more with
#include <iostream> #include <vector> typedef struct point { int x; int y; int z; } point; typedef struct line { int nbPoints; std::vector<point> points; } line; int main() { line myLine; size_t sizeLine = sizeof(line); size_t sizeMyLine = sizeof(myLine); std::cout << "sizeof(line) == " << sizeLine << std::endl << "sizeof(myLine) == " << sizeMyLine << std::endl; }
Premium ContentYou need an Expert Office subscription to comment.Start Free Trial | https://www.experts-exchange.com/questions/24836104/About-vector-container-in-the-STL-C.html | CC-MAIN-2019-47 | refinedweb | 135 | 55.37 |
16 April 2013 22:07 [Source: ICIS news]
MEDELLIN, Colombia (ICIS)--Seven people have been killed in violent clashes in Venezuela following Nicolas Maduro’s narrow victory in the country’s presidential election on Sunday, the country’s state news agency (AVN) said on Tuesday.
After a bitterly fought campaign triggered by the death of former leader Hugo Chavez in March, acting president Maduro beat opposition candidate Henrique Capriles by just 1.6 percentage points with 99% of the votes counted, according to the country’s electoral commission (CNE).
Capriles has contested the outcome of the election, calling the result “illegitimate”, and has demanded a full recount of the vote, which the CNE has ruled out.
The violence threatens to escalate into widespread civil conflict and raises serious questions concerning Maduro’s capacity to govern a deeply divided country.
According to AVN, the deaths occurred in the states of Miranda, Zulia and ?xml:namespace>
Local media have shown footage of police firing tear gas and rubber bullets to disperse protestors.
During a televised appearance on Tuesday, a clearly agitated Maduro condemned Capriles personally for the post-election violence and accused the opposition of attempting a coup.
“You are responsible for the dead that we are mourning today,” he said.
The president-elect also warned against a planned protest against the CNE by opposition supporters on Wednesday.
“We will come down hard on the fascists and those who threaten democracy,” he said. “If they want to overthrow me, let them come.”
Capriles responded to the provocation by suggesting that the violence is the government’s fault for not authorizing a recount of votes.
“The illegitimate one and his government ordered the violence to avoid a count of the votes,” Capriles said on Twitter. “They are responsible!”
Those who expected an easy win for Maduro – some pre-election polls had put the ruling party candidate 15 percentage points ahead of Capriles – were shocked at the slender victory margin. The new president is due to be officially sworn in on Friday.
In light of the violence and the clear political cleavages in
Rina Quijada, chief executive of petrochemical consultancy Intellichem, said that Maduro’s victory would be regarded as unfinished business for most voters.
“This will continue to fuel the polarization of the population during Maduro’s mandate,” she said.
Furthermore, the new president will require the political and economic expertise to manoeuvre the nation back to stability.
“If these are not part of the president’s political DNA, his mandate could be short-lived,” Quijada | http://www.icis.com/Articles/2013/04/16/9659673/venezuela-says-seven-dead-in-post-election-violence.html | CC-MAIN-2014-52 | refinedweb | 423 | 51.89 |
C - Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. These specifiers precede the type that they modify. There are.
#include <stdio.h> /* function declaration */ void func(void); static int count = 5; /* global variable */ main() { while(count--) { func(); } return 0; } /* function definition */ void func( void ) { static int i = 5; /* local static variable */ i++; printf("i is %d and count is %d\n", i, count); }
You may not understand this example at this time because I have used function and global variables, which I have not explained so far. So for now let us proceed even if you do not understand it completely. When the above code is compiled and executed, it produces the following result: keyword is being used to declare count in the second file where as it has its definition in the first file, main.c. Now, compile these two files as follows:
$gcc main.c support.c
This will produce a.out executable program, when this program is executed, it produces the following result:
5 | http://www.tutorialspoint.com/cprogramming/c_storage_classes.htm | CC-MAIN-2015-32 | refinedweb | 180 | 58.52 |
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
3 years, 11 months ago.
Using multiple BufferedSerial on Nucleo F091RC
Hello,
I have a problem using multiple BufferedSerial on the USARTs of NUCLEO F091RC. I picked this board because it has 8 USARTs. The PC is used for debug via USB. USART4 and USART5 are connected to a sensor that sends data every 10 seconds (82 bytes each sensor). USART8 is connected to a communication device.
To be specific when more than one USART is receiving data the program stop running (freeze).
If I comment one of the sensors the code works fine. If I use the Buffered Library only in one USART (per example only in USART4) the code works but I'm not capable to receive all the 82 bytes in the normal (non Buffered) Serial USART.
Main.cpp
#include "mbed.h" #include "BufferedSerial.h" #include "custom_f.h" Serial pc(USBTX, USBRX); BufferedSerial sensor1(PC_10, PC_11); BufferedSerial sensor2(PC_12, PD_2); Serial comDevice(PC_8, PC_9); // Not used yet DigitalOut myled(LED1); int main() { pc.baud(9600); sensor1.baud(19200); sensor2.baud(19200); comDevice.baud(115200); while(1) { if (sensor1.readable()) { pc.printf("SENSOR1: "); while(sensor1.readable()) { char incoming = sensor1.getc(); pc.putc(incoming); } pc.printf("\r\n"); } myled = !myled; wait_ms(500); if (sensor2.readable()) { pc.printf("SENSOR2: "); while(sensor2.readable()) { char incoming = sensor2.getc(); pc.putc(incoming); } pc.printf("\r\n"); } myled = !myled; wait_ms(500); } }
NOTE: To simplify the debugging process, I'm not using the real function that process the data sent by the sensor. The previous code work, is a simplified version for debug. This version freeze in the same way than the complex function, I mean when more than one USART receive data; eventually the LED1 stop "blinking" and the PC USB stop showing new data.
Can you please help ?
Thank you !
2 Answers
3 years, 11 months ago.
Hello Felícito,
Since you are receiving constant size (82 bytes) packets every ten seconds, another alternative is to use your own buffers:
#include "mbed.h" const int PACKET_SIZE = 82; // Data packet size const float RX_MAXTIME = 3.0f; // Maximum time gap between two serial bytes // (must be < time gap between two packets) char sensor1RxBuf[PACKET_SIZE]; char sensor2RxBuf[PACKET_SIZE]; volatile int sensor1RxLen = 0; volatile int sensor2RxLen = 0; Serial pc(USBTX, USBRX); Serial sensor1(PC_10, PC_11); Serial sensor2(PC_12, PD_2); Serial comDevice(PC_8, PC_9); // Not used yet DigitalOut myled(LED1); Timer rx1Timer; Timer rx2Timer; // Sensor1 serial received interrupt handler: Reads data into a buffer void onSensor1Rx(void) { if(sensor1RxLen < PACKET_SIZE) { sensor1RxBuf[sensor1RxLen++] = sensor1.getc(); rx1Timer.reset(); } else sensor1.getc(); } // Sensor2 serial received interrupt handler: Reads data into a buffer void onSensor2Rx(void) { if(sensor2RxLen < PACKET_SIZE) { sensor2RxBuf[sensor2RxLen++] = sensor2.getc(); rx2Timer.reset(); } else sensor2.getc(); } int main() { pc.baud(9600); sensor1.baud(19200); sensor2.baud(19200); comDevice.baud(115200); sensor1.attach(&onSensor1Rx); sensor2.attach(&onSensor2Rx); rx1Timer.start(); rx2Timer.start(); while(1) { // Discard incomplete/corrupted packets if (rx1Timer.read() > RX_MAXTIME) sensor1RxLen = 0; if (rx2Timer.read() > RX_MAXTIME) sensor2RxLen = 0; // Process complete packets if (sensor1RxLen == PACKET_SIZE) { sensor1RxLen = 0; pc.printf("SENSOR1: "); for(int i = 0; i < PACKET_SIZE; i++) pc.printf(" %x", sensor1RxBuf[i]); pc.printf("\r\n"); } if (sensor2RxLen == PACKET_SIZE) { sensor2RxLen = 0; pc.printf("SENSOR2: "); for(int i = 0; i < PACKET_SIZE; i++) pc.printf(" %x", sensor2RxBuf[i]); pc.printf("\r\n"); } myled = !myled; wait_ms(500); } }
3 years, 11 months ago.
For a start increase the baud rate on the pc connection and take out the waits.
Each time around your loop takes about 1.15 seconds (1s of waits plus the time it takes to send 2x 84 bytes at 9600 baud from a uart with a 16 byte tx buffer.) If you sensors are sending data at 1Hz then you aren't going to keep up with them.
There is no reason at all to have those waits in there.
For every 82 bytes that show up on a sensor you are outputting 84 bytes to the PC. Since you have two sensors that means that you should set the PC uart baud rate to at a very minimum twice the sensor baud rate, ideally faster.
Thanks for your reply Andy.
I have tried changing the pc baudrate to 38400. But it does not work, the program keep freezing when both USART receive data from the sensor1 and sensor2.I kept digging and found this table. Link:
Table 10. STM32F091xB/xC USART implementation:
Where: X mean supported.
I kept the pc baudrate in 38400; but move the sensor1 to USART1 and sensor2 to USART3 (by factory the USART2 is the PC, could be change moving some jumpers in the board); keep using BufferedSerial and everything work fine :) . Also modify the wait_ms - this to gave time for the buffer to be polled, not so sure... but this allow that the entery 82 bytes recived get in a single char array.
The new code is this one:
include the mbed library with this snippet
#include "mbed.h" #include "BufferedSerial.h" // all these are optional const int BUFF_SIZE = 64; const int TX_MULTIP = 8; const char* SEN1 = "S1"; const char* SEN2 = "S2"; Serial pc(USBTX, USBRX); // USART2 BufferedSerial fuelR1(PA_9, PA_10, BUFF_SIZE, TX_MULTIP, SEN2); // USART1 BufferedSerial fuelR2(PB_10, PB_11, BUFF_SIZE, TX_MULTIP, SEN2); // USART3 DigitalOut myled(LED1); int main() { pc.baud(38400); fuelR1.baud(19200); fuelR2.baud(19200); while(1) { if (fuelR1.readable()) { wait_ms(10); pc.printf("SENSOR1: "); while(fuelR1.readable()) { char incoming = fuelR1.getc(); pc.putc(incoming); } pc.printf("\r\n"); } if (fuelR2.readable()) { wait_ms(10); pc.printf("SENSOR2: "); while(fuelR2.readable()) { char incoming = fuelR2.getc(); pc.putc(incoming); } pc.printf("\r\n"); } myled = !myled; wait_ms(10); } }
At my point of view (read: guessing), the Issue could be that the USART4, 5, 6, 7, 8 does not support Timeout Interrupt. It would be great to have another point of view to confirm.
Best regards.posted by 01 Jun 2016 | https://os.mbed.com/questions/69133/Using-multiple-BufferedSerial-on-Nucleo-/ | CC-MAIN-2020-24 | refinedweb | 991 | 58.89 |
I am converting a console IO program to a file IO program. The program worked perfectly as a console IO. I thought I made the appropriate changes to the program. It compiles, and when I run it output does go to my output text file, but the output is the same as if the input text file was blank. No matter what I do to the input text file the output text file is the same, so somehow my program is not reading it. I know that I spelled the input file name correctly when opening it in the program. Here is the program, thanks for any suggestions.
#include <fstream> using std::ifstream; using std::ofstream; using std::endl; int main() { ifstream inStream; ofstream outStream; inStream.open("infile.txt"); outStream.open("output.txt"); int avgRain[12], currentRain[12], x, y, z, r; outStream << "Please enter the average rainfall (to the nearest inch), starting with January, " << endl; outStream << "then February, then March, etc. Make sure to press enter after every month." << endl; for (x = 0; x < 12; x++) // x used to take exactly 12 inputs { inStream >> avgRain[x]; outStream << endl; } outStream << "What is numeral of the current month? (Jan is 1, Oct is 10, etc)" << endl << endl; inStream >> y; outStream << endl; if (y > 1) // This converts y to variable z. z accounts for the array going from 0 - 11 z = (y - 2);// rather than 1 - 12 and represents the previous month number in the array currentRain else if (y == 1) z = 11; else z = 10; outStream << "Please enter the amount of rain (to the nearest inch) that fell " << endl; outStream << "last month. Then enter the amount that fell the month before " << endl; outStream << "that. Continue until you have entered an amount for the last 12 " << endl; outStream << "months. Press enter after every measurement." << endl; int m = 0; while (m < 12) // m is used to make sure the while statement is executed exactly 12 times { if (z > 0) { inStream >> r; // r is the last recorded rain measurement for any month z outStream << endl; currentRain[z] = r; z--; } else { inStream >> r; outStream << endl; currentRain[0] = r; z = 11; } m++; } char results = 'g'; // results is the variable that determines how the data is represented outStream << endl; // and it is initialized to g (graph) while ((results == 'g') || (results == 'G') || (results == 'c') || (results == 'C')) { outStream << "Enter g to see the results graphically or c to see a chart. Or press any " << endl; outStream << "other key to quit." << endl << endl << endl; inStream >> results; if ((results == 'c') || (results == 'C')) { outStream << "Month__Average Rainfall__Previous Recorded Rainfall__PRF Deviation From Average" << endl; x = 0; while (x < 12) { outStream << x + 1; outStream << " "; outStream << avgRain[x]; outStream << " "; outStream << currentRain[x]; outStream << " "; outStream << currentRain[x] - avgRain[x] << endl; x++; } } if ((results == 'g') || (results == 'G')) { outStream << endl << endl << endl; x = 0; while ((x < 12) && (x >= 0)) { outStream << (x + 1) << " "; int g = avgRain[x]; // g is initialized to the value of any given x index in while (g > 0) // the avgRain array { outStream << "*"; g--; } outStream << endl; outStream << (x + 1) << " "; int h = currentRain[x]; // h is similar to g except used for the currentRain array while (h > 0) { outStream << "*"; h--; } outStream << endl << endl; x++; } outStream << "The top line indicates the average rainfall; bottom indicates the last " << endl; outStream << "recorded measure for that month. Every * represents 1 inch." << endl << endl << endl; } } inStream.close(); outStream.close(); } | https://www.daniweb.com/programming/software-development/threads/265469/program-not-recognizing-input-file | CC-MAIN-2017-43 | refinedweb | 556 | 62.61 |
Internationalize a Python application
This page explains step by step how to add support for translations in a Python application for Maemo.
There are already some tutorials online about how to internationalize (i18n) Python applications, but I find them difficult to follow and they lack some needed code and final tricks to make everything work fine.
To support i18n we need to accomplish 5 tasks:
- Define correctly a function '
_()' that translates strings
- Mark the strings in the code with that function
- Generate a template for the translators
- Add translations
- Include the translations in the installation
[edit] The overall process
From the source code, using a command line tool, we will generate a "
.pot" file. It is plain text file containing all strings that need translation in the project. This
.pot file only needs to be generated/recreated when the strings change in the code (and not in every build!). There is only one
.pot file per project.
Then, from the
.pot files and using another command line tool, we will generate the
.po files for each language. There is one
.po file per language, and it is the file that the translators need to complete. Both
.pot and all
.po files should be committed in the repository.
But once your program is running, it doesn't use
.po files directly, but a binary (compiled) version of them: the
.mo files. These
.mo files must be re-created on build time (when creating the package) and installed in the right location in the system. These are generated files, so don't commit them to the repository.
From the code point of view, you just need to call few functions to tell gettext where are the translation files, what language do you want to use (usually the locale of the environment), and then it will use its implementation to find the right string.
Ok, this is what we need to do. Let's code.
[edit] Configure gettext Define the '_()' function
If you don't care too much about the details, just copy this i18n.py file in your src/ directory (change the APP_NAME variable there!), or copy the code block below into a file i18n.py:
# -*- coding: utf-8 -*- import os, sys import locale import gettext # Change this variable to your app name! # The translation files will be under # @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo APP_NAME = "SleepAnalyser" # This is ok for maemo. Not sure in a regular desktop: #APP_DIR = os.path.join (sys.prefix, 'share') LOCALE_DIR = os.path.join(APP_DIR, 'i18n') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/ # Now we need to choose the language. We will provide a list, and gettext # will use the first translation available in the list # # In maemo it is in the LANG environment variable # (on desktop is usually LANGUAGES) DEFAULT_LANGUAGES = os.environ.get('LANG', '').split(':') DEFAULT_LANGUAGES += ['en_US'] lc, encoding = locale.getdefaultlocale() if lc: languages = [lc] # Concat all languages (env + default locale), # and here we have the languages and location of the translations languages += DEFAULT_LANGUAGES mo_location = LOCALE_DIR # Lets tell those details to gettext # (nothing to change here for you) gettext.install(True, localedir=None, unicode=1) gettext.find(APP_NAME, mo_location) gettext.textdomain (APP_NAME) gettext.bind_textdomain_codeset(APP_NAME, "UTF-8") language = gettext.translation(APP_NAME, mo_location, languages=languages, fallback=True)
And in every .py file that needs to translate any string, add these lines at the top:
import i18n _ = i18n.language.ugettext #use ugettext instead of getttext to avoid unicode errors
Done. If you are curious about what is going on there, the file has plenty of comments explaining every line.
[edit] Mark strings for i18n
This is one of the easiest parts. Browse the source code files that show something on the screen, and wrap the visible strings (window titles, dialog titles, notifications, labels, button labels and so on) with the '
_()' function.
For example:
# import the _() function! import i18n _ = i18n.language.gettext class Example (hildon.StackableWindow): def __init__ (self): hildon.StackableWindow.__init__ (self) self.set_title ( _("All music") ) <------- ADD THIS!
[edit] Generate template for the translators
Create a po folder in your project (usually at the same level as src/) and run the following command from the top directory of your project. You can do this inside or outside Scratchbox, there is no difference. Don't forget to replace PROJECTNAME with the name of your project.
xgettext --language=Python --keyword=_ --output=po/PROJECTNAME.pot `find . -name "*.py"`
It will parse files, written in Python, looking for strings marked with the keyword (function name) '_' and saving the output in a file called '
po/PROJECTNAME.pot'. The list of files is the last argument. I like to use "find", but you can manually put a list of files there.
That command will generate the
.pot file. Easy, isn't it?
If you get the error "xgettext: Non-ASCII character at...", try to add the parameter "--from-code=UTF-8" to the command:
xgettext --language=Python --keyword=_ --output=po/PROJECTNAME.pot --from-code=UTF-8 `find . -name "*.py"`
[edit] How to add translations
Now you want to get a translation in an specific language. You need to generate a
.po for it.
There are several ways to do it. I suggest to do it the easy way with poEdit:
[edit] With poEdit
Poedit is cross-platform gettext catalogs (.po files) editor. For more information, see its website. Just start it and generate a new catalog from the generated .pot file. In the option window you can select the translated language, your name, email address and so on. This is useful, so others know who created this translation.
Now you can start to translate all the text. If you modify your application and generate a new .pot file, you can easily import it. It will use all the existing translation and add the new/modified strings. If you changed the charset before like me, you will have to select it again. Every time you save the file, poEdit will generate a .mo file. You can use it for testing the new translation.
[edit] Manual way
Go to the
po/ folder and run this command (again, inside/outside scratchbox doesn't matter):
msginit --input=PROJECTNAME.pot --locale=LOCALE
For instance, if I want a
.po file for the Spanish translation of my project Mussorgsky, I write:
msginit --input=mussorgsky.pot --locale=es_ES
It will generate a file "
es.po" and translators can/must work on that file.
IMPORTANT: by default the generated
.po file declares its charset as ASCII. This means that translations with non-ascii characters will provoke an error in the program. To solve this, set the charset to '
utf-8':
"Language-Team: Spanish\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" <--- THIS MUST BE UTF-8
If you don't know the locale of a language, can check or people.w3.org/rishida/utils/subtags.
[edit] Include translations in your installation
Here again are several ways of doing it. I suggest to do it the automatic way as it is way easier if you have scratchbox.
[edit] Automatic way
If you already have the .tar.gz file, then you already have the structure with the files. Just unpack the .tar.gz file into a folder. If you have to pack it for the first time, MohammadAG has a good page about how to generate the needed files: User:Mohammad7410/Packaging
Now you will have to add some basic lines to the debian/rules file.Under the line with "install: build" should be many lines with "
mkdir" and "
cp -a". After the last one of them, add those two lines:
#compile language files with msgfmt msgfmt src/opt/PROJECTNAME/i18n/de.po --output-file debian/PROJECTNAME/opt/PROJECTNAME/i18n/de/LC_MESSAGES/PROJECTNAME.mo
This will tell the autobuilder to generate the .mo files. You will need a line like that for every language! Don't forget to adapt the file paths. In the example the .mo files are in the sub folder i18n/de/LC_MESSAGES/
[edit] Python way
This part is more tricky, because it depends on your build system. I'll explain how it goes with the common python 'distutils' (what makes the usual
python setup.py install command work). In distutils all the magic happens in the
setup.py file.
First of all, if in the previous steps you have added the
i18n.py file to your source tree, don't forget to include it in your
data_files list!
Then, copy to the root folder of your project the file msgfmt.py. It is a program that translates the .po files into the binary .mo files that the application needs.
In your
setup.py file you need to add all this code. It "overloads" the default 'build' and 'install' instructions to include the translations in the process. Now in 'build' time it will generate the .mo files (using the
msgfmt.py we added just now), and in 'install' time it will include the '
.mo' files in the
data_files list. The code is copied from this a setup.py file.
from distutils.core import setup from distutils import cmd from distutils.command.install_data import install_data as _install_data from distutils.command.build import build as _build import msgfmt import os
This command compiles every
.po file under the
po/ folder into a
.mo (the
.mo files will be under
build/locale/)
class build_trans(cmd.Command): description = 'Compile .po files into .mo files' def initialize_options(self): pass def finalize_options(self): pass def run(self): po_dir = os.path.join(os.path.dirname(os.curdir), 'po') for path, names, filenames in os.walk(po_dir): for f in filenames: if f.endswith('.po'): lang = f[:-3] src = os.path.join(path, f) dest_path = os.path.join('build', 'locale', lang, 'LC_MESSAGES') dest = os.path.join(dest_path, 'mussorgsky.mo') if not os.path.exists(dest_path): os.makedirs(dest_path) if not os.path.exists(dest): print 'Compiling %s' % src msgfmt.make(src, dest) else: src_mtime = os.stat(src)[8] dest_mtime = os.stat(dest)[8] if src_mtime > dest_mtime: print 'Compiling %s' % src msgfmt.make(src, dest)
Now we append the previous command to the 'build' command.
class build(_build): sub_commands = _build.sub_commands + [('build_trans', None)] def run(self): _build.run(self)
Installation time: put every
.mo file under
build/locale in the
data_files list (the list of things to be installed) and call the default 'install' operation
class install_data(_install_data): def run(self): for lang in os.listdir('build/locale/'): lang_dir = os.path.join('share', 'locale', lang, 'LC_MESSAGES') lang_file = os.path.join('build', 'locale', lang, 'LC_MESSAGES', 'mussorgsky.mo') self.data_files.append( (lang_dir, [lang_file]) ) _install_data.run(self)
Finally, add the new commands in distutils...
cmdclass = { 'build': build, 'build_trans': build_trans, 'install_data': install_data, }
And don't forget to add this in your setup function, in the
setup.py
setup(name = 'your project', ... license = 'GPL v2 or later', data_files = DATA, scripts = SCRIPTS, cmdclass = cmdclass <----- DON'T FORGET THIS )
Ok, now everything should be ready. If you run
python2.5 setup.py build
the terminal will print things like
compiling es.po compiling de.po ...
Usually
dpkg-buildpackage uses
python2.5 setup.py build and
install, so everything should work out-of-the-box with your previous package configuration.
Feel free to complete/correct this wiki page with your own experience.
- This page was last modified on 5 April 2013, at 21:17.
- This page has been accessed 26,850 times. | http://wiki.maemo.org/How_to_Internationalize_python_apps | CC-MAIN-2015-40 | refinedweb | 1,903 | 60.72 |
NOTE: In order to run the demo, you must have the PDC 2001 release of Visual Studio. NET otherwise you won't have the correct system dlls. You can still download the source and build it.
After writing my first article on loading types at runtime in mid-December I’ve since started a re-write of my type interface (after seeing a fatal flaw in my design). In doing so I also realized that the code to load my new types looked nearly identical to what I used before; in fact, the code for most people’s use would probably look the same.
So I broke it out into its own class, and created a fancy splash screen to go with it.
When you extract the source you will have a setup.bat in the root directory, run this to setup the strong name key files (snk). You may have to use Visual Studio's provided command line shortcut to ensure that your path is setup correctly. In order for the project to work you must sign your assemblies (though you probably don't have to sign the main executable I do because it doesn't take much work to do, and gives added peace of mind to your users).
Once you compile all three projects place the resulting DLLs in the directory with the main executable, you should only need to copy the dll from the StandardTypes project. You can now run the program, and you should see the splash screen come up, load a type, then disappear.
The type loader will be doing the grunt work for you, all you have to do is tie into it via the TypeLoading event, and optionally the TypeLoaded event.
TypeLoading
TypeLoaded
public TypeCollection Types { get; set; }
This is the collection of types that have been loaded via the TypeLoading event. It is a strongly typed Collection of Type objects (generated via Microsoft's Collection Generator).
public event TypeLoadingEventHandler TypeLoading;
public delegate void TypeLoadingEventHandler(object sender,
TypeLoadingEventArgs e);
This event will be fired for every type that the class encounters while it is loading. The TypeLoading property contains the Type object in question. Set the Cancel property to true to not load the type, set it to false to load the type.
Cancel
public event TypeLoadedEventHandler TypeLoaded;
public delegate void TypeLoadedEventHandler(object sender,
TypeLoadedEventArgs e);
This event will be fired for every type that was successfully loaded by the system. That is, it'll be fired for every type where the TypeLoading event's Cancel property was false when it returned. The TypeLoaded property contains the Type object that was loaded. This event is provided only as a service and is not required to be listened to.
public void LoadTypesFromDirectory(string path);
public void LoadTypesFromDirectory(string path, string searchPattern);
public void LoadTypesFromDirectory(string path,
string searchPattern, bool recurseSubdirectories);
If not specified searchPattern will default to "*.dll" and recurseSubdirectories will be false.
searchPattern
recurseSubdirectories
This method is the whole purpose of the class to begin with. It will search a directory for types, and notify the caller when it finds some via the TypeLoading event.
The path should be suitable for the System.IO.Directory class, and the searchPattern should work with the System.IO.Directory.GetFiles method.
System.IO.Directory
System.IO.Directory.GetFiles
Each of the overloads in the end calls down to a protected method, LoadTypesFromDirectoryRecursive.
LoadTypesFromDirectoryRecursive
None of these methods clears the collection of types.
void Clear();
This method removes all Types from the TypeCollection.
TypeCollection
public static bool TypeImplementsInterface(Type type, Type interfaceType);
Returns true if the given type implements the interface name passed. This currently goes through the list of all types implemented and compares the full name of both types. Since its possible for two different assemblies to have the same namespace, its recommended that you prefix all namespaces with your company name.
The splash screen has 2 customizable parts to it
The bitmap is a 352x72 pixel image displayed on the top portion of the window.
The Type Listing displays all the types that have been successfully loaded by the program. In this case the listing shows a bitmap and a name gotten from the type.
public void ShowSplashScreen()
{
SplashScreen splash = new SplashScreen();
TypeCollection typesLoaded = splash.DoSplash();
// Use the typeCollection in your main program
}
Simple eh? Not quite that simple though, you have to modify the source to the splash screen, just a bit so that it looks for the types you want to use in your program. The method you need to change is loader_TypeLoading. It currently shows an example of how to look for an interface being implemented by a class.
loader_TypeLoading
All the work is done in the events for the TypeLoader object.
In the TypeLoading event it does a compare on the type to see if it implements the IType interface from the Types namespace. The compare is done using TypeLoader's only static method, TypeImplementsInterface.
IType
TypeLoader'
TypeImplementsInterface
In the TypeLoaded event it gets the picture from the IType, adds it to the imagelist; then adds it to the ListView. Pretty simple, and gives the effect I was looking for.
ListView
If you look through the code you'll see that my root namespace is Takklesoft.CollectorsDatabase. No I didn't forget to change it, this is code I've ripped from my current project. So if I ever get it released you'll know how I did the splash screen.
Takklesoft.CollectorsDatabase
As always any questions or comments, leave them below or e-mail me.
The code I provide here is free for anyone to use, I don't require anything in return, but a mention in some documents or an about box would be nice
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Jonny Newman
Liverpool, UK
Sonork: 16257:Jonny Newman
MSN Msngr: jonathann4@hotmail.com
ICQ: 37606329
and now.....
nonny@nonny.com
I'm out there! Feel free to contact me about anything.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/1712/TypeLoader-for-NET | CC-MAIN-2016-18 | refinedweb | 1,065 | 62.17 |
Opened 13 years ago
Closed 7 years ago
#5335 closed New feature (duplicate)
Add an append method to ErrorDict
Description
Custom Validation: If you need to access other fields, you
need to overwrite form.clean(). If you want to have
the error message near a widget (not all), you need to
modify the _error dict of the form.
To make this more user friendly I wrote a small patch:
ErrorDict.append(fieldname, message)
Doc patch included.
Attachments (6)
Change History (39)
Changed 13 years ago by
comment:1 Changed 13 years ago by
comment:2 Changed 13 years ago by
Thank you brosner, for looking at this patch. But I can't use clean_FIELD():
if clean_FIELD() requires to look at FIELD2, the dict self.cleaned_data does not contain
FIELD2. If you need the cleaned values of two fields for validation, you can not use clean_FIELD().
Nevertheless I want the error message to be near the field FIELD.
Here is how I use the patch:
def clean(self): parent=self.cleaned_data.get("parent") name=self.cleaned_data.get("name") if ....: # Needs Django Patch #5335 self.errors.append("name", u'...') return self.cleaned_data
Of course I could do this without the patch, too:
errorlist=self.errors.get(name) if errorlist==None: errorlist=ErrorList() self.errors[name]=errorlist errorlist.append(message)
But that's too much code, I don't want to repeat. Maybe the documentation should
be updated, too.
comment:3 Changed 13 years ago by
Changed 13 years ago by
comment:4 Changed 13 years ago by
Added doctests
comment:5 Changed 13 years ago by
comment:6 Changed 12 years ago by
comment:7 Changed 12 years ago by
comment:8 Changed 12 years ago by
Related django snippet:
comment:9 Changed 12 years ago by
comment:10 Changed 12 years ago by
Attached patch implements
ErrorDict as a
defaultdict (can't inherit directly from
defaultdict since it's new in 2.5 or 2.4, can't remember, but definitely not in 2.3). It would be helpful if someone could review the documentation part of the patch since I'm not a native english speaker.
Changed 12 years ago by
updated patch, tests and documentation
comment:11 Changed 12 years ago by
The docs look ok by me, 2 small things though, instead of
self.has_key(field) do
field in self . Also there's no need to use super() for setitem since it isn't overode in the subclass, you can actually just use setattr(self, field, []).
Changed 12 years ago by
updated patch using setdefault
comment:12 Changed 12 years ago by
Even better, I used
setdefault so in the end is a one-line patch.
comment:13 Changed 12 years ago by
There's actually a slight disconnect between the docs and the code, the docs say an ErrorList is created, but getitem adds a list([]), I think an ErrorList would be the correct behavior.
Changed 12 years ago by
Fixed patch, create an
ErrorList instead of a simple list
comment:14 Changed 11 years ago by
According to Version1.1Features seems to be in scope for 1.1?
comment:15 Changed 11 years ago by
Bumping to 1.2. For the record, I have to do this all the time and I'd like to see something like this, but I'm not entirely sold on this way yet.
comment:16 Changed 11 years ago by
Definitely. Often views need to perform more involved steps *after* the form is validated; which may fail, and ultimately mean there was a problem with what was entered in the form.
There needs to be an easy, documented, encouraged way of appending errors to NON_FIELD_ERRORS as well as to specific fields; post-validation (ie from the view).
comment:17 Changed 11 years ago by
This approach is in conflict with #4752 ([6142]).
The method would either have to be on the Form class (not entirely insane). Another way how to propagate your error onto a field is using ComplexValidators present in model-validation branch, that way you don't have to worry about the internals of ErrorDict...
comment:18 Changed 10 years ago by
comment:19 Changed 10 years ago by
This a a feature, so I'm bumping it to 1.3. Sorry. I'm assigning it to myself it to increase the chances that I'll remember it for the next cycle.
comment:20 Changed 10 years ago by
comment:21 Changed 9 years ago by
Looks like Joseph didn't remember :-( This is a feature, so will have to wait again. Patch also needs updating (especially to use unittest rather than doctests).
comment:22 Changed 9 years ago by
Changed 9 years ago by
Reviewed patch with unittests
comment:23 Changed 9 years ago by
Thanks a lot for updating the patch. I showed it to Alex and he wondered if you could write a test that verifies that doing
errors['foo'] without actually altering it doesn't cause any problem?
comment:24 Changed 9 years ago by
comment:25 Changed 9 years ago by
Current patch (form_error_append_r16741.diff) will auto-create an
ErrorList() object for a field's error list even if the including form has over-ridden the form's error class (). If we are going to add this (and it would be nice) it needs to be done in a way that will use the form's custom error class if it has been defined. This case should also be tested, in a test similar to:
comment:26 Changed 9 years ago by
Milestone 1.4 deleted
comment:27 Changed 7 years ago by
comment:28 Changed 7 years ago by
Actually there is merit in making
ErrorDict inherit from
defaultdict.
PR
comment:29 Changed 7 years ago by
Looping through defaultdicts in templates can cause problems. See #16335. I believe the pull request 1481 would stop the following template snippet from working.
<ul> {% for field, errors in form.errors.items %} <li>{{ field }}: {{errors}}</li> {% endfor %} </ul>
I realise it's a slightly artificial example, and that usually you would use
{{ form.errors }}.
comment:30 Changed 7 years ago by
comment:31 Changed 7 years ago by
@alasdair: that looks like a nasty incompatibility with no obvious workaround.
The only reason I fixed this despite #20867 was so internally it wouldn't be needed to check if keys existed, it's clearly not worth breaking existing templates over this.
I think we should close this ticket as wontfix, especially now that another ticket addresses the main issue.
You can use the clean_FIELD() method validation hooks to get errors messages near fields. | https://code.djangoproject.com/ticket/5335 | CC-MAIN-2020-34 | refinedweb | 1,107 | 60.75 |
Nico Meyer782 Points
What the correct code? Got it working but challenge don't accept answer.
In this task we're going to write a simple function that takes two numbers and returns the remainder of dividing one number by the other.
Step 1: Declare a function named getRemainder that takes two parameters, a.
// Enter your code below func getRemainder(a value: Int, b divisor: Int) -> Int { return (value % divisor) }
1 Answer
andren28,359 Points
You have the local and external names of the parameters the wrong way around. The parameters are meant to be called
a and
b locally and
value and
divisor externally. Also it's not really necessary to wrap the equation is parenthesis, though it won't produce an error either.
If you fix the code like this:
func getRemainder(value a: Int, divisor b: Int) -> Int // Swapped local and external names { return a % b // Change names to account for the above change }
Then your code will pass task 1.
josh kinney1,576 Points
Why doesn't this pass the second part?
func getRemainder(value a: Int, divisor b: Int) -> Int { return a % b }
let result = getRemainder(a:10, b:3)
Nico Meyer782 Points
Nico Meyer782 Points
Thanks, that dit the trick. Appreciate the help | https://teamtreehouse.com/community/what-the-correct-code-got-it-working-but-challenge-dont-accept-answer | CC-MAIN-2019-35 | refinedweb | 209 | 61.87 |
JSF ManagedBean is a java class that can be accessed by the JSF page for retrieving the values of the UI fields.
Table of Contents
JSF ManagedBean
JSF Managed Bean can be created using
@ManagedBean annotation. If a name attribute is not specified after the
@ManagedBean annotation, it indicates that the name of the managed bean is the same as the class name. If the name is specified then it is a managed bean with the name specified in the attribute.
There are other annotations specifying the scope attributes which can be used with the managed bean.
@SessionScoped: Indicates that the bean is valid for the whole session
@RequestScoped: The bean is valid for the http request.
@ApplicationScoped: Bean is valid as long as the web application is valid.
Let’s now create a managed bean named Car.java as shown below.
package com.journaldev.jsf.beans; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class Car { private String cname = "Santro"; private String color = "blue"; private String Id = "S1"; private String model = "S-800"; private String regno = "S4567"; private String description; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRegno() { return regno; } public void setRegno(String regno) { this.regno = regno; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getId() { return Id; } public void setId(String Id) { this.Id = Id; } }
In the above code, since we have not used any name attribute after
@ManagedBean annotation, a managed bean with the name Car is created.
@SessionScope is used to indicate that the bean is valid for the whole session. The Car bean basically contains the fields of the car like color, id, description, model and regno along with the getter and setter methods for these.
Now create
viewdetails.xhtml which is the view for the details of the car.
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <h:head> <title>Car Details</title> </h:head> <h:body> Car Id:#{car.id} <br> <br> Car Name:#{car.cname} <br> <br> Car color:#{car.color} <br> <br> Car Model:#{car.model} <br> <br> Car Registration Number:#{car.regno} </h:body> </html>
Now run the application and it should produce the following output in the browser.
Injecting JSF Managed Bean
The
@ManagedProperty annotation enables us to inject a managed bean into another managed bean. Let’s look into an example of how to inject the managed bean.
Create the managed bean named Car_gen.java as below.
package com.journaldev.jsf.beans; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; @ManagedBean(name = "car_gen", eager = true) @RequestScoped public class Car_gen { @ManagedProperty(value = "#{alto_car}") private Alto alto; private String description; public Car_gen() { } public String getDescription() { description = alto.getDescription(); return description; } public void setDescription(String description) { this.description = description; } public Alto getAlto() { return alto; } public void setAlto(Alto alto) { this.alto = alto; } }
Here the bean named alto_car is injected with the
@ManagedProperty annotation. In the getter method we call the getDescription method of alto to fetch the value from the alto managed bean.
The #{alto_car} indicates that the managed bean named alto_car is injected as we have specified in the name attribute of
@ManagedBean annotation in
Alto.java class.
The “eager=true” indicates that the managed bean is created before it is requested for the first time.
Next create the bean named Alto.java as shown below.
package com.journaldev.jsf.beans; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean(name = "alto_car", eager = true) @RequestScoped public class Alto { private String description = "Alto has power windows"; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
This managed bean contains the description field with the value initialised and has getter and setter methods.
Now we create a JSF page named
car_gen.xhtml to bind this.
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <h:head> <title>Alto Description</title> </h:head> <h:body> #{car_gen.description} </h:body> </html>
We fetch the description value from the
car_gen bean which further fetches the value from alto bean. This is possible because the Alto bean is being injected into the generic
car_gen bean.
Upon running the code, we can see the JSF page rendering the description of alto car in the browser.
The final project structure is shown below.
You can download the project from below link and play around with it to learn more.
Good One, good Job!!! Keep it up!!
Thank you for your tutorial,
I understand the point of scopes, but i don’t like the Alto example, just because you can call the function with
#{alto_car.description} and it will give us the same description.
Anyhow, thanks again for your tutorial and time.
Cheers | https://www.journaldev.com/6881/jsf-managedbean-managedproperty | CC-MAIN-2021-25 | refinedweb | 847 | 51.04 |
Hello and welcome to This Week in .NET — a lovingly curated collection of links relating to what’s new and exciting in the world of .NET. The complete list is tagged dotnetweekly. (Don’t forget to check out our weekly JavaScript roundup too!)
Software
- Dmitri Nesteruk and the team over at JetBrains announce the release of ReSharper C++
- Paul Stovell shares a little utility (ServiceBouncer) to help when developing services and constantly needing to restart them.
- Roy Primrose shares a little utility that makes it easier to rename namespaces in your .NET projects.
- The .NET Team and the Internet Explorer Team released a few security updates last week, be sure you stay updated.
- Scott Guthrie announces the release of Premium Storage for Azure to the General Public.
Information
- Gabriel Schenker continues his series of posts looking at CQRS with a look at applying its practices to a real world problem. Also check out Gabriel’s topic on the concepts and application of Domain Driven Design.
- Erik Dietrich continues his TDD video series looking at building tests with SpecFlow.
- Jason Jarrett looks at where DefinitelyTyped is now in today’s web and its impact.
- Tugberk Ugurlu discusses how ASP.NET 5 applications are structured and how IIS Express and Azure Web App hosting utilizes those applications.
- Dave Voyles kicks off a series of posts looking at video in HTML5 using Azure Media Services and providing an overview of the various supported formats.
- Eric Lippert continues his look at the use of the unchecked keyword in C# and answers some of the questions from the first post on the subject.
- James Michael Hare shares his solution to his recent little puzzler, Largest Puddle on a Bar Chart. Be sure to check out James’ latest little wonder, Status Using Statements in C# 6 too.
- Sam Brand shares the results of the Stack Exchange Developer Survey from 2015 giving insight into our industry.
- John Sonmez discusses a real world example where comments in code are not as clear as good expressive code could be.
- Vincent Maverick S. Durano highlights the release of ‘ASP.NET MVC Succinctly’ by Nick Harrison, which is a free e-boook from Syncfusion (registration required).
- Wriju Ghosh takes a look at DocumentDB walking through two of the most common use cases.
- Robert MacLean takes a look at the nameof call that allows you to get the names of members at compile time without resorting to using reflection.
- Dan Wahlin discusses the use of TypeScript and how you can go about extending interfaces and classes with new methods, as well as looking at how interfaces work in TypeScript.
- Andrew Siemer takes a look at putting proxies and gateways in front of API services to help scale and protect your services.
- Brij Bhushan Mishra takes a look at the concept and use of a View Component in ASP.NET MVC 5.
- Nathan Evans shares a simple looking module for wrapping System.Xml.Linq functionality to provide an expressive way of writing XML content in F#.
- Joe Mayo shares a look at Custom Window Layouts in Visual Studio 2015 which makes it easier for developers to place their tool windows in the correct locations and keep them there! (you know the pain we are talking about!)
- Jeremy Likness shares a couple of cheat sheets for AngularJS and TypeScript.
- Cellfish highlights a useful feature of the Visual Studio Debugger that allows you to print messages when a breakpoint hits instead of halting the flow.
I hope you enjoyed this week’s links. Which ones caught your attention?
Please PM me if you have anything of interest for the next issue, and happy reading! - cpradio | https://www.sitepoint.com/community/t/this-week-in-net-20-april-2015/147426 | CC-MAIN-2020-29 | refinedweb | 610 | 63.9 |
New Product
Your technology certification is waiting. Enroll in Cloud Class ®
Submit
Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.
Dim wreq As HttpWebRequest
Dim wres As HttpWebResponse
Dim str as string =""
wreq = HttpWebRequest.Create(str)
wreq.Method = "Post"
wres = wreq.GetResponse
Dim sr As StreamReader
sr = New StreamReader(wres.GetResponseStream)
str = sr.ReadToEnd
str = replacetags(str) 'This is a function which replaces all html tags and return a string. this part is correct as it displayes correct thing in webbrowser.
webbrowser1.DocumentText = str
webbrowser1.update()
Dim theElementCollection As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("Input") 'HERE I AM GETTING INVALID TYPE CAST EXCEPTION be more like:
Dim theElementCollection As HtmlElementCollection = WebBrowser1.Document.GetEl
For Each element As Object In theElementCollection
Console.WriteLine(element.
Next element
That code will write the object types to the Output window. You can use that type name to get the correct cast for the "element" object.
Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.
Open in new window
2) I like to use the Microsoft.mshtml namespace to parse the HTML, which would require the WebBrowser.Document.DomDoc
3) Does the <input> element have an ID?
############ Due to nested frames and few elements in webpage that really sucks to load, cracks the software... creates huge delay..
2) I like to use the Microsoft.mshtml namespace to parse the HTML, which would require the WebBrowser.Document.DomDoc
########### Y cant we do it by Regex?
3) Does the <input> element have an ID?
########## its just a sample code... ya they have...
This code says to me that what you are doing should work.
HtmlDocument..GetElementsB
Dim test As Object = WebBrowser1.Document.GetEl
Dim typeName As String = test.GetType().Name
i used a dead try catch finally block..
try
Dim theElementCollection As HtmlElementCollection = WebBrowser1.Document.GetEl
a:
For Each curElement As HtmlElement In theElementCollection
**************************
catch ex as exception
goto a
end try
he he he.. its working..
Dim typeName As String = test.GetType().Name
mate can u please explain me this further.. how to use this?
I use WebBrowser.ReadyState a lot, and I have seen a few problems using it, but it is usually a web page problem. | https://www.experts-exchange.com/questions/24335302/Web-browser-manipulation.html | CC-MAIN-2018-22 | refinedweb | 384 | 53.37 |
I am started with my first Dapper Dal project.
I have three projects: - Website (MVC) - DataLayer (Dapper) - Model (Poco Classes)
I want to add validation to my model but i also want to use clean poco classes for my datalayer. My datalayer use dapper to map my poco classes to the database.
I have searched the internet but i can't find a good answer.
My question is: Where do i add my validation? - In a seppetated project with classes that extend my poco classes or is there a different way?
If you want a clean separation between your DAL classes and your MVC classes, then you can do just that by, for instance, using ViewModels in your MVC-project. The ViewModel would have the properties and validations that works best with what you are presenting in the browser. Your controller would be responsible for mapping the data between the DAL classes and the ViewModels. Automapper is a very good tool for just that.
It would look a bit like the following:
DAL:
public class MyDapperClass { public int Id { get; set; } public string SomeProperty { get; set; } }
ViewModel:
public class MyViewModelClass { public int Id { get; set; } [StringLength(50),Required] public string SomeProperty { get; set; } }
Controller:
// using AutoMapper; public class MyController : Controller { public MyController() { // Set up AutoMapper to be able to map your class Mapper.CreateMap<MyDapperClass, MyViewModelClass>(); } public ActionResult MyAction() { var dalObject = DAL.GetObject(); var viewModel = Mapper.Map<MyViewModelClass>(dalObject); return View(viewModel); } } | https://dapper-tutorial.net/knowledge-base/25240087/dapper-and-dal-where-must-i-place-my-validation | CC-MAIN-2021-10 | refinedweb | 242 | 54.73 |
I am trying to create a 3D bar graph with Matplotlib 1.2.0 and Python 2.7.3. I followed the advice in and plotted the bar one by one, but I am still getting rendering problems (i.e., bars on top of each other).
Moreover, I get the following when I invoke my code:
/usr/apps/python/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py:1476: RuntimeWarning: divide by zero encountered in divide for n in normals])
/usr/apps/python/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py:1476: RuntimeWarning: invalid value encountered in divide for n in normals])
My questions:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as colors
import matplotlib.cm as cmx
# my data
dat = [2.31778665482167e-310, 0.006232785101850947, 0.0285075971030949, 0.0010248181570355695, 0.0048776795767614825, 0.02877090365176044, 0.002459331469834533, 0.0008594610645495889, 0.002919824084878003, 0.000968081117692596, 0.0, 0.0, 0.0319623949119874, 0.00568752311279771, 0.009994801469036968, 0.03248018520506219, 0.006686905726805326, 0.005987863156039365, 0.0072955095915350045, 0.005568911905473998, 0.0, 0.0, 0.0, 0.028483143996551524, 0.031030793902192794, 0.06125216053962635, 0.02935971973938871, 0.028507530280092265, 0.030112963748812088, 0.028293406731749605, 0.0, 0.0, 0.0, 0.0, 0.004510645022825792, 0.028998119822468988, 0.0013993630391143715, 0.0010726572949244424, 0.002288215944285159, 0.0006513973584945584, 0.0, 1.1625e-320, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.03148966953869102, 0.005215047563268979, 0.004491716298086729, 0.006010166308872446, 0.005186976949223524, 0.0, 0.0, 0.0, 0.0, 0.0, 1.107e-320, 0.02983657915729719, 0.028893006725328373, 0.030526067389954753, 0.028629390713739978, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0015217840289869456, 0.002751587509779179, 0.001413669523724954, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0024680339073824705, 0.0008254364860386303, 0.0, 0.0, 0.0, 9.965e-321, 1.15348834e-316, 2.3177866547513e-310, 0.0, 0.0, 0.0, 0.002621588539481613, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.41e-321, 1.15348834e-316, 2.3177866547513e-310]
dat = np.reshape(dat,[10,10],order='F')
lx = len(dat[0])
ly = len(dat[:,0])
n = lx*ly
# generate colors
cm = plt.get_cmap('jet')
vv = range(len(dat))
cNorm = colors.Normalize(vmin=0, vmax=vv[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
colorVals = [scalarMap.to_rgba(i) for i in range(ly)]
# generate plot data
xpos = np.arange(0,lx,1)
ypos = np.arange(0,ly,1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(n)
dx = 0.5*np.ones_like(zpos)
dy = dx.copy()
dz = dat.flatten()
cc = np.tile(range(lx), (ly,1))
cc = cc.T.flatten()
# generate plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
opacity = 1
for i in range(n):
ax.bar3d(xpos[i], ypos[i], zpos[i], dx[i], dy[i], dz[i],
color=colorVals[cc[i]], alpha=opacity, zsort='max')
plt.autoscale(enable=True, axis='both', tight=True)
plt.grid()
plt.show(block=False)
This isn't the answer that you are looking for, but I think that this might be a bug in matplotlib. I think that the same problem was encountered here. The problem was described as "intractable" according to the mplot3d FAQ.
But to me it doesn't seem intractable. You simple need to figure out which object is closer to the viewer and set the z-order accordingly. So, I think that the problem might just be a bug.
If I take the matplotlib 3D histogram example and just change "bins=4" to "bins=6" or a higher number, then I get the same "axes3d.py:1476: RuntimeWarning: invalid value encountered in divide / for n in normals])". Also, I can reproduce the wrong z-order of the bars (check out the tall guy near the front who jumps in front of his short friend):
The incorrect ordering of the bars seems linked to the divide by zero error, since the plots look just fine when I use a smaller number of bins.
Line 1476 in axes.py is:
shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5]) for n in normals])
Basically, I think it is trying to figure out the shading using the normal vectors to each face. But, one or more of the normal vectors is zero, which should not be the case. So, I think that this is just some bug in matplotlib that can probably be fixed by someone with more programming skills than myself.
The mplot3d FAQ is correct that MayaVI can be used if you want a better 3D engine. I used
from mayavi import mlab mlab.barchart(xpos,ypos,dz*100)
to generate a plot of your data:
I hope that this gets figured out soon. I would like to make some similar 3D barcharts in the near future. | https://codedump.io/share/xIh4v7R3fLvw/1/matplotlib-bar3d-clipping-problems | CC-MAIN-2017-04 | refinedweb | 820 | 77.03 |
Hi!
I'm new to Unity and am working on an endless runner platformer that changes the level from a list when the player reaches an "end point" of the previous level. I'm following this tutorial by Code Monkey ( ) where he creates prefabs that spawn after each other. I tried doing that but instead drawing different levels using a tile palette, saving them as a prefab, and then trying to spawn them. The result is 1 block from the tile palette and nothing else. I'm not sure how to explain any further but my problem is that my drawn level is gone and only one block is spawned from the prefab. Would really appreciate some help!
Picture of regular view:
Picture of prefab view:
Any other suggestions on how to proceed are much appreciated! As noted I'm not aware of any good practices but am eager to learn.
Answer by Dsaxni
·
Jul 22 at 08:57 AM
Might have figured out a solution. I created an empty prefab, created a grid and tilemap within it and used the previous tile palette in the prefab view. I had a LevelStart platform that is not a prefab which is the start area for the endless runner. Then I initiated the prefab level part with this code in an empty object:
public class LevelGenerator : MonoBehaviour
{
public Transform LevelPart_Start;
public Transform LevelPart_1;
private void Awake(){
Transform lastLevelPartTransform;
lastLevelPartTransform = SpawnLevelPart(LevelPart_Start.Find("EndPosition").position);
// can copy this part to create more clones
lastLevelPartTransform = SpawnLevelPart(lastLevelPartTransform.Find("EndPosition").position);
}
private Transform SpawnLevelPart(Vector3 spawnPosition){
Transform levelPartTransform = Instantiate(LevelPart_1, spawnPosition, Quaternion.identity);
return levelPartTransform;
}
}
The explanation might be a bit unclear but I hope it helps anyone else.
My 2D tiles have holes in them
0
Answers
Create prefab with tilemap
1
Answer
How can I Instantiate a Sprite into my 2D Scene?
1
Answer
Reusing tilemap segments
0
Answers
Is it possible to instantiate a prefabe on tilemap!?
0
Answers | https://answers.unity.com/questions/1753405/trouble-with-tilemaps-as-prefabs-for-2d-plattforme.html | CC-MAIN-2020-34 | refinedweb | 327 | 52.9 |
So – you’ve got the hang of React, and you’ve even built a little app. But after making your app look nice, you remember that you also need to make it work. And that’s when you start searching for form libraries.
First you look for tools to structure data and event flow. Then you shift focus to libraries which reduce repetition in form components. And while you’re at it, tools which validate user input would certainly help. Tools like react-forms and formsy-react and flux and redux and RxJS and as one redditor put it:
I’ve been evaluating a few frameworks out there. It’s been the bane of my existence for the past two weeks.
Wasn’t the whole idea that tools would save you time?
Why spend two weeks investigating when you could have implemented the most important part in three minutes? Its not even like you’d have to think that hard; all you have to do is follow this exercise:
Exercise 1 – Collecting user input
This is part two of my series on Raw React. If you’re new to React, start from part one. Otherwise, get the starter code from part one’s GitHub repository.
Before we move on to the exercise, let’s answer a quick revision question: If an element’s
props can take
string and
array values, can they also take a
function? Touch or hover your mouse over this box for the answer:
propsare called callback functions.
Gathering keystrokes from an
<input> element is accomplished by passing a callback function to its
onChange prop, like so:
React.createElement("input", { // The callback passed to `onChange` will be called when `value` should change onChange: function(syntheticEvent) { // Log new `value` to JavaScript console console.log(syntheticEvent.target.value) } })
But this exercise is titled collecting user input, not callback functions – so let’s collect the various changes from our
<input> elements. And what better component to manage changes to a
contact object than part one’s
ContactForm:
var ContactForm = React.createClass({ propTypes: { value: React.PropTypes.object.isRequired }, render: function() { return ( React.createElement('form', {className: 'ContactForm'}, React.createElement('input', { type: 'text', placeholder: 'Name (required)', value: this.props.value.name, }), React.createElement('input', { type: 'email', placeholder: 'Email', value: this.props.value.email, }), React.createElement('textarea', { placeholder: 'Description', value: this.props.value.description, }), React.createElement('button', {type: 'submit'}, "Add Contact") ) ) }, });
Just as an
<input> element displays its current
value and emits changes via its
onChange callback, we’d like our
ContactForm to display a
value (which it already does), and emit new
contact objects via an
onChange callback.
So, after modifying
ContactForm.propTypes appropriately:
propTypes: { value: React.PropTypes.object.isRequired, onChange: React.PropTypes.func.isRequired, }
And adding a
console.log to our
ContactView class to test our work:
React.createElement(ContactForm, { value: this.props.newContact, onChange: function(contact) { console.log(contact) }, })
Your task is to add a working
onChange prop to the
ContactForm class.
This will involve adding
onChange callbacks to the
<input> and
<textarea> elements. These callbacks call
ContactForm‘s own
onChange callback, emitting a copy of the existing
value with changes applied to the appropriate values. Your form element’s new
value is available through the passed in SyntheticEvent
target (see above example).
Once everything is working as expected, each keystroke in the contact form should emit a console message. You can see this in action with the below JSBin solution.
thisis has a different meaning within a nested
function!
Here is how you’d use
Object.assign in this exercise:
// Return a new `contact` with an updated `name` property var updated = Object.assign({}, this.props.value, {name: e.target.value})
Congratulations – you’ve now completed the most important part of your form! Of course when you’re building forms on your own, you’re not going to get the correct
propTypes handed to you on a platter; you’re either going to need to comb through the React documentation to find what works, or take a quick look at my React.js Cheatsheet. But I digress. Let’s move on and quickly implement the fun part of your form.
Get the PDF cheatsheet!
Exercise 2 – Displaying changes
Can you remember how we went about displaying new data in part one? All you need to do is create a new
ReactElement with the updated data, and pass it to
ReactDOM.render:
var rootElement = React.createElement(ContactView, newData) ReactDOM.render(rootElement, document.getElementById('react-app'))
The only problem being that the new data is currently only available to the
ContactView component:
var ContactView = React.createClass({ // ... render: function() { return React.createElement('div', {className: 'ContactView'}, // ... React.createElement(ContactForm, { value: this.props.newContact, onChange: function(contact) { /* * Our new `contact` is only available here */ }, }) }, }); /* * But we want to use our new `contact` here! */ ReactDOM.render( React.createElement(ContactView, { contacts: contacts, newContact: newContact }), document.getElementById('react-app') )
How would you access the new
contact from the application’s entry point? Using callbacks, of course!
Your task is to add an
onContactChange prop to the
ContactView component, and use this to display the latest changes.
Once complete, you should have a working form:
And now you know everything you need to know to build Ridiculously Simple Forms with React! So let’s talk about:
Why?
The first time I saw a form component with
value and
onChange props, I thought to myself: this is fucking stupid! Why should my form have a
value prop when the
<input> elements underneath it have
value props too? Isn’t that code duplication? Isn’t that failing to separate concerns? It felt anything but elegant, but here I am telling you to build forms that way — why?
React’s killer feature is that it helps us make user interfaces which are easy to reason about. But React can’t do this by itself; we need to help it out by making sure that a component’s
props tell us everything about it. This means that our form’s displayed data must all be available under its
value, and that changes must be emitted through callbacks — not hidden inside the form component’s state.
And the thing is — we wouldn’t be managing that state if we didn’t need to use it. Even if we were to find a way to move data from the
<input> components to where it is needed without passing it through
ContactForm‘s
value and
onChange props, there would still need to be some way of making that transfer happen.
In larger projects, all this wiring can make it a little harder to grok the bigger picture. In these cases, tools like Flux will help add structure to manage your complexity. But, if you’re just starting a new project, you don’t have any complexity to manage! So while our Ridiculously Simple Forms may not be particularly elegant, they are certainly incredibly simple:
valueprop). Nobody uses them though, or at least nobody should.
So now that we’ve decided we’re going to structure forms this way, lets spend a little time making them easier to work with. Starting with:
Instance methods and auto-binding
Did your solution to Exercise One use anonymous functions for
onChange callbacks, like mine?
var oldContact = this.props.value; var onChange = this.props.onChange; // ... React.createElement('input', { type: 'text', placeholder: 'Name (required)', value: this.props.value.name, onChange: function(e) { onChange(Object.assign({}, oldContact, {name: e.target.value})); }, }),
Ignoring the fact that JavaScript creates these anonymous functions anew every single time
render is called (which is sloooooow), defining handlers like this is a pain in the arse because we need a workaround to access
this. And given the number of event handlers our forms need, this isn’t just a small pain.
To avoid this, define your handlers as component instance methods by passing them to
React.createClass. React auto-binds instance methods, ensuring that
this always refers to your component instance. Even when used as callbacks:
var ContactForm = React.createClass({ propTypes: { // ... }, onNameInput: function(e) { this.props.onChange(Object.assign({}, this.props.value, {name: e.target.value})) }, render: function() { return React.createElement('form', {className: 'ContactForm'}, React.createElement('input', { // ... onInput: this.onNameInput, }) // ... ) } });
Structuring application state
As it stands, our app only contains two top level variables –
contacts and
newContact – so you’d think we’d be a way from having to worry about structure. But apps don’t stay small forever, and this begs the question of where do you draw the line? Five variables? 50?
For Ridiculously Simple Forms, and indeed Ridiculously Simple Apps, the best place to draw the line is actually one state variable. Managing all your state from one place means you’ll never forget to do your housekeeping, and also eliminates that most annoying problem of deciding where to put things.
But how do you turn two state variables into one? Exactly the same way that React does – with a state object and a setter function:
/* * State */ // The app's complete current state var state = {}; // Make the given changes to the state and perform any required housekeeping function setState(changes) { Object.assign(state, changes); ReactDOM.render( React.createElement(ContactView, Object.assign({}, state, { onNewContactChange: function(contact) { setState({newContact: contact}); }, })), document.getElementById('react-app') ); } // Set initial data setState({ contacts: [ {key: 1, name: "James K Nelson", email: "james@jamesknelson.com", description: "Front-end Unicorn"}, {key: 2, name: "Jim", email: "jim@example.com"}, ], newContact: {name: "", email: "", description: ""}, });
And since we’re deciding where to put things, let’s finish the job properly and also decide where to put code which modifies state. Since we’re aiming for simple, let’s just creates one
function for each of the actions we can perform. Like this:
/* * Actions */ function updateNewContact(contact) { setState({ newContact: contact }); }
Switch out the anonymous function assigned to
onNewContactChange for our new
updateNewContact, and we’re good to go!
So now that you can add actions and state in your sleep, let’s try:
Exercise 3 – Saving contacts
The only thing left before your form is fully functional is the ability to add new contacts to the list.
To do this, you’ll need an action which expands the
contacts array and resets
newContact – let’s call this action
submitNewContact. You’ll also want to make sure this action ignores contacts with an empty
name or
We could do this by passing
submitNewContact through to your submit button’s
onClick prop, which is called every time the user clicks the button (surprise!). But, since we care about the user experience, we don’t want them to be surprised when they hit enter after entering their contact — and nothing happens. So instead, let’s call our action when the
submit event is fired on the HTML
<form>.
Your task is to implement the
submitNewContact action.
Check the React documentation if you need help finding appropriate callback props. Once you’ve got it working, see how your solution compares with mine. Don’t get too hung up on any differences, though – the important thing is that it works!
e.preventDefault()on your
submitevent, otherwise your browser will do what it normally does and submit the form!
Don’t make users think
Congratulations – you’ve now completed a functional app! However, you’re not going to kill salesforce by just getting the functionality right. People won’t buy your product unless they understand it.
From your customer’s point of view, there is still a serious issue with this app: when the user clicks the “Add Contact” button without entering anything, nothing happens. People expect something to happen when they click a button, so let’s prevent any confusion by making sure something does.
Ridiculously Simple Validation
If you’ve completed exercise three (which you should have, seeing you’re reading this), you’ve already implemented basic validation! Our task is to actually display the result to the user.
Doing so will require passing our validation result from where it is computed to where it is rendered. Happily, we don’t need any callbacks this time; we can implement this by adding an
errors object to the
newContact object inside our submit action:
var contact = Object.assign({}, state.newContact, {key: state.contacts.length + 1, errors: {}});
Store any messages on the appropriate properties under
contact.errors:
// Test that `contact.email` looks like a real e-mail address using a RegExp if (!/.+@.+\..+/.test(contact.email)) { contact.errors.email = ["Please enter your new contact's email"] }
And to distinguish between new contacts and those which have failed validation, let’s keep
errors as
null on our contact template:
var CONTACT_TEMPLATE = {name: "", email: "", description: "", errors: null}
If you’ve used Ruby on Rails, this pattern probably feels fairly familiar – the only difference is that it doesn’t use a special Errors class, making it even simpler. But now that we’ve stored our error messages in the application state, how do we display them?
Exercise 4 – Displaying validation errors
To keep things simple, let’s ignore the messages themselves.
Your task is to display a red border on the
<input> elements which have an error.
Do so by adding
className props to the appropriate
<input> elements. Once you’ve got it working, compare your solution with mine.
And there you have it – you now know how to build Ridiculously Simple Forms! And all in less time than it would have taken to even start building a list of form libraries. Pat yourself on the back for a job well done!
Choose your adventure
So where do you go from here? Well, given that you now know how to make ridiculously simple forms, it wouldn’t hurt to invest some time in learning how to make them usable. To do this, you’re going to need to understand how to interact with the DOM using React. And this article will teach you how, using the same codebase that you’re already familiar with.
But once you’ve mastered React DOM interaction, are you just going to spend your weeks tweaking your single form on your single page? Of course you’re not. And that is why you need to learn about routing.
Luckily, after reading next week’s article in the Raw React series, you’ll be able to build an incredibly simple router for your React application in your sleep. And you won’t stop there – when complete, your app will be able to:
- Handle navigation/routing
- Communicate with an API
- Authenticate users
Update: Part 3: Routing with Raw React!
- Interacting with the DOM in React
- Learn Raw React Part 1
- Learn Raw React Part 3: Routing
- Introduction to Higher Order Components
very useful article, thank you!
Nice article, James.
Question: Everytime when adding a contact you copy an array of contacts. Isn’t it too slow when there are many contacts?
state.contacts.slice(0).concat(contact)
Possibly, although you’d thousands of contacts before this became a problem. It isn’t something to worry about with an app this size, and ensuring we’re copying instead of mutating the array is important, as otherwise we’d be mutating our state.
On Exercise 2 we skipped right to state before explaining it ? I got a bit lost there.
Thank you, James!
This has been a nice introduction to ReactJS. I enjoy your writing, and your explanations are clearly communicated.
Very nice work. Your efforts are appreciated.
Looks great! will give it a try to see how its going
Best introduction to React I’ve seen yet.
This is great. Thank you. I signed up for the newsletter and followed you on Twitter.
I like your tutorials, very nicely done!
I do have a question, though. Why use this…
`state.contacts.slice(0).concat(contact)`
…and not just this:
`state.contacts.concat(contact)`
What advantage does slicing have in this scenario?
James, Great article! I am a designer and don’t develop daily. I am familiar with React and worked for a start-up that used React as framework. I gained more understanding of how React works by working through your exercises. Thanks for taking the time to put this together!
I am unable to see your jsBin codes. Anyone else also facing this issue?
I just checked and am able to view them. Is the problem resolved on your end?
I too am unable to view them. The JSBin sections show a loading bin, but it never loads for me.
My internet is fine as I can go to other websites.
You can add a “name” attribute for every input element, and then use a single onChange method that will use e.target.name as “key” for input value 🙂
I was surprised that the console output in exercise 1 was always a single character – I expected the input field(s) to store each character, and concatenate them to form the input string. Clearly, the data returned in the (synthetic) element callback is formed by concatenating the current value property, and the entered character, because the tutorial code certainly never does the concatenation, and the fields are correctly concatenated in ex. 2. I notice that in ex. 1, I can get more than one character to be logged by pasting in a string into the input field – a paste is obviously considered to be a single input event.
Please help me figure out why textfields hasn’t placeholders after sucessful form submit? I must click to field, so placeholders are going visible. | http://jamesknelson.com/learn-raw-react-ridiculously-simple-forms/ | CC-MAIN-2017-34 | refinedweb | 2,904 | 57.16 |
Pluggable Applets via ServiceLoaders, Groovy, and Griffon:
In what way is the application pluggable? Read yesterday's blog entry but, in summary, be aware that none of the items in the list that you see above are defined in the Griffon application. Each item is made available by a different service provider and loaded into the list via the JDK 6 ServiceLoader class. For more details, read yesterday's blog entry. The only change is that I've added a border so that later, when the application is deployed as an applet, I have something to hold on to as I drag the applet out of the browser:
import javax.swing.border.TitledBorder import javax.swing.border.EtchedBorder application(title:'Encoder Sales') { border = new TitledBorder( new EtchedBorder(), 'Available Encoders') panel(border:border) { textArea( id:'encoderList', rows:10, columns:30, editable:false ) } }
Also note that above I removed "pack:true" from the application's properties. And here it is deployed to the web as an applet:
That's possible because when Griffon creates the applet (when you do "griffon run-app"), the value of the applet's archive element is a list of all the JARs on the application's classpath. Those JARs include the service providers (and the service itself), hence the resources defined in META-INF/services are made available to the applet. As a result, applets are pluggable too!
And, of course, one can drag the applet out of the browser (Firefox3 with JDK 6 Update 10):
By the way, did you know that you can close the browser... and the applet will still exist, running independently on your desktop?
Summary: I created the applet by first creating a Swing application in Groovy via the Griffon framework. I used the JDK 6 ServiceLoader class to plug three service providers into my application. Then I ran "griffon run-app" and, in addition to a Swing application, an applet (and a JNLP application) was created by Griffon. However, for the applet to work, I needed to remove "pack:true" from the view. When I ran the applet, I had the same result as the Swing application, i.e., the ServiceLoader loaded the service provider interface, thus letting me call the exposed method on each of the implementations registered in their JAR's META-INF/services folder. Hence, I did nothing at all to create the applet, Griffon simply generated it for me from my Groovy (in the Griffon application) and Java (in the service providers) source code. Among many other things, this example therefore shows yet another scenario where Groovy and Java work seamlessly together.
Sep 21 2008, 07:02:22 AM PDT Permalink
Inside of an application node pack:true wasn't your mistake, it's part of the default templates and is supposed to be benign in applets. Furthermore it is supposed to work just fine. Griffon (in 0.0.2 or 0.1) will address that issue, a patch is in SVN.
Posted by 75.163.151.236 on September 21, 2008 at 09:47 AM PDT # | http://blogs.sun.com/geertjan/entry/pluggable_applets_via_serviceloaders_groovy | crawl-002 | refinedweb | 510 | 62.38 |
Extras/SteeringCommittee/Meeting-20060427
From FedoraProject
Summary
Present from FESCo: thl, warren, f13, scop, mschwendt, jeremy, skvidal, spot,
- Kernel module standardization
- scop> | one kmodtool/yum interop issue was found, I just committed some fixes for it
- thl still wants to improve some minor things but has no time for it atm -- needs to wait
- Security SIG/EOL
- Updated proposal in the works; some discussions around details (see full log for details)
- proposal will be posted to the list (it was actually posted to the list on friday after the meeting)
- Broken deps report
- skvidal and mschwendt will work on getting it to run on extras64
- the script will be imported to cvs
- Weekly sponsorship nomination
- tibbs (Jason L Tibbitts III) nominated himself; FESCo will discuss the nomination in the next meeting
- FESCO future
- we'll roughly proceed as suggested in the proposal for a elected FESCO that was posted to the list
- some interesting quotes:
- <.
- < mschwendt> | warren: meritocracy _and_ acceptance/approval by the community
- < warren> | I think this is a little more complicated than we're thinking now, and we shouldn't lock ourselves into any long-term plan just yet.
- < thl> | any plans we do can be reverted later
- Members of cvsextras are eligible to vote
- self-nominations to fedora-extras-list and the wiki during the first week of May and voting in the second week (if we have a solution how to actually do the vote until then; help appreciated); people that want to be in FESCo should (that's no must) lay down informations like "1) Mission Statement 2) Past work summary 3) Future plans"
- Still discussions about the number of FESCo members in the future. Remains undecided, we'll look at it again when we saw the nomination results.
- some minor packaging guidlines changes
- modules for "erlang" and "R" shall follow the same naming scheme as python in the future
- Free discussion
- yum problems "Provides: and Obsoletes: to satisfy pre-extras package dependencies?" -> mschwendt will file a bug
Full Log
19:00 --- | thl has changed the topic to: FESCo meeting in progress 19:00 * | thl looks around 19:00 * | warren here 19:00 < thl> | any FESCo members around? 19:01 * | scop here in a jiffy 19:01 < f13> | I'm here. 19:01 < thl> | okay, let's start slowly 19:01 --- | thl has changed the topic to: FESCo meeting -- Kernel module standardization 19:02 < thl> | didn't have time for it 19:02 < thl> | it still needs some minor fixes afaics 19:02 < scop> | one kmodtool/yum interop issue was found, I just committed some fixes for it 19:02 < thl> | and I plan to reply to Axel's mail, too 19:02 < thl> | scop, k, thx 19:03 * | scop is trying hard to avoid feeding that discussion 19:03 < thl> | well, let's ignore it for now and proceed 19:03 --- | thl has changed the topic to: FESCo meeting -- Security SIG 19:03 < thl> | I have a updated proposal 19:03 < thl> | and recevied some comments on the privatly 19:04 < thl> | but didn't found time yet to post it to the public list 19:04 < mschwendt> | have you posted it to fesco-list? 19:04 < thl> | do we want to wait another week to discuss this 19:04 < f13> | thl: I'm finally on fedora-extras-list so I'll see future discussion. 19:04 < thl> | mschwendt, nope, sorry 19:04 < warren> | I'd like to talk privately about the proposal 19:04 < mschwendt> | how "privately"? 19:04 < f13> | warren: planning on doing that any time soon, you know, like the last week (or 3) you were given ? 19:05 < thl> | warren, we should have at least one final round of discussion on fedora-extras-list 19:05 < warren> | I'm mostly satisfied by the current proposal. 19:05 < mschwendt> | thl: I don't find the fedora-extras-list discussion too fruitful 19:05 < warren> | mschwendt, yes. 19:05 < thl> | warren, mschwendt, that's often true 19:05 < mschwendt> | thl: it loops back to the "2nd class citizen" problem 19:06 < thl> | but I still want to show it to the public once 19:06 < thl> | before we ratify it 19:06 < warren> | how does Hans feel about the current proposal? 19:06 < warren> | the thl proposal was different from Hans 19:06 * | jeremy is here 19:06 < warren> | and I really think that everyone should really listen closely to what Bressers has to say. I feel strongly that copying Bressers' model is a good idea. 19:06 < thl> | warren, I got the impression that hans has a lot of other things to do atm 19:07 < warren> | One particular issue I'd like to discuss now. 19:07 < thl> | warren, shoot 19:08 < warren> | I don't think it is a good idea to be completely inflexible in not letting new things in. We should have a process of approval that is a HUGE hassle, but at least it is *possible*. 19:08 * | Rathann|work is away: Home. 19:08 < thl> | warren, that's in the latest proposal I wrote 19:08 < warren> | Discourage people from adding things, and generally we say no, unless there is a good reason to allow something in. 19:08 < warren> | thl, sorry, I missed that, is that the private mail version? 19:08 < thl> | warren, a "FESCO can allow exceptions" 19:08 < thl> | warren, yes, the private mail version 19:08 < warren> | OK, sounds good. 19:09 < mschwendt> | hmm, what do we discuss a secret private mail version? Who knows it? 19:09 < mschwendt> | s/what/why/ 19:09 < warren> | Let's discuss this in private and aim to post the proposal on fedora-extras-list on Monday? 19:09 * | Rathann|work is away: Home. 19:10 < thl> | mschwendt, sorry, I took this approach because it seemed the best way to driver things forward 19:10 < thl> | mschwendt, Josh, warren, and the people that showed interest in the Security SIG were in the "To:" 19:10 < f13> | warren: bressers' model is more about implimentation. The proposal was about framework. 19:10 < warren> | Do we have agreement on this basic idea? "Security team's role is mainly tracking and testing security. Maintainers are primarily resposible for fixing tracked issues. If they fail, then security team steps in." 19:11 < thl> | warren, "Monday" seems like a good idea 19:11 < warren> | thl, let's go for that. 19:11 < thl> | k 19:11 < thl> | anything else regarding EOL / Security SIG? 19:12 * | thl will move on in 15 19:12 < warren> | let's move =) 19:12 --- | thl has changed the topic to: FESCo meeting -- Broken deps report 19:12 < thl> | skvidal, are you around? 19:13 < skvidal> | yes, I am now 19:13 < skvidal> | hiya! 19:13 < thl> | mschwendt, skvidal can you get this running on extras64? 19:13 < skvidal> | yep, we can do it now 19:13 < skvidal> | mschwendt: once more, I'm sorry, send me the script or check it into extras-buildsys/utils in fedora cvs 19:14 < mschwendt> | where can I learn more about "fedora cvs"? is it the same or different from Extras cvs? 19:14 < skvidal> | 19:14 < skvidal> | right there 19:14 < skvidal> | it's the same cvs system 19:14 < skvidal> | just a different tree 19:15 < jwb> | it requires different auth too 19:15 < mschwendt> | is joining a special group in the account system needed? 19:15 < skvidal> | which I thought mschwendt had 19:15 < skvidal> | I'll check 19:15 < skvidal> | mschwendt: one sec 19:15 < jwb> | mschwendt, yes. cvsfedora 19:15 < mschwendt> | k 19:16 < skvidal> | ah, you are not in that group. sorry 19:16 < warren> | mschwendt, if you don't have access to that group, you definitely should have it. 19:16 < skvidal> | do you want to be? 19:16 < skvidal> | I can add you now, if you'd like 19:16 <-- | BobJensen has quit (Remote closed the connection) 19:16 < mschwendt> | well, if I shall keep the scripts there, yes 19:16 < skvidal> | okay doke 19:17 < skvidal> | mschwendt: done 19:17 < thl> | k, anything else regarding the scripts? 19:17 < skvidal> | you're in the group 19:17 < skvidal> | thl: we'll work out the rest in email, I suspect 19:17 < thl> | skvidal, mschwendt, tia 19:17 --- | thl has changed the topic to: FESCo meeting -- Weekly sponsorship nomination 19:17 < thl> | anyone? 19:18 * | thl will move on in 15 19:18 < mschwendt> | no self-nominees? ;) 19:18 < ixs> | .oO( to be shot down in flames... ;) 19:18 --- | thl has changed the topic to: FESCo meeting -- FESCO future 19:18 < tibbs> | Crap. 19:19 < thl> | opinions on the ml-thread on fedora-extras-list? 19:19 --> | BobJensen (Robert 'Bob' Jensen) has joined #Fedora-Extras 19:19 < thl> | tibbs, any idea for a better solution? 19:19 < skvidal> | thl: I think we should progress with more-or-less your suggestion about elections. 19:19 < tibbs> | Sorry, I seem to have missed the start of this meeting. 19:20 < tibbs> | date -u is telling me it;s 17:20. 19:20 < warren> | Elections for the new members this time? 19:20 < warren> | Or are we talking about built-in timeout in FESCO membership with re-elections necessary? 19:21 < thl> | warren, I can't follow you completely 19:21 < warren> | I think nominations and election for the new FESCO members this round are a good idea. 19:21 < thl> | "built-in timeout in FESCO membership with re-elections necessary" seems like the way to go IMHO 19:21 < scop> | yes 19:21 < warren> | I don't think automatically timing people out necessitating re-election is a good idea. 19:22 < bpepple> | thl: +1 19:22 < warren> | I do support kicking people out if they haven't done anything. =) 19:22 < thl> | I would prefer if we could avoid kicking 19:22 < scop> | auto-timeout is much easier and less hassle 19:22 <. 19:23 < thl> | warren, I'm fine with "meritocracy" 19:23 < ixs> | warren: the debian problem is not the democracy, it's the love for endless discussions. 19:23 < ixs> | and politics. 19:23 < mschwendt> | warren: meritocracy _and_ acceptance/approval by the community 19:24 < thl> | mschwendt, +1 19:24 < warren> | mschwendt, that sounds nice, but how do you codify that? 19:24 < mschwendt> | yeah, that's the hard part 19:24 < mschwendt> | we need to make FESCO work and see how the community reacts to FESCO's decisions 19:25 < thl> | warren, decisions have to be made in a meritocracy, too -- that's also a hard part 19:25 < mschwendt> | part of that will be a learning-by-doing process 19:25 * | spot agrees with mschwendt 19:25 < warren> | I think this is a little more complicated than we're thinking now, and we shouldn't lock ourselves into any long-term plan just yet. 19:25 < warren> | It would be simpler if we do a one-time election for these new members now and figure out what to do with the new leadership group. 19:25 < tibbs> | You have to be willing to try and fail and try again. 19:25 < thl> | any plans we do can be reverted later 19:26 < warren> | true 19:26 < mschwendt> | sounds good 19:26 < thl> | we just need to find a way to do it now "somehow" 19:26 < thl> | and we'll learn from the results 19:26 < warren> | one more thought along these lines 19:26 < warren> | Who is eligible to vote? 19:26 < thl> | cvsextras 19:27 < warren> | Democracies have not always created the best outcome in history. 19:27 < thl> | well, we can try something like the following 19:27 < thl> | (it was suggested on the list iirc) 19:27 < warren> | Democracy could mean someone joins without merit. 19:28 < thl> | we let people vote 7 (or 9)FESCo members 19:28 < skvidal> | warren: do you have a political science degree? 19:28 < thl> | and 6 (or 4) are elected by the old FESCo 19:28 < skvidal> | warren: history? 19:28 < skvidal> | warren: any social science at all? 19:28 < warren> | skvidal, no, but I studied it a lot. 19:28 --> | kimberly (kimberly) has joined #fedora-extras 19:29 < skvidal> | warren: trust me. given the userbase there's not much fear of a fesco dominated by people who are not qualified for the job 19:29 < warren> | Another issue, do we have agreement that we want FESCo to be larger in order to have some redundancy in membership, because not everyone attends meetings at any given time? 19:29 < warren> | I'm in support of 15 for this reason. 19:29 * | spot points out that meetings during the work week are very hard for him to attend 19:29 < mschwendt> | yes, because we need to reach a well-defined quorum 19:30 < thl> | there were a lot of people that prefered a smaller FESCo 19:30 < scop> | I still support a smaller number, like 9, and folks who are really active 19:30 < thl> | I don't want to go lower than 11 19:30 < thl> | and my vote are still 13 19:30 < warren> | I don't think there is a danger in FESCo of a larger group causing too much noise. FESCo is really about who gets things done. 19:31 < warren> | 13 or 15 is fine to me. 19:31 < warren> | If we have enough energized people who want to be there to number 15, I dont think we should deny two. 19:31 < warren> | Let's just go forward with nominations? 19:31 < tibbs> | What is the size of the voting pool? 19:31 * | warren looks... 19:32 < bpepple> | tibbs: Aren't there around a 100 or so folks in cvsextras? 19:32 < thl> | bpepple, no, there are more iirc 19:32 < mschwendt> | 238 19:32 < warren> | easy things to agree upon: We want nominations. 19:33 < bpepple> | Boy, that a bunch more than I thought. 19:33 < tibbs> | Tough to regularly find 15 people from that. 19:33 < warren> | cvsextras should vote for people who are nominatd 19:33 < thl> | warren, self-nominations imho 19:33 < warren> | ok, that's fine 19:33 < thl> | we can go for the proposed plan 19:34 < thl> | self-nominations to fedora-extras-list during the first week of May 19:34 < thl> | and voting in the second week 19:34 < warren> | thl, +1 19:34 < thl> | (if we have a solution how to actually do the vote until then) 19:34 < warren> | I move that we decide the number of spots only after we see the nomination results. 19:35 < thl> | warren, yeah, might make sense 19:35 < thl> | any "-1" for the "self-nominations to fedora-extras-list during the first week of May" solution? 19:36 < thl> | otherwise we'll go for it 19:36 < warren> | Should we suggest that nominees put information about their work and plans on their Wiki page? 19:36 < thl> | mschwendt, scop, jeremy, skvidal ? 19:36 < bpepple> | warren: That's not a bad idea. 19:36 < thl> | warren, +1 19:36 < warren> | We can have a FESCOCampaign page with links to nominee pages. 19:36 < spot> | sounds good to me. 19:36 < skvidal> | thl: announce the call for nominations to a couple of lists, too 19:36 < skvidal> | otherwise I'm down with that 19:36 < thl> | skvidal, will do 19:37 < skvidal> | oh and one more thing 19:37 < skvidal> | you do NOT have to self-nominate 19:37 < skvidal> | if someone else wants to they can nominate another person 19:37 < warren> | but you do have to accept a nomination =) 19:37 < skvidal> | but the other person has the right to decline 19:37 < skvidal> | fuck that noise 19:37 < thl> | and write a mission statement 19:37 < warren> | on each person's wiki page 19:38 * | spot goes to write a mission statement on each person's wiki page... 19:38 < thl> | skvidal, I really want to hear goals, plan from those that want to be in the next FESCO 19:38 < skvidal> | okay, that's cool 19:38 < warren> | how about... 19:38 < skvidal> | but if someone is nominated 19:38 < skvidal> | and they don't want to do it 19:38 < skvidal> | they can decline the nomination 19:38 < skvidal> | that's all I mean 19:39 < thl> | sure 19:39 < warren> | 1) Mission Statement 2) Past work summary 3) Future plans 4) links to good posts or reviews and other examples 19:39 < mschwendt> | 4? 19:39 < warren> | I don't know, just ideas. 19:39 < warren> | #4 is really the same as #2 19:40 < mschwendt> | except you don't really want anyone to look up "links" 19:40 < warren> | eh? 19:40 < mschwendt> | is bugzilla.fedora.us still alive? 19:40 < mschwendt> | are you serious about "links to good posts"? 19:41 < warren> | actually, for the moment it is still up 19:41 < warren> | the other server died 19:41 < thl> | I don't think we need to formalize the format of the "mission statement" to much 19:41 < skvidal> | thl: +1 19:41 < warren> | If you're serious about getting votes, you have the option of putting information on your wiki page. 19:42 < thl> | k, anything else? 19:42 * | thl will move on in 20 19:43 --- | thl has changed the topic to: FESCo meeting -- Free discussion 19:43 < thl> | anything else releated to Extras? 19:43 < mschwendt> | The topic I started on fesco-list yesterday. 19:43 < tibbs> | I had wanted to self-nominate for sponsorship but it seems my clocks are wrong. 19:43 < mschwendt> | I really seek for more feedback from other FESCO members. 19:44 < skvidal> | mschwendt: file a bug 19:44 < tibbs> | I'll catch the next meetin for that. 19:44 < jwb> | mschwendt, what is that topic? 19:44 < warren> | skvidal, the last time a bug was filed it was closed NOTABUG, are you saying your mind changed? 19:45 < skvidal> | I'm saying i'm not sure it is the same thing at all 19:45 < warren> | skvidal, your attitude here is a bit upsetting. 19:45 < skvidal> | more importantly the rule is the same no matter what 19:45 < mschwendt> | jwb: The thread "Provides: and Obsoletes: to satisfy pre-extras package dependencies?" on extras-list is related. 19:45 < skvidal> | what attitude - he claims there is a bug or a problem 19:45 < thl> | jwb, that'S 19:45 < skvidal> | he refuses to file it to get looked at 19:45 < jwb> | thank you 19:45 < warren> | If you insist this is a different issue, then he should file the bug and we'll see where this goes. 19:46 < thl> | warren, agreed 19:46 < mschwendt> | skvidal: do you accept bug reports in bugzilla.redhat.com or only upstream where I don't have an account? 19:46 < warren> | But everyone else has been under the impression that this was the same bug, if that is the case then your stance has been frustrating. 19:46 < tibbs> | I started that thread; I was just checking to make sure that it was allowable 19:46 < skvidal> | mschwendt: I have hundreds of bugs opened at rh bugzilla 19:46 < scop> | I'm pretty sure it's the same one 19:46 < skvidal> | mschwendt: feel free 19:46 < tibbs> | to include those kinds of obsoletes to cover pre-extras package history. 19:46 < skvidal> | warren: how is it that you help in this discussion? 19:46 < skvidal> | warren: scurry on your way 19:47 < warren> | skvidal, I'm pointing out that your typical attitude is demeaning towards others. 19:47 < warren> | skvidal, including this. 19:47 < skvidal> | not really 19:47 < skvidal> | just you 19:47 < skvidal> | not others 19:47 < mschwendt> | skvidal: okay, I'm going to file a bug in the next 1-2 hours 19:47 < skvidal> | mschwendt: cool 19:47 * | spot wants to propose some minor packagingguidlines changes 19:47 < scop> | mschwendt, put me in Cc, will you? 19:47 < mschwendt> | scop: yes 19:48 < skvidal> | yay, progress 19:48 < thl> | okay, I'll move on 19:48 --- | thl has changed the topic to: FESCo meeting -- spot: some minor packagingguidlines changes 19:48 < f13> | warren: um, I think you're misguided. skvidal needs a bug filed so that he can examine the issue to see if they are in fact the same issue or not. 19:48 < spot> | specifically, i want to append "erlang-*" and "R-*" to the python naming scheme 19:48 < f13> | warren: not a hard concept to understand. 19:48 < skvidal> | spot: append or prepend? 19:48 < warren> | f13, stay out of this, this isn't your problem. 19:48 < skvidal> | warren: nor is it yours 19:48 < f13> | *cough* 19:49 < spot> | skvidal: either or. add. 19:49 * | spot is pretty dosed up on cough medicine 19:49 < warren> | f13, quite frankly, I'm annoyed that you NOW join fedora-extras-list despite being on FESCO for how long? really... 19:49 < jeremy> | spot: you mean "have erlang-* and R-* follow the same" ? 19:49 < spot> | jeremy: yeah. 19:49 < spot> | same as python 19:49 < jeremy> | seems sane 19:49 < f13> | warren: I was dragged into FESCO due to Legacy, and I've been trying to get OFF fesco for a while now. 19:49 < jwb> | warren, skvidal, f13: /msg each other with bitching please 19:49 < skvidal> | spot: it makes sense from a consistency standpoint 19:49 < skvidal> | jwb: :) 19:49 < tibbs> | Stricter than python would be good 19:49 < thl> | skvidal, yeah, seems sane 19:49 < skvidal> | tibbs: stricter? 19:50 < tibbs> | Python has the "py" exception; no need for that. 19:50 < skvidal> | oh 19:50 < nirik> | spot: did you follow the elisp issue ? ( muse review )... thoughts on elisp namespace? 19:50 < thl> | s/skvidal/spot/ 19:50 < warren> | What about the emacs sub-package namespace? 19:50 < skvidal> | tibbs: you don't want erfoo :) 19:50 < jeremy> | skvidal: I want erlfoo ;) 19:50 < skvidal> | jeremy: my name is erlfoo 19:50 * | warren fought the Java namespace battle last year and lost. 19:50 < tibbs> | The initial problem was "efoo". 19:50 < tibbs> | Not a lot of uniqueness in "e". 19:50 < skvidal> | tibbs: ejabberd is an example 19:50 < skvidal> | it's not a erlang module 19:50 < skvidal> | but it is written in erlang 19:51 < tibbs> | I assume we're talking about add-on modules 19:51 * | ixs pipes up, I have ejabberd in the extras queue 19:51 < spot> | yeah, only add-on modules 19:51 < skvidal> | tibbs: okay 19:51 < tibbs> | not standalone packages that happen to be written in something. 19:51 < skvidal> | ixs: yay 19:51 < skvidal> | tibbs: okay, then I agree 19:51 < skvidal> | anyone against erlang-* and R-*? 19:51 < warren> | Add-on modules that are libraries and not applications should follow namespace guidelines. Typically the applications at the end of the chain don't. 19:52 < spot> | nirik: i'll have to look at elisp seperately. 19:52 < ixs> | skvidal: first successfull build happened yesterday. the openssl stuff was tricky. 19:52 < skvidal> | ixs: cool 19:52 < warren> | +1 Just go for erlang-* and R-* 19:52 < skvidal> | spot: sounds like a winner 19:52 < scop> | elisp needs to be emacs-* and xemacs-* in binaries due to incompatibilities with byte-compiled code 19:53 < scop> | unless the Debian way that tagoh suggested makes its way in in one form or another 19:53 < nirik> | spot: yeah, it's diffrent. I don't think it's worth doing a specific namespace for it... not enough packages, and confusing since there is emacs and xemacs to deal with. 19:53 < spot> | Other item I'd like to do is add a section to the Guidelines covering find_lang, why and how to use it. 19:53 < spot> | We've got a MUST in the reviewguidelines about it, but no text in the Guidelines 19:53 < f13> | spot: please do! 19:53 < tibbs> | Yes, I don't understand %find_lang. 19:54 < tibbs> | At least, not completely enough to tell submitters how to handle it. 19:54 < warren> | Regarding elipse, I move that scop writes a summary proposal for policy to fedora-extras-list, we discuss it, then aim for ratification next Thursday. 19:54 < warren> | elisp* 19:54 < nirik> | scop: yeah, but base packages are currently mostly %name... not emacs-%name or elisp-%name or anything. 19:55 < scop> | warren, I'd rather not 19:55 * | jwb smiles at ratification 19:55 < warren> | scop, what do you want to happen? 19:55 < scop> | no time, nor much interest here, and tagoh's approach should to be discussed first 19:55 < warren> | hmm 19:55 < tibbs> | Yes, this is a complicated issue. 19:55 < warren> | Or we could just continue to ignore the problem. 19:56 < tibbs> | We need to dissect Debian's approach to elisp packages. 19:56 * | nirik doesn't see a problem with no namespace for base packages for elisp and emacs- and xemacs- subpackages for them... 19:57 < warren> | nirik, like what happened to muse? 19:57 < spot> | well, since elisp issues aren't going to be decided now, thats all i have. 19:57 < nirik> | warren: yeah... and mew, and others already in extras. ;) 19:58 < f13> | spot: did we want to talk about a new 'governing' body over the Package Guideliens and such? 19:58 < f13> | now that more than just Extras is invovled? 19:58 < spot> | f13: i do, but lets get FESCO sorted out first. 19:58 < warren> | f13, thl, me and Max began a plan for that 19:58 < f13> | warren: oh? 19:58 < spot> | warren: yeah, thanks for CC'ing me on that btw. 19:59 < thl> | spot, I think we covered evrerything for today 19:59 < warren> | f13, we need to figure it out before posting it wider 19:59 --- | thl has changed the topic to: FESCo meeting -- nearly done 19:59 < warren> | spot, this began literally last night with Max pushing, I suspect he is not aware of you, don't worry you'll be included. 19:59 * | warren nudges mspevack 20:00 * | mspevack met spot at LinuxWorld. If I left him out of a thread, I apologize 20:01 < spot> | life goes on. are we about done? i need to go rest, still very sick. 20:02 < thl> | warren, spot, f13, let's get back to it another time 20:02 < warren> | thl, yes, this is in progress. 20:02 < warren> | I move that we adjourn. 20:02 < thl> | k, anything else? 20:02 < spot> | second 20:03 < warren> | pretty good, lots of ground covered in roughly an hour. 20:03 * | thl will close the meeting in 60 20:03 * | thl will close the meeting in 30 20:03 < thl> | tibbs, btw, consider yourself nominated 20:03 < thl> | tibbs, we'll discuss this next week 20:04 < tibbs> | Thanks. 20:04 * | thl will close the meeting in 10 20:04 < thl> | MARK meeting end 20:04 < tibbs> | BTW, the Wiki page says the meeting starts about now. 20:04 < warren> | tibbs, URL? 20:04 < tibbs> | 20:04 < tibbs> | Unless it isn't 18:05 UTC right now. | http://fedoraproject.org/wiki/Extras/SteeringCommittee/Meeting-20060427 | CC-MAIN-2013-48 | refinedweb | 4,553 | 66.57 |
Weather Station Wirelessly Connected to Wunderground
Wimp Weather
Phant is No Longer in Operation
The Wimp is a personal weather station that uses the weather shield along with an Electric Imp to push live weather data up to Wunderground. You can help increase the accuracy and prediction of weather by adding a weather meter to your house! But why buy an off-the-shelf system when you can build you own? For around $250 you can build a cutting edge open source station that you have complete control over! All you need is a pile of parts and access to a Wifi network.
Wunderground makes it really easy to setup your own weather station. You fill out a form, pick a username and password, then get a station ID. Using this ID and password, we can push weather data with a simple HTTP POST command:
Copy and paste the above code into a browser, and press return. You should see
success. You can then view the weather station data you just posted here. Congrats! You've just published your first weather data to the Internet of Things.
The above link shows how to push temperature data to the web, but you can also post a large number of other weather metrics. This example will show you how to report the following bits of weather:
- Temperature
- Humidity
- Light level
- Rain fall
- Instantaneous Wind speed + direction
- Gusting speed + direction for the last 2 minutes
- Gusting speed + direction for the last 60 minutes
You can also see even more data at the Wimp Weather Stations channel over on data.sparkfun.com. This channel includes some extra bits including battery voltage level, ambient light level, and local time stamp (including DST correction).
This project builds on quite a few concepts. You may want to read the following tutorials if they are unfamiliar to you:
Electronics
Required Materials
To follow along with this tutorial, you will need the following materials. You may not need everything though depending on what you have. Add it to your cart, read through the guide, and adjust the cart as necessary. Here are the parts we used to build our weather station:
- SparkFun RedBoard Programmed with Arduino
- Electric Imp
- Electric Imp Shield
- Weather Shield
- Shield Header Kit x 2
- RJ11 Jacks x 2
- Weather Meters
- Sunny Buddy MPPT Solar Charger
- 6000mAh LiPo Battery
- 3.5W, 6W, or 9W Solar Panel
- Plastic Enclosure (optional)
- Light Pipe (optional)
Below is a wishlist to make things a bit easier:
You Will Also Need
Here are additional parts that SparkFun doesn't carry:
- Solar Shield - We got ours from Ambient Weather. $40, works great!
- Camera Tripod - We found a cheap one on Amazon for $20 and chopped the camera mount off.
- Handful-o-zipties - If you don't have these laying around, you'll need some to secure the various charging and weather meter cables.
- 2" Hose Clamps - Sometimes called worm clamps, these connect the weather meter to the headless camera tripod. The weather meters should come with a few to get you started.
- Cement ballast - Solid concrete blocks can be found for a few dollars at a hardware store
- Eyebolts and concrete anchors - Ballast is useless if you can't attach to it securely. An eyebolt with a lead anchor makes a very secure connection to the cement block.
- Wire rope, cable clips, and turnbuckle - Wire rope with clips should survive extreme conditions. The turnbuckle was key; it allowed mass to be easily tensioned onto the tripod.
- Galvanized metal bits - To hold the solar panel in place.
The system is designed to be low-power enough that a battery+charger+solar combination will suffice, but, if you have a source of power near your weather station, feel free to simplify things and use a wall adapter.
RedBoard
This is our Arduino-compatible workhorse. It will gather all the weather data from the weather shield and then pipe serial strings to the Imp.
Weather Shield
You can read all about the Weather Shield over on its hookup guide tutorial. All you really need to know is that it's capable of reading a huge number of weather metrics but doesn't have the capabilities to wirelessly report them.
Electric Imp
You will need to modify the Electric Imp shield in three ways:
- Clear the card detect Jumper
- Clear and move the TX and RX jumpers
- Add jumper from P1 to RST for wireless bootloading
Clear the card detect CD-A0 jumper so that the Arduino can take readings from the wind vane without being affected by the Electric Imp shield. The easiest way to clear this jumper is to carefully cut the connecting trace with an exacto knife.
The Electric Imp is a simple to use internet-of-things device. It's like a Wifi adapter with a bunch of built in bells and whistles. We'll set it up to receive the serial strings from the RedBoard and pipe that data to an agent that will in turn post the weather metrics to Wunderground.
Note: The Electric Imp shield shown above has been modified for wireless bootloading of the Arduino. This saves an immeasurable amount of work! We can reprogram the Arduino from the comfort of our living room rather than climbing up on a ladder and plugging in a USB cable. To find out more checkout our tutorial on Wireless Arduino Programming.
Power System
The Wimp runs off a 3.7V 6000mAh LiPo battery.
The following measurements were taken for various bits of the project:
- Electric Imp (average when posting data every 5 seconds): [4.5mA during sleep for 8s, 80-100mA for 2s] = 22mA avg
- Weather Shield: 2mA (with out GPS)
- RedBoard: 15mA
The voltage of the LiPo battery will vary from 4.2V when fully charged to 3.2V when very dead. This is acceptable because the RedBoard can operate from 5V down to about 3V, and both the Electric Imp and the Weather Shield have on board 3.3V regulators. The RedBoard can also detect what the system voltage is at by doing an analog to digital conversion. Basically we connect the 3.3V rail of the Arduino to one of the analog pins so that we can establish what the battery level voltage actually is. You can read more about this trick over on the ML8511 UV tutorial.
The average total current consumption of the system is about 39mA. This means on a 6000mAh battery the system will run for about 150 hours or about 6 days. This should be pretty good for Colorado, with 300 days of sunshine. If the solar cell does get covered in snow, the angle of the panel will help remove it. If all things go pear shaped and the system dies, you've probably got bigger (weather) problems to be worrying about.
If anyone knows of a good article on how to size your battery capacity vs power requirements vs charging system, we would be thrilled to link to it!
Enclosure
Creating a good weather station enclosure is difficult. There has been a fair number of comments on the Weather Shield product page and a great number of discussions and solutions proposed on the Internet.
Our plastic red enclosure is very robust against adverse weather and is easily modified with tools found at home (hand drill, dremel, etc). The problem is that depending on where you want to mount your weather station, the red box enclosure can heat up quite a bit. In Colorado direct sunlight can be quite intense, so do plenty of Googling to determine what's best for you.
For this project, we went all out and used a radiation shield from Ambient Weather. A solar shield allows for free flow of air across the sensors while reflecting the majority of incident heat. Additionally, this enclosure had plenty of room for our stack-up of Arduino shields, batteries, and solar charger. There are three long threaded rods with three wing nuts that hold the stack of plastic layers together. Opening the enclosure takes a few minutes but is pain free.
It is not obvious from the photo, but the three cables (wind, rain, and charging) enter into the enclosure through the gap between two of the layers about half way down the enclosure.
Initially, because the solar shield is open to the elements, I was nervous that stray wind and rain would eventually cause the electronics to fail. My wife had the excellent idea of wrapping the non-sensor bits in cellophane. Two of the layers are wrapped, and the top shield (the weather shield) is left exposed so that the air can freely move across the sensors. It's not entirely clear if this method is preventing water damage to the stack of boards, but it puts my mind at ease. When repairs are needed, I'll update the tutorial with any future insights.
At first, I thought I would need a light pipe to get light into the enclosure. After installing the station on my roof, I found that plenty of light is passed through the gaps of the radiation shielding to get a great ambient light reading. If you're looking for a more scientific reading, you might consider piping light directly.
Someday, it would be fun to gather UV data as well. We've got a great ultraviolet light sensor, but the light pipe material may or may not pass UV light specifically. If you have any information or experience gathering UV readings, we welcome your feedback!
Assembly
First, solder the headers onto the shields, and build up the stack. Not sure how to solder the headers on? Checkout the tutorial on installing Arduino headers. This will also be a good time to solder the two RJ11 jacks to the weather shield as well. These will connect to the cables coming off the weather meters.
Once you are finished soldering, you're ready to program your weather station!
Firmware
You will need to associate your Imp to your Wifi network. This has been documented a few times. I used my cell phone and their free android app. It took a few tries, but I was eventually able to get the Imp to link up to my home network..
Below, you will find example code, but, for the latest version of everything, see the Wimp GitHub Repo.
language:c /* Weather Station using the Electric Imp By: Nathan Seidle SparkFun Electronics Date: October 4th, 2013 License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license). Much of this is based on Mike Grusin's USB Weather Board code. This code reads all the various sensors (wind speed, direction, rain gauge, humidty, pressure, light, batt_lvl) and sends it to the imp, which then forwards that data to an Imp Agent on the cloud that does some processing then bounces the weather data to Wunderground. The Imp Shield has Card Detect tied to pin A0. We use A0 for wind direction. You will need to cut the trace on the Imp shield. Current: 130 for 2 seconds while transmitting ~30mA during sleep Todo: Reset after 45 days to avoid millis roll over problems What was the wind direction and speed gust for the last 10 minutes? Is the 3.3V pin tied on the weather shield or elsewhere? */ #include <avr/wdt.h> //We need watch dog for this program #include <Wire.h> //I2C needed for sensors #include "MPL3115A2.h" //Pressure sensor #include "HTU21D.h" //Humidity sensor //#define ENABLE_LIGHTNING //SoftwareSerial imp(8, 9); // RX, TX into Imp pin 7 MPL3115A2 myPressure; //Create an instance of the pressure sensor HTU21D myHumidity; //Create an instance of the humidity sensor //Hardware pin definitions //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // digital I/O pins const byte WSPEED = 3; const byte RAIN = 2; const byte STAT1 = 7; #ifdef ENABLE_LIGHTNING const byte LIGHTNING_IRQ = 4; //Not really an interrupt pin, we will catch it in software const byte slaveSelectPin = 10; //SS for AS3935 #endif // analog I/O pins const byte WDIR = A0; const byte LIGHT = A1; const byte BATT = A2; const byte REFERENCE_3V3 = A3; //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #ifdef ENABLE_LIGHTNING #include "AS3935.h" //Lighting dtector #include <SPI.h> //Needed for lighting sensor byte SPItransfer(byte sendByte); AS3935 AS3935(SPItransfer, slaveSelectPin, LIGHTNING_IRQ); #endif //Global Variables //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= long lastSecond; //The millis counter to see when a second rolls by unsigned int minutesSinceLastReset; //Used to reset variables after 24 hours. Imp should tell us when it's midnight, this is backup. byte seconds; //When it hits 60, increase the current minute byte seconds_2m; //Keeps track of the "wind speed/dir avg" over last 2 minutes array of data byte minutes; //Keeps track of where we are in various arrays of data byte minutes_10m; //Keeps track of where we are in wind gust/dir over last 10 minutes array of data long lastWindCheck = 0; volatile long lastWindIRQ = 0; volatile byte windClicks = 0; #ifdef ENABLE_LIGHTNING byte lightning_distance = 0; #endif //We need to keep track of the following variables: //Wind speed/dir each update (no storage) //Wind gust/dir over the day (no storage) //Wind speed/dir, avg over 2 minutes (store 1 per second) //Wind gust/dir over last 10 minutes (store 1 per minute) //Rain over the past hour (store 1 per minute) //Total rain over date (store one per day) byte windspdavg[120]; //120 bytes to keep track of 2 minute average #define WIND_DIR_AVG_SIZE 120 int winddiravg[WIND_DIR_AVG_SIZE]; //120 ints to keep track of 2 minute average float windgust_10m[10]; //10 floats to keep track of largest gust in the last 10 minutes int windgustdirection_10m[10]; //10 ints to keep track of 10 minute max volatile float rainHour[60]; //60 floating numbers to keep track of 60 minutes of rain //These are all the weather values that wunderground expects: int winddir; // [0-360 instantaneous wind direction] float windspeedmph; // [mph instantaneous wind speed] float windgustmph; // [mph current wind gust, using software specific time period] int windgustdir; // [0-360 using software specific time period] float windspdmph_avg2m; // [mph 2 minute average wind speed mph] int winddir_avg2m; // [0-360 2 minute average wind direction] float windgustmph_10m; // [mph past 10 minutes wind gust mph ] int windgustdir_10m; // [0-360 past 10 minutes wind gust direction] float humidity; // [%] float tempf; // [temperature F] float rainin; // [rain inches over the past hour)] -- the accumulated rainfall in the past 60 min volatile float dailyrainin; // [rain inches so far today in local time] //float baromin = 30.03;// [barom in] - It's hard to calculate baromin locally, do this in the agent float pressure; //float dewptf; // [dewpoint F] - It's hard to calculate dewpoint locally, do this in the agent //These are not wunderground values, they are just for us float batt_lvl = 11.8; float light_lvl = 0.72; // volatiles are subject to modification by IRQs volatile unsigned long raintime, rainlast, raininterval, rain; //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //Interrupt routines (these are called by the hardware interrupts, not by the main code) //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void rainIRQ() // Count rain gauge bucket tips as they occur // Activated by the magnet and reed switch in the rain gauge, attached to input D2 { raintime = millis(); // grab current time raininterval = raintime - rainlast; // calculate interval between this and last event if (raininterval > 10) // ignore switch-bounce glitches less than 10mS after initial edge { dailyrainin += 0.011; //Each dump is 0.011" of water rainHour[minutes] += 0.011; //Increase this minute's amount of rain rainlast = raintime; // set up for next event } } void wspeedIRQ() // Activated by the magnet in the anemometer (2 ticks per rotation), attached to input D3 { if (millis() - lastWindIRQ > 10) // Ignore switch-bounce glitches less than 10ms (142MPH max reading) after the reed switch closes { lastWindIRQ = millis(); //Grab the current time windClicks++; //There is 1.492MPH for each click per second. } } void setup() { wdt_reset(); //Pet the dog wdt_disable(); //We don't want the watchdog during init Serial.begin(9600); pinMode(WSPEED, INPUT_PULLUP); // input from wind meters windspeed sensor pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor pinMode(WDIR, INPUT); pinMode(LIGHT, INPUT); pinMode(BATT, INPUT); pinMode(REFERENCE_3V3, INPUT); pinMode(STAT1, OUTPUT); midnightReset(); //Reset rain totals //Configure the pressure sensor myPressure.begin(); // Get sensor online myPressure.setModeBarometer(); // Measure pressure in Pascals from 20 to 110 kPa myPressure.setOversampleRate(128); // Set Oversample to the recommended 128 myPressure.enableEventFlags(); // Enable all three pressure and temp event flags myPressure.setModeActive(); // Go to active mode and start measuring! //Configure the humidity sensor myHumidity.begin(); #ifdef ENABLE_LIGHTNING startLightning(); //Init the lighting sensor #endif seconds = 0; lastSecond = millis(); // attach external interrupt pins to IRQ functions attachInterrupt(0, rainIRQ, FALLING); attachInterrupt(1, wspeedIRQ, FALLING); // turn on interrupts interrupts(); Serial.println("Wimp Weather Station online!"); reportWeather(); // wdt_enable(WDTO_1S); //Unleash the beast } void loop() { wdt_reset(); //Pet the dog //Keep track of which minute it is if(millis() - lastSecond >= 1000) { lastSecond += 1000; //Take a speed and direction reading every second for 2 minute average if(++seconds_2m > 119) seconds_2m = 0; //Calc the wind speed and direction every second for 120 second to get 2 minute average windspeedmph = get_wind_speed(); winddir = get_wind_direction(); windspdavg[seconds_2m] = (int)windspeedmph; winddiravg[seconds_2m] = winddir; //if(seconds_2m % 10 == 0) displayArrays(); //Check to see if this is a gust for the minute if(windspeedmph > windgust_10m[minutes_10m]) { windgust_10m[minutes_10m] = windspeedmph; windgustdirection_10m[minutes_10m] = winddir; } //Check to see if this is a gust for the day //Resets at midnight each night if(windspeedmph > windgustmph) { windgustmph = windspeedmph; windgustdir = winddir; } //Blink stat LED briefly to show we are alive digitalWrite(STAT1, HIGH); //reportWeather(); //Print the current readings. Takes 172ms. delay(25); digitalWrite(STAT1, LOW); //If we roll over 60 seconds then update the arrays for rain and windgust if(++seconds > 59) { seconds = 0; if(++minutes > 59) minutes = 0; if(++minutes_10m > 9) minutes_10m = 0; rainHour[minutes] = 0; //Zero out this minute's rainfall amount windgust_10m[minutes_10m] = 0; //Zero out this minute's gust minutesSinceLastReset++; //It's been another minute since last night's midnight reset } } //Check to see if there's been lighting #ifdef ENABLE_LIGHTNING if(digitalRead(LIGHTNING_IRQ) == HIGH) { //We've got something! lightning_distance = readLightning(); } #endif //Wait for the imp to ping us with the ! character if(Serial.available()) { byte incoming = Serial.read(); if(incoming == '!') { reportWeather(); //Send all the current readings out the imp and to its agent for posting to wunderground. Takes 196ms //Serial.print("Pinged!"); #ifdef ENABLE_LIGHTNING //Give imp time to transmit then read any erroneous lightning strike delay(1000); //Give the Imp time to transmit readLightning(); //Clear any readings and forget it #endif } else if(incoming == '@') //Special character from Imp indicating midnight local time { midnightReset(); //Reset a bunch of variables like rain and daily total rain //Serial.print("Midnight reset"); } else if(incoming == '#') //Special character from Imp indicating a hardware reset { //Serial.print("Watchdog reset"); delay(5000); //This will cause the system to reset because we don't pet the dog } } //If we go for more than 24 hours without a midnight reset then force a reset //24 hours * 60 mins/hr = 1,440 minutes + 10 extra minutes. We hope that Imp is doing it. if(minutesSinceLastReset > (1440 + 10)) { midnightReset(); //Reset a bunch of variables like rain and daily total rain //Serial.print("Emergency midnight reset"); } delay(100); //Update every 100ms. No need to go any faster. } //Prints the various arrays for debugging void displayArrays() { //Windgusts in this hour Serial.println(); Serial.print(minutes); Serial.print(":"); Serial.println(seconds); Serial.print("Windgust last 10 minutes:"); for(int i = 0 ; i < 10 ; i++) { if(i % 10 == 0) Serial.println(); Serial.print(" "); Serial.print(windgust_10m[i]); } //Wind speed avg for past 2 minutes /*Serial.println(); Serial.print("Wind 2 min avg:"); for(int i = 0 ; i < 120 ; i++) { if(i % 30 == 0) Serial.println(); Serial.print(" "); Serial.print(windspdavg[i]); }*/ //Rain for last hour Serial.println(); Serial.print("Rain hour:"); for(int i = 0 ; i < 60 ; i++) { if(i % 30 == 0) Serial.println(); Serial.print(" "); Serial.print(rainHour[i]); } } //When the imp tells us it's midnight, reset the total amount of rain and gusts void midnightReset() { dailyrainin = 0; //Reset daily amount of rain windgustmph = 0; //Zero out the windgust for the day windgustdir = 0; //Zero out the gust direction for the day minutes = 0; //Reset minute tracker seconds = 0; lastSecond = millis(); //Reset variable used to track minutes minutesSinceLastReset = 0; //Zero out the backup midnight reset variable } //Calculates each of the variables that wunderground is expecting void calcWeather() { //current winddir, current windspeed, windgustmph, and windgustdir are calculated every 100ms throughout the day //Calc windspdmph_avg2m float temp = 0; for(int i = 0 ; i < 120 ; i++) temp += windspdavg[i]; temp /= 120.0; windspdmph_avg2m = temp; //Calc winddir_avg2m, Wind Direction //You can't just take the average. Google "mean of circular quantities" for more info //We will use the Mitsuta method because it doesn't require trig functions //And because it sounds cool. //Based on: //Based on: long sum = winddiravg[0]; int D = winddiravg[0]; for(int i = 1 ; i < WIND_DIR_AVG_SIZE ; i++) { int delta = winddiravg[i] - D; if(delta < -180) D += delta + 360; else if(delta > 180) D += delta - 360; else D += delta; sum += D; } winddir_avg2m = sum / WIND_DIR_AVG_SIZE; if(winddir_avg2m >= 360) winddir_avg2m -= 360; if(winddir_avg2m < 0) winddir_avg2m += 360; //Calc windgustmph_10m //Calc windgustdir_10m //Find the largest windgust in the last 10 minutes windgustmph_10m = 0; windgustdir_10m = 0; //Step through the 10 minutes for(int i = 0; i < 10 ; i++) { if(windgust_10m[i] > windgustmph_10m) { windgustmph_10m = windgust_10m[i]; windgustdir_10m = windgustdirection_10m[i]; } } //Calc humidity humidity = myHumidity.readHumidity(); //float temp_h = myHumidity.readTemperature(); //Serial.print(" TempH:"); //Serial.print(temp_h, 2); //Calc tempf from pressure sensor tempf = myPressure.readTempF(); //Serial.print(" TempP:"); //Serial.print(tempf, 2); //Total rainfall for the day is calculated within the interrupt //Calculate amount of rainfall for the last 60 minutes rainin = 0; for(int i = 0 ; i < 60 ; i++) rainin += rainHour[i]; //Calc pressure pressure = myPressure.readPressure(); //Calc dewptf //Calc light level light_lvl = get_light_level(); //Calc battery level batt_lvl = get_battery_level(); //Lightning is checked in the main loop } //Returns the voltage of the light sensor based on the 3.3V rail //This allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V) float get_light_level() { float operatingVoltage = averageAnalogRead(REFERENCE_3V3); float lightSensor = averageAnalogRead(LIGHT); operatingVoltage = 3.3 / operatingVoltage; //The reference voltage is 3.3V lightSensor *= operatingVoltage; return(lightSensor); } //Returns the voltage of the raw pin based on the 3.3V rail //The battery can ranges from 4.2V down to around 3.3V //This function allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V) //The weather shield has a pin called RAW (VIN) fed through through two 5% resistors and connected to A2 (BATT): //3.9K on the high side (R1), and 1K on the low side (R2) float get_battery_level() { float operatingVoltage = averageAnalogRead(REFERENCE_3V3); float rawVoltage = averageAnalogRead(BATT); operatingVoltage = 3.30 / operatingVoltage; //The reference voltage is 3.3V rawVoltage *= operatingVoltage; //Convert the 0 to 1023 int to actual voltage on BATT pin rawVoltage *= 4.90; //(3.9k+1k)/1k - multiply BATT voltage by the voltage divider to get actual system voltage return(rawVoltage); } //Returns the instataneous wind speed float get_wind_speed() { float deltaTime = millis() - lastWindCheck; //750ms deltaTime /= 1000.0; //Covert to seconds float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4 windClicks = 0; //Reset and start watching for new wind lastWindCheck = millis(); windSpeed *= 1.492; //4 * 1.492 = 5.968MPH /* Serial.println(); Serial.print("Windspeed:"); Serial.println(windSpeed);*/ return(windSpeed); } int get_wind_direction() // read the wind direction sensor, return heading in degrees { unsigned int adc; adc = averageAnalogRead(WDIR); // get the current reading from the sensor // The following table is ADC readings for the wind direction sensor output, sorted from low to high. // Each threshold is the midpoint between adjacent headings. The output is degrees for that ADC reading. // Note that these are not in compass degree order! See Weather Meters datasheet for more information. if (adc < 380) return (113); if (adc < 393) return (68); if (adc < 414) return (90); if (adc < 456) return (158); if (adc < 508) return (135); if (adc < 551) return (203); if (adc < 615) return (180); if (adc < 680) return (23); if (adc < 746) return (45); if (adc < 801) return (248); if (adc < 833) return (225); if (adc < 878) return (338); if (adc < 913) return (0); if (adc < 940) return (293); if (adc < 967) return (315); if (adc < 990) return (270); return (-1); // error, disconnected? } //Reports the weather string to the Imp void reportWeather() { calcWeather(); //Go calc all the various sensors Serial.print("$,winddir="); Serial.print(winddir); Serial.print(",windspeedmph="); Serial.print(windspeedmph, 1); Serial.print(",windgustmph="); Serial.print(windgustmph, 1); Serial.print(",windgustdir="); Serial.print(windgustdir); Serial.print(",windspdmph_avg2m="); Serial.print(windspdmph_avg2m, 1); Serial.print(",winddir_avg2m="); Serial.print(winddir_avg2m); Serial.print(",windgustmph_10m="); Serial.print(windgustmph_10m, 1); Serial.print(",windgustdir_10m="); Serial.print(windgustdir_10m); Serial.print(",humidity="); Serial.print(humidity, 1); Serial.print(",tempf="); Serial.print(tempf, 1); Serial.print(",rainin="); Serial.print(rainin, 2); Serial.print(",dailyrainin="); Serial.print(dailyrainin, 2); Serial.print(","); //Don't print pressure= because the agent will be doing calcs on the number Serial.print(pressure, 2); Serial.print(",batt_lvl="); Serial.print(batt_lvl, 2); Serial.print(",light_lvl="); Serial.print(light_lvl, 2); #ifdef LIGHTNING_ENABLED Serial.print(",lightning_distance="); Serial.print(lightning_distance); #endif Serial.print(","); Serial.println("#,"); //Test string //Serial.println("$,winddir=270,windspeedmph=0.0,windgustmph=0.0,windgustdir=0,windspdmph_avg2m=0.0,winddir_avg2m=12,windgustmph_10m=0.0,windgustdir_10m=0,humidity=998.0,tempf=-1766.2,rainin=0.00,dailyrainin=0.00,-999.00,batt_lvl=16.11,light_lvl=3.32,#,"); } //Takes an average); } //The following is for the AS3935 lightning sensor #ifdef ENABLE_LIGHTNING byte readLightning(void) { byte distance = 0; //Check to see if we have lightning! if(digitalRead(LIGHTNING_IRQ) == HIGH) { //"); distance = 64; } if (irqSource & 0b1000) { // need to find how far that lightning stroke, function returns approximate distance in kilometers, // where value 1 represents storm in detector's near victinity, and 63 - very distant, out of range stroke // everything in between is just distance in kilometers distance = AS3935.lightningDistanceKm(); //Serial.print("Lightning: "); //Serial.print(lightning_distance, DEC); //Serial.println(" km"); //The AS3935 remembers the nearest strike distance. For example 15km away then 10, then overhead all following //distances (10, 20, 30) will instead output as 'Storm overhead, watch out!'. Resetting the chip erases this. lightning_init(); } } return(distance); } void startLightning(void) { pinMode(slaveSelectPin, OUTPUT); // set the slaveSelectPin as an output: pinMode(LIGHTNING_IRQ, INPUT_PULLUP); //Set IRQ pin as input SPI.begin(); //Start SPI SPI.setDataMode(SPI_MODE1); // NB! chip uses SPI MODE1 SPI.setClockDivider(SPI_CLOCK_DIV16); //Uno 16MHz / 16 = 1MHz SPI.setBitOrder(MSBFIRST); // and chip is MSB first lightning_init(); //Setup the values for the sensor Serial.println("Lightning sensor online"); } void lightning_init() { AS3935.reset(); // reset all internal register values to defaults // if lightning detector can not tune tank circuit to required tolerance, // calibration function will return false if(!AS3935.calibrate()) { Serial.println("Tuning out of range, check your wiring, your sensor and make sure physics laws have not changed!"); } AS3935.setOutdoors(); //The weather station is outdoors AS3935.enableDisturbers(); //We want to know if a man-made event happens AS3935.setNoiseFloor(3); //See table 16 of the AS3935 datasheet. 4-6 works. This was found through experimentation. //printAS3935Registers(); } /); }*/ byte SPItransfer(byte sendByte) { return SPI.transfer(sendByte); } #endif
Load the code onto your RedBoard (or Arduino of choice). Open a terminal window at 9600bps. You should see new weather data upon power up and every time you send the
! character.
Next, grab the two code blocks (agent and device shown above) for the Imp. The Electric Imp has two types of code: the device code runs on the actual SD card, the agent runs out on the cloud. The Imp itself is pretty powerful, but the cloud has far more resources. Thus, we do the low-level string manipulation on the device but leave the heavy lifting to the agent.
You'll need to replace
STATION_ID and
STATION_PASSWORD with your own ID and password.
Note: Because we are passing an http post, you can't have symbols in your password. You may need to change your Wunderground password to only have alphenumerics.
Setting Proper Altitude
Weather stations across the world report a scaled pressure reading that takes into account the local altitude (this is often called the altimeter setting). In order to be as accurate as possible, we recommend you use a cell phone or a GPS module (my current favorite is the GP-635T) to obtain an altitude reading. Meters matter, so take a couple readings and average them together. Once you know your local altitude replace
LOCAL_ALTITUDE_METERS in the agent.
You may also want to enter the altitude and location into Wunderground's site. This will give people in your community a better idea of what weather is happening at what location. Publicly posting your weather station's location has obvious privacy implications, so think about it before you make your station publicly viewable.
How It Works
The RedBoard monitors all the various sensors (humidity, temperature, rain gauge, etc) and does a little bit of processing on the data. It mashes up the individual data with identifiers and creates a comma delimited string. The Imp reads this concatenated string and looks for the correct header (
$) and ender (
#) characters. If an incomplete frame is received, it's ignored. The Imp then reports this string, verbatim, to the Agent out in the cloud.
The Agent receives this string and cracks it apart into its pieces. Because the RedBoard has pretty limited resources, we report raw Pascals to the Imp and let the Agent do the complex mmHg pressure and dew point calculations. Once all the pieces are calculated, we create another big string that is an http:// address. Posting this long link causes the weather data to be transmitted to Wunderground. After all that, we can check our weather station and see what the weather is like!
Extra Bits
This project required quite a bit of extra mechanical bits to withstand mother nature.
Base
The weather station was installed on an old camera tripod. A hacksaw quickly removed the head of the tripod where the camera attaches.
The weather meters are attached using two hose clamps, and the solar shield is attached using the included U-bolts.
Solar
To hold the solar panel at the proper angle, a steel hanger was used. Commonly used with sheetrock, the metal was heavy enough gauge to be bent with hand tools but rigid enough to hold the solar panel in place. Using construction adhesive and a clamp, we attached the solar panel to a piece of metal then zip tied the metal to the camera tripod base. Be sure to mount the solar cell where it can get a clear view of the sky, away from any possible shading.
The incline angle of the solar panel was not scientifically determined - I pointed the solar panel to the south with about a 45 degree angle. This is a common orientation in Colorado, but there are plenty of solar angle calculators available to help you determine the best inclination for your part of the world.
Ballast
Because the winds are so strong in our area, I wanted to be sure to attach the base to as much ballast as possible. I found solid cinder blocks weighing 35lbs each (16 kilograms) along with eye-bolts and lead inserts at my local hardware store. Using a 1/2" mason bit, I drilled a hole for the lead inserts then used a cheater bar to twist the eye bolts into the cinder block. Notice that I rotated one eye bolt completely off its screw; I should have probably used slightly larger inserts to allow for that size eye bolt. I used a regular bolt with a few wing nuts on the second block. Once installed the eye bolt and screw were very solidly attached to the cinder block.
Wire Rope
Shown above is the final setup using wire rope with wire rope clips and turnbuckles. Zip ties prevent the turnbuckles from escaping from the eye bolts.
This provided a really solid connection from the ballast to the tripod. The turnbuckles are tensioned so that they were one twist away from raising the concrete block a smidge off the surface of the roof.
Lessons Learned
Lesson 1 - The Wind is Strong
Boulder is known for strong gusts of wind that can break 100MPH (160KPH) a few times a year. Finding a location on my roof where I could solidly attach the system was crucial. I didn't watch to drill into my roof or the sides of the house, so instead I decided to use a tripod with ballast to hold the station in place.
When I originally setup the weather station I calculated (with words in my head) that a single 35lbs block would hold the station in place. Should be fine...
This first setup used zip ties to tension the two blocks to the base of the tripod. Unfortunately I had some really bad zip ties. You know - the ones that snap or release as soon as you put a bit of force behind them? I know this attachment system was questionable, but note the snow and my decision to start this project in December.
After a bit of Googling, I discovered these things called turnbuckles! Wow they work. You probably fall into one of two categories. Either you know exactly what wire rope is, and you think I'm crazy, or you're like me, never anchored something before, and think zip ties'll do it. Believe me - they won't.
The third setup adds a proper turnbuckle and wire rope. This setup is really nice and solid! The turnbuckle makes it really easy to tension the full 35lbs onto the tripod. Who needs the second ballast?
There are roughly a dozen nights a year in Boulder, CO where you question the build quality of your home. The windows vibrate, the walls shake, and you lay awake at night thinking about the large trees out front coming down on your car. On February 20th, 2014, the station blew over. A cup broke off the anemometer, the wind direction vane broke off completely, and the solar cell broke off its mount. The damage was rough, but I'm lucky the station didn't leave the roof entirely.
Late on February 20th, the station clocked a few 50mph gusts before the ballast was moved 6 inches and the turnbuckle came unhooked from the eye bolt. The station blew over, the Imp SD card popped out of the socket on the shield, and Wimp stopped reporting.
Because one ballast was attached and one was not, we get a neat view into how much the station actually dragged 35lbs across the roof. I believe the station would have not been blown over if the turnbuckle had not worked itself out of the eye bolt. Remember the previous picture? I never zip tied the hook to hold it against the eye bolt.
Here's what the setup looks like today. I don't recommend using zip ties for loads any more, but they do a great job of making sure the hooks won't escape the eye bolts.
Lesson 2 - Make it Accessible
Above all else, put the Wimp where it can be easily maintained. Things will break - be sure you can access your weather station with as little danger as possible.
You may think you'll only have to do maintenance on the weather station once a year. If you're building your own, plan to be in the station once a week in the beginning and once a month after you get it up and running.
I ended up having to replace the battery pack a few times. I had problems with my solar charger due to a rouge piece of code failing to put the Imp properly to sleep and because the solar cell was shaded by a large clamp (repairs post wind storm). Even with the best laid plans, you'll find yourself on the roof, in February, wondering why you started this project...
Lesson 3 - The Code is Wrong
No matter how much you try to prevent it, there will be problems with your code. Even Spirit, the Mars rover, had a rolling reboot issue. I had similar problems with small errors including a bug that arbitrarily zeroed the wind gust measurement.
When I started this project, I assumed the Arduino portion of the project would have to be locked in because who wants to climb on their roof to plug in a USB cable to reprogram the Arduino? Luckily, a few weeks after the first station was built I discovered the Imp could wirelessly reprogram the Arduino. This has proven to be extremely helpful. If you can, plan for bad code, and make your device remotely reprogrammable.
Resources and Going Further
By building your own weather station, not only are you learning a ton about DIY electronics, but you also get a good taste of what it takes to deploy an electronics project in the real world. And congratulations - you've added something to this thing everyone keeps calling the Internet of things. It's a good thing! More weather data means better forecasting in the future.
This was a big tutorial to write! We hope you've enjoyed it. If you've got similar weather projects or lessons, please let us know.
Extra Resources:
- Read more about the Electric Imp
- Hacking MindWave Mobile
- Making Simon Says Wireless | https://learn.sparkfun.com/tutorials/weather-station-wirelessly-connected-to-wunderground?_ga=1.96543519.1661814591.1474882863 | CC-MAIN-2020-45 | refinedweb | 6,213 | 61.26 |
unittest-based test runner with Ant/JUnit like XML reporting.
Project description
unittest-xml-reporting (aka xmlrunner)
A unittest test runner that can save test results to XML files in xUnit format. The files can be consumed by a wide range of tools, such as build systems, IDEs and continuous integration servers.
Schema
There are many schemas with minor differences.
We use one that is compatible with Jenkins xUnit plugin, a copy is
available under
tests/vendor/jenkins/xunit-plugin/junit-10.xsd (see attached license).
- Jenkins (junit-10.xsd), xunit plugin (2014-2018), please note the latest versions (2.2.4 and above are not backwards compatible)
You may also find these resources useful:
-
-
- Jenkins (junit-10.xsd), xunit plugin 2.2.4+
- JUnit-Schema (JUnit.xsd)
- Windyroad (JUnit.xsd)
- a gist (Jenkins xUnit test result schema)
Things that are somewhat broken
Python 3 has the concept of sub-tests for a
unittest.TestCase; this doesn't map well to an existing
xUnit concept, so you won't find it in the schema. What that means, is that you lose some granularity
in the reports for sub-tests.
Requirements
- Python 3.5+
- Please note Python 2.7 end-of-life was in Jan 2020, last version supporting 2.7 was 2.5.2
- Please note Python 3.4 end-of-life was in Mar 2019, last version supporting 3.4 was 2.5.2
- Please note Python 2.6 end-of-life was in Oct 2013, last version supporting 2.6 was 1.14.0
Installation
The easiest way to install unittest-xml-reporting is via Pip:
$ pip install unittest-xml-reporting
If you use Git and want to get the latest development version:
$ git clone $ cd unittest-xml-reporting $ sudo python setup.py install
Or get the latest development version as a tarball:
$ wget $ unzip master.zip $ cd unittest-xml-reporting $ sudo python setup.py install
Or you can manually download the latest released version from PyPI.
Command-line
python -m xmlrunner [options] python -m xmlrunner discover [options] # help python -m xmlrunner -h
e.g.
python -m xmlrunner discover -t ~/mycode/tests -o /tmp/build/junit-reports
Usage
The script below, adapted from the
unittest, shows how to use
XMLTestRunner in a very simple way. In fact, the only difference between
this script and the original one is the last line:
import random import unittest import xmlrunner class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = list(range(10)) @unittest.skip("demonstrating skipping") def test_skipped(self): self.fail("shouldn't happen")( testRunner=xmlrunner.XMLTestRunner(output='test-reports'), # these make sure that some options that are not applicable # remain hidden from the help menu. failfast=False, buffer=False, catchbreak=False)
Reporting to a single file
if __name__ == '__main__': with open('/path/to/results.xml', 'wb') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False)
Doctest support
The XMLTestRunner can also be used to report on docstrings style tests.
import doctest import xmlrunner def twice(n): """ >>> twice(5) 10 """ return 2 * n class Multiplicator(object): def threetimes(self, n): """ >>> Multiplicator().threetimes(5) 15 """ return 3 * n if __name__ == "__main__": suite = doctest.DocTestSuite() xmlrunner.XMLTestRunner().run(suite)
Django support
In order to plug
XMLTestRunner to a Django project, add the following
to your
settings.py:
TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
Also, the following settings are provided so you can fine tune the reports:
Contributing
We are always looking for good contributions, so please just fork the repository and send pull requests (with tests!).
If you would like write access to the repository, or become a maintainer, feel free to get in touch.
Testing changes with
tox
Please use
tox to test your changes before sending a pull request.
You can find more information about
tox at.
$ pip install tox # basic sanity test, friendly output $ tox -e pytest # all combinations $ tox
Project details
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/unittest-xml-reporting/ | CC-MAIN-2020-10 | refinedweb | 672 | 59.9 |
Hi all,
Does anybody know how to merge two PDFs using Python while maintaning layers as shown on the attached picture?
I am using arcpy for ArcGIS Pro to export an 'Overview' PDF and a 'Detailed Location' PDF.
Both PDFs contain the layers once they're opened on PDF viewer. However, when I merge both PDF 'lots' within a single 'Map Book' PDF using 'arcpy.PDFDocumentCreate' and '<pdfDoc>.appendPages', those layers are lost.
I have also tried PdfFileMerger within PyPDF2 Library without success,
Any thoughts?
Thanks, Ana
Hi! In case anyone else needs it... Use the PDF merger from the Arcmap arcpy. The drawback is that for each PDF you have a list of layers, separately. I don't really like that.
def merge_all(dict_paths, out_dir):
for empl, pdfs in dict_paths.items():
out_pdf = os.path.join(out_dir,"{0}.pdf".format(empl))
# pdfDoc = arcpy.mp.PDFDocumentCreate(out_pdf) #this is for Pro
pdfDoc = arcpy.mapping.PDFDocumentCreate(out_pdf)
for pdf in pdfs:
pdfDoc.appendPages(pdf)
pdfDoc.updateDocProperties(pdf_open_view= "LAYERS")
pdfDoc.saveAndClose() | https://community.esri.com/t5/arcgis-pro-questions/merging-pdfs-without-losing-layers-pdf-viewer/td-p/592663 | CC-MAIN-2022-21 | refinedweb | 168 | 54.9 |
Deploying a Simple Golang Web App on Heroku
A developer and DZone Core member gives an in-depth tutorial on how to create a web application using the Go language, the Gin web framework, and Heroku.
Join the DZone community and get the full member experience.Join For Free
The Go programming language, often referred to as "Golang," has gained a lot of well-deserved traction in the DevOps community. Many of the most popular tools such as Docker, Kubernetes, and Terraform are written in Go, but it can also be a great choice for building web applications and APIs.
Go provides you with all the speed and performance of a compiled language, but feels like coding in an interpreted language. This comes down to the great tooling that you get out of the box with a compiler, runner, test suite, and code formatter provided by default. Add to that the robust and easily comprehensible approach to concurrency, to take maximum advantage of today's multi-core or multi-CPU execution environments, and it's clear why the Go community has grown so rapidly.
Go feels like it was created with specific goals in mind, leading to a deceptively simple language design that's straightforward to learn, without compromising on capabilities.
In this post, I'm going to show you how easy it is to develop a simple web application in Go, package it as a lightweight Docker image, and deploy it to Heroku. I'll also show a fairly new feature of Go: built-in package management.
Go Modules
I'm going to use Go's built-in module support for this article.
Go 1.0 was released in March 2012. Up until version 1.11 (released in August 2018), developing Go applications involved managing a GOPATH for each "workspace," analogous to Java's
JAVA_HOME, and all of your Go source code and any third-party libraries were stored below the
GOPATH.
I always found this a bit off-putting, compared to developing code in languages like Ruby or JavaScript where I could have a simpler directory structure isolating each project. In both of those languages, a single file (
Gemfile for Ruby,
package.json for JavaScript) lists all the external libraries, and the package manager keeps track of managing and installing dependencies for me.
I'm not saying you can't manage the
GOPATHenvironment variable to isolate projects from one another. I particularly find the package manager approach is easier.
Thankfully, Go now has excellent package management built in, so this is no longer a problem. However, you might find
GOPATH mentioned in many older blog posts and articles, which can be a little confusing.
Hello, World!
Let's get started on our web application. As usual, this is going to be a very simple "Hello, World!" app, because I want to focus on the development and deployment process, and keep this article to a reasonable length.
Pre-requisites
You'll need:
- A recent version of Golang (I'm using 1.14.9.)
- Docker
- A Heroku account (the free account works fine for this example.)
- The Heroku command-line client
- git
Go mod init
To create our new project, we need to create a directory for it, and use the
go mod init command to initialize it as a Go module.
xxxxxxxxxx
mkdir helloworld
cd helloworld
go mod init digitalronin/helloworld
It's common practice to use your GitHub username to keep your project names globally unique, and avoid name conflicts with any of your project dependencies, but you can use any name you like.
You'll see a
go.mod file in the directory now. This is where Go will track any project dependencies. If you look at the contents of the file, they should look something like this:
xxxxxxxxxx
module digitalronin/helloworld
go 1.14
Let's start committing our changes:
xxxxxxxxxx
git init
git add *
git commit -m "Initial commit"
Gin
We're going to use Gin for our web application. Gin is a lightweight web framework, similar to Sinatra for Ruby, Express.js for Javascript, or Flask for Python.
Create a file called
hello.go containing this code:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.String(200, "Hello, World!")
})
r.Run(":3000")
}
Let's break this down a little:
xxxxxxxxxx
r := gin.Default()
This creates a router object,
r, using the built-in defaults that come with Gin.
Then, we assign a handler function to be called for any HTTP GET requests to the path
/hello, and to return the string "Hello, World!" and a 200 (HTTP OK) status code:
xxxxxxxxxx
r.GET("/hello", func(c *gin.Context) {
c.String(200, "Hello, World!")
})
Finally, we start our web server and tell it to listen on port 3000:
xxxxxxxxxx
r.Run(":3000")
To run this code, execute:
xxxxxxxxxx
go run hello.go
You should see output like this:
xxxxxxxxxx
go:go:
Now if you visit in your web browser, you should see the message "Hello, World!"
Notice that we didn't have to install Gin separately, or even edit our
go.mod file to declare it as a dependency. Go figures that out and makes the necessary changes for us, which is what's happening when we see these lines in the output:
xxxxxxxxxx
go: finding module for package github.com/gin-gonic/gin
go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.6.3
If you look at the
go.mod file, you'll see it now contains this:
xxxxxxxxxx
module digitalronin/helloworld
go 1.14
require github.com/gin-gonic/gin v1.6.3 // indirect
You will also see a
go.sum file now. This is a text file containing references to the specific versions of all the package dependencies, and their dependencies, along with a cryptographic hash of the contents of that version of the relevant module.
The
go.sum file serves a similar function to
package-lock.json for a JavaScript project, or
Gemfile.lock in a Ruby project, and you should always check it into version control along with your source code.
Let's do that now:
xxxxxxxxxx
git add *
git commit -m "Add 'Hello world' web server"
Serving HTML and JSON
I'm not going very far into what you can build with Gin, but I do want to demonstrate a little more of its functionality. In particular, sending JSON responses and serving static files.
Let's look at JSON responses first. Add the following code to your
hello.go file, right after the
r.GET block:
xxxxxxxxxx
api := r.Group("/api")
api.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
Here we're creating a "group" of routes behind the path
/api with a single path
/ping which will return a JSON response.
With this code in place, run the server with
go run and then hit the new API endpoint:
xxxxxxxxxx
curl
You should get the response:
xxxxxxxxxx
{"message":"pong"}
Finally, let's make our web server serve static files. Gin has an additional library for this.
Change the import block at the top of the
hello.go file to this:
xxxxxxxxxx
import (
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
)
The most popular code editors have Golang support packages you can install which will take care of the
importdeclarations for you automatically, updating them for you whenever you use a new module in your code.
Then, add this line inside the
main function:
xxxxxxxxxx
r.Use(static.Serve("/", static.LocalFile("./views", true)))
The full code for our web application now looks like this:
hello.go
xxxxxxxxxx
package main
import (
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/hello", func(c *gin.Context) {
c.String(200, "Hello, World!")
})
api := r.Group("/api")
api.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Use(static.Serve("/", static.LocalFile("./views", true)))
r.Run()
}
The
r.Use(static.Serve... line enables our web server to serve any static files from the
views directory, so let's add a few:
xxxxxxxxxx
mkdir -p views/css
views/css/stylesheet.css
xxxxxxxxxx
body {
font-family: Arial;
}
h1 {
color: red;
}
views/index.html
xxxxxxxxxx
<html>
<head>
<link rel="stylesheet" href="/css/stylesheet.css" />
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
Now restart the web server using
go run hello.go and visit and you should see the styled message:
Dockerize
We've written our Go web application, now let's package it up as a Docker image. We could create it as a Heroku buildpack, but one of the nice features of Go is that you can distribute your software as a single binary file. This is an area where Go really shines, and using a Docker-based Heroku deployment lets us take advantage of that. Also, this technique isn't limited to Go applications: you can use Docker-based deployment to Heroku for projects in any language. So, it's a good technique to understand.
So far, we've been running our code with the
go run command. To compile it into a single, executable binary, we simply run:
xxxxxxxxxx
go build
This will compile all our Go source code and create a single file. By default, the output file will be named according to the module name, so in our case it will be called
helloworld.
We can run this:
xxxxxxxxxx
./helloworld
And we can hit the same HTTP endpoints as before, either with
curl or our web browser.
The static files are not compiled into the binary, so if you put the
helloworldfile in a different directory, it will not find the
viewsdirectory to serve our HTML and CSS content.
That's all we need to do to create a binary for whatever platform we're developing on (in my case, my Mac laptop). However, to run inside a Docker container (for eventual deployment to Heroku) we need to compile a binary for whatever architecture our Docker container will run on.
I'm going to use Alpine Linux, so let's build our binary on that OS. Create a
Dockerfile with the following content:
xxxxxxxxxx
FROM golang:1.14.9-alpine
RUN mkdir /build
ADD go.mod go.sum hello.go /build/
WORKDIR /build
RUN go build
In this image, we start with the
golang base image, add our source code, and run
go build to create our
helloworld binary.
We can build our Docker image like this:
xxxxxxxxxx
docker build -t helloworld .
Don't forget the trailing
.at the end of that command. It tells Docker we want to use the current directory as the build context.
This creates a Docker image with our
helloworld binary in it, but it also contains all the Go tools needed to compile our code, and we don't want any of that in our final image for deployment, because it makes the image unnecessarily large. It can also be a security risk to install unnecessary executables on your Docker images.
We can see the size of our Docker image like this:
xxxxxxxxxx
$ docker images helloworld
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld latest 9657ec1ca905 4 minutes ago
For comparison, the
alpine image (a lightweight Linux distribution, often used as a base for Docker images) is much smaller:
xxxxxxxxxx
$ docker images alpine
REPOSITORY TAG IMAGE ID CREATED SIZE
alpine latest caf27325b298 20 months ago
On my Mac, the
helloworld binary is around 14MB, so the Golang image is much bigger than it needs to be.
What we want to do is use this Dockerfile to build our
helloworld binary to run on Alpine Linux, then copy the compiled binary into an Alpine base image, without all the extra Golang tools.
We can do this using a "multistage" Docker build. Change the Dockerfile to look like this:
xxxxxxxxxx
FROM golang:1.14.9-alpine AS builder
RUN mkdir /build
ADD go.mod go.sum hello.go /build/
WORKDIR /build
RUN go build
FROM alpine
RUN adduser -S -D -H -h /app appuser
USER appuser
COPY --from=builder /build/helloworld /app/
COPY views/ /app/views
WORKDIR /app
CMD ["./helloworld"]
On the first line, we label our initial Docker image
AS builder.
Later, we switch to a different base image
FROM alpine and then copy the
helloworld binary from our builder image like this:
xxxxxxxxxx
COPY --from=builder /build/helloworld /app/
Build the new Docker image:
xxxxxxxxxx
docker build -t helloworld .
Now, it's the size you would expect for a base Alpine image plus our
helloworld binary:
xxxxxxxxxx
$ docker images helloworld
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld latest 1d6d9cb64c7e 8 seconds ago
We can run our web server from the Docker image like this. (If you have another version running using
go run hello.go or
./helloworld, you'll need to stop that one first, to free up port 3000.)
docker run --rm -p 3000:3000 helloworld
The dockerized webserver should behave just like the
go run hello.goand
./helloworldversions except that it has its own copies of the static files. So, if you change any of the files in
views/you won't see the changes until you rebuild the Docker image and restart the container.
Deploy to Heroku
Now that we have our dockerized web application, let's deploy it to Heroku. Heroku is a PaaS provider that makes it simple to deploy and host an application. You can set up and deploy your application through the Heroku UI, or through the Heroku CLI. For this example, we'll use the Heroku command-line application.
Getting PORT From an Environment Variable
We've hard-coded our web server to run on port 3000, but that won't work on Heroku. Instead, we need to alter it to run on whichever port number is specified in the
PORT environment variable, which Heroku will supply automatically.
To do this, alter the
r.Run line near the bottom of our
hello.go file, and remove the
":3000" string value so the line becomes:
xxxxxxxxxx
r.Run()
The default behavior of Gin is to run on whatever port is in the
PORT environment variable (or port 8080 if nothing is specified). This is exactly the behavior Heroku needs.
Setting up Our Heroku app
First, log into Heroku:
xxxxxxxxxx
heroku login
Now, create an app:
xxxxxxxxxx
heroku create
Tell Heroku we want to build this project using a Dockerfile, rather than a buildpack:
xxxxxxxxxx
heroku stack:set container
To do this, we also need to create a
heroku.yml file like this:
xxxxxxxxxx
build
docker
webDockerfile
run
web./helloworld
The
heroku.yml file is a manifest that defines our app and allows us to specify add-ons and config vars to use during app provisioning.
Next, add git and commit these files, then push to Heroku to deploy:
xxxxxxxxxx
git push heroku main
My git configuration uses
mainas the default branch. If your default branch is called
master, then run
git push heroku masterinstead.
You should see Heroku building the image from your Dockerfile, and pushing it to the Heroku Docker registry. Once the command completes, you can view the deployed application in your browser by running:
xxxxxxxxxx
heroku open
Conclusion
To recap, here's a summary of what we covered today:
- Creating a Golang web application, using Go modules and the Gin web framework to serve strings, JSON, and static files.
- Using a multistage Dockerfile to create a lightweight Docker image.
- Deploying a Docker-based application to Heroku using
heroku stack:set containerand a
heroku.ymlfile.
I've only scratched the surface in this article on how to use Go to build web applications and APIs. I hope this gives you enough to get started on your own Golang web applications.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/deploying-a-simple-golang-webapp-on-heroku | CC-MAIN-2021-49 | refinedweb | 2,654 | 63.8 |
hwi_find_item()
Find an item in the hwinfo structure
Synopsis:
#include <hw/sysinfo.h> unsigned hwi_find_item( unsigned start, ... );
Since:
BlackBerry 10.0.0
Arguments:
- start
- Where to start the search for the given item..
This function is in libc.a, but not in libc.so (in order to save space).
Description:
The hwi_find_item() function finds an item in the hwinfo structure of the system page.
Returns:
The offset of the item requested, or HWI_NULL_OFF if the item wasn't found.
Examples:);
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/h/hwi_find_item.html | CC-MAIN-2014-42 | refinedweb | 102 | 72.12 |
SeekBar Android Example Code and Tutorial
Understand how the
SeekBar is used in an Android App. This tutorial provides some SeekBar Android example code for you to try out. This demo code for the SeekBar appeared in a pre-Android Studio API Demos app that came with earlier versions of the Android Software Development Kit (SDK).
(Up until Android API 17, Jelly Bean MR1, the Google Android sample code came as Eclipse projects. The API Demos project was one of them. From Android API 18, Jelly Bean MR2, the Eclipse projects became Legacy samples and a new set of Android Studio sample projects appeared. The Android samples are no longer shipped with the SDK. From Android API 24, Nougat, the samples are online and the legacy samples are only available if the older APIs are installed with the SDK Manager.)
The legacy API Demos app is very large and it can be difficult to find the sample code you need. Putting the SeekBar Android example here allows it to be easily seen.
(This Android SeekBar.)
ProgessBar That Can Be Dragged
The SeekBar is a useful User Interface (UI) control. It allows a user to easily vary an integer value simply by dragging left or right. Although for very large integer values you may not have fine control and a
EditText may be a better option. For small values, such as a percentage, it is a good solution for providing a value setting interface.
What Does an Android SeekBar Look Like?
The SeekBar Android Example Code
Start by generating a new app in Android Studio, here it is called SeekBar Demo. An Empty Activity is used with all other settings left at their default values. You can of course add the SeekBar to an existing app by adapting the code.
Either delete the default Hello World! and drop a SeekBar (given an id of seek) and two TextViews (given ids progress and tracking) onto the app screen, or replace the code, here in activity_main.xml, with the following:
<LinearLayout xmlns: <SeekBar android: <TextView android: <TextView android: </LinearLayout>
There are three string values are added to strings.xml in the res/values folder. The full strings.xml now looks like this:
<resources> <string name="app_name">SeekBar Demo</string> <string name="seekbar_tracking_on">Tracking on</string> <string name="seekbar_tracking_off">Tracking off</string> <string name="seekbar_from_touch">from touch</string> </resources>
Here is the Java code for the SeekBar for the MainActivity.java file.
package com.example.seekbardemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.SeekBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { TextView mProgressText; TextView mTrackingText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ((SeekBar)findViewById(R.id.seek)).setOnSeekBarChangeListener(this); mProgressText = (TextView)findViewById(R.id.progress); mTrackingText = (TextView)findViewById(R.id.tracking); } public void onStopTrackingTouch(SeekBar seekBar) { mTrackingText.setText(getString(R.string.seekbar_tracking_off)); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { mProgressText.setText(progress + " " + getString(R.string.seekbar_from_touch) + "=" + fromTouch); } public void onStartTrackingTouch(SeekBar seekBar) { mTrackingText.setText(getString(R.string.seekbar_tracking_on)); } }
This simple SeekBar Android example should be enough to get you up and running with the SeekBar in your App. The App should run without any errors. If it fails to run examine the error messages to find the fault.
See Also
- Download the code for this example, available in seekbar-demo.zip
- See the Android Developer page for the SeekBar class for more information.
- Android Example Projects
- For a full list of all the articles in Tek Eye see the full site alphabetical Index.
Author:Daniel S. Fowler Published: Updated: | https://tekeye.uk/android/examples/ui/seekbar-android-example | CC-MAIN-2019-13 | refinedweb | 604 | 50.43 |
Problems when sending float (temperatur) with VirtualWire Arduino
- Login or register to post comments
- by the_droid
// User Gareth
// Project Node // Remote Receiving Temparature and Humidity over RF Link to LCD Display // how to use VirtualWire to receive messages and display floating point values to SerialMonitor // rx pin 23 on mega #include #undef int #undef abs #undef double #undef float #undef round void setup() { Serial.begin(9600); // Debugging only // Initialise the IO and ISR vw_set_ptt_inverted(true); // Required for DR3100 vw_setup(2000); // Bits per sec vw_set_rx_pin(23); vw_rx_start(); // Start the receiver PLL running } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) // Non-blocking { int i; digitalWrite(13, true); // Flash a light to show received good message // Message with a good checksum received, dump it. for (i = 0; i < buflen; i++) { Serial.print(buf[i]); // the received data is stored in buffer } Serial.println(""); } }
Thats the Reciever Code
Guys, I set the SerialMonitor to 9600.. and I got:
ÿ23.0ßC þ35.0% defintly not what I expected ^^ Any idea how I can fix that?
Set your monitor to 9600
Set your monitor to 9600 baud input to go along with the:
Serial.begin(9600);
// other setup instructions
}
I set the monitor to 9600
When I set the monitor to 9600 i get :ÿ23.0ßC þ35.0%
That sucks -.-
Tried other baudrates yet?
The code which works
I did a quick search for float to string arduino
The first hit I got suggested via a forum post that:
#include <stdlib.h>
dtostrf(FLOAT,WIDTH,PRECSISION,BUFFER);
Double Post. Sorry.
dev/null
You failed to let us know ...
what version of the DHT library you are using. The one I grabbed does not differentiate two sensors the way the one yours does.
All of this means I can not replicate your issues until I know what DHT lib you are using.
Adafruit... who else.
...looks like it is this one here. Sample here.
Turn it into a integer problem?
You can try to send the humidity value as a tupel of two int values. So then your float to char* problem turns into a int to char* problem.
There are several techniques to do that. A simple one is to take the truncated integer part of your humidity value into int A and the scaled floating part into int B. So a number like 1234.5678 turns into A: "1234" and B: "5678" (Scaling-Factor: 1000).
This two integers can be transmitted as two char* now.
Here is a transmitter code snippet:
Here is a receiver code:
...
This is my test setup. | http://letsmakerobots.com/node/35577 | CC-MAIN-2015-14 | refinedweb | 431 | 65.32 |
- problem
- form objects
- How do I pass a string to a function?
- ajax wilgets javascript
- How to create menus using javascript?
- Alternate for Showmodaldialog in mozilla firefox
- Case Conversion
- onfocus() is working fine in IE but not in Firefox
- newbie: removeChild() on table does nothing
- Using AJAX/JSON and performance issues with eval()
- Msgbox Abort retry button only.
- Last number standing problem: extract number at specified position in array
- How to Count the number of lines?
- How can get the id of the focused element of the web page
- If button clicked, value should be reflected in text box
- Randomize HTML Table Rows from JavaScript
- How to Match Line Breaks using Regular Expression
- need some help to write a javascript function
- UI Libraries
- How do I get a text value from an input element?
- Drop down with MASSIVE list
- Question about function objects vs object literals?
- How to supress "location" in window
- Passing data back from AJAX call
- Re: Question on JavaScript
- Is it possible to find out the number of frames in a html page?
- Class diagrams for javascript
- document.getElementById stopped working after adding an iframe
- IMG Javascript question
- How can I disable drag and drop?
- Object Expected Error
- Cell Style in Dojo Grid
- Problem with onchange event and apex/apostrophe
- Javascript tabbed navigation..
- FAQ Topic - How do I trim whitespace - trim/trimRight/trimLeft (2008-06-30)
- Web Page doesn't work on new FireFox 3: JavaScript function untriggered!
- IE (naturally) select-option bug, workaround?
- change the parent window of a DIV.
- This should be simple but Simple left the building.
- vml editor drawing image to be saved
- Mind map with Ajax
- Working with iframe history
- reCaptcha
- server-side JavaScript: Example 3: Dictionary class
- GromJS server-side JavaScript
- Variable initialization with curly braces
- getting problem in window.onbeforeunload
- Fading / Rotating Images
- About simple form validation
- Populate HTML Form from Text file...
- Re: How do links know they have been visited?
- Re: looping through variable question
- Re: Replacing a private function an keeping access to privatevariables
- Re: Adding CSS units to an old JS Script
- page contains both secure and nonsecure items When setting locationin IE6
- Re: Replacing a private function an keeping access to private variables
- AJAX Question
- JDOMP - DB access without AJAX using the DOM
- Pop Up Window in JavaScript
- Getting action info from popup to main window
- Accessing private members of a different scope in the same type
- Private static members in JavaScript
- window.open problem
- repeated XMLHttpRequest GETs and displaying result
- Regexp: Case-insensitive matching | N factorial
- splice an array into another array
- Access Denied
- Need Help with Calculator Java Script
- mouse middle click disabling
- newbie: validator?
- Is there any javascript function available to auto resize swf
- waiting on GM_xmlhttprequest to finish
- trying to loop an xml page from ajax
- help with JSON
- Re: some good JS sites?
- Javascript error occuring on new build machine
- Drag and drop problem, please help?
- Text box value keeps resetting after submit
- Any body give me solution
- Run function from form text input on Enter
- Re: some good JS sites?
- Convert array to string after "for loop" is finished
- //<![CDATA[
- nested accordions with internal links?
- 5 brand new & working Javascript tricks
- newbie: reading radio selection
- debugging in aptana
- reaching html elements
- Writing Arrays To <select> Tag
- Creating DIV Tag
- Can JavaScript use a function before it's defined?
- FAQ Topic - Why does simple decimal arithmetic give strange results? (2008-06-21)
- Anybody wanna check my company's website?
- window.open
- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? (2008-06-20)
- Creating files on client side using javascript
- tableless design ==> practical problems???
- CHECK BOX Problem
- Downloading java runtime environment
- mostrar ocultar etiquetas div desde un ID
- Size of an object
- OBJECT EXPECTED ERROR.
- Need a dropdown list that holds the value
- Automatic update of website
- Regex
- reconnect after lost connection (googletalk style?)
- Client Images and Screencaps Quickie Display
- Javascript Namespace
- newbie: some errors reported by validator
- GetElementbyID Issue
- XML validation with parseFromString on Safari
- New browsers : SunSpider JavaScript Benchmark Results.
- Pulling my hair out
- Date in Opera 9.50
- Getting correct value from radio button
- Trivial Question About Quotes
- hi5 opensocial Issue of syntax error: ..... rc:504 error,inJavaScript making request .Please Somebody Help for me
- How to get ride of the Caption that says "Rotator" on a bannerrotator?
- invoking a function with variable number of arguments
- IE Jpeg opacity?
- funciones especiales anidadas
- making pacman game.... logic problems
- unload event more restrictive now on Safari 3.1 ?
- send email having some fields on the form using only html andjavascript anybody knows
- Listbox containing check boxes
- Prototype.js vs other JS libraries
- creating graphs in javascript/etc
- validation
- Terms for method types?
- coding conventions/good practices in js
- How do I get HTML sent to server?
- Re: Safari and className oddity?
- Hide all elements of a specific class
- What to read first...?...
- Printing Question
- dynamically generating html vs using html scaffolding?
- How to add a text-button (like a hyperlink)?
- This code requires the user 2 click the mouse twice, how do i do itin just one mouse-click?
- PDF INTO MSIE POPUP
- newbie: problem with calling or including .js file
- I'm dumb, you're not... can you help me?
- FAQ Topic - What books cover javascript? (2008-06-13)
- simple chat script
- window.onload being ignored for child in IE
- eval
- Whats wrong with this code?
- Array constructor or literal
- message of 'is null or not an object'
- Two Popups on One Click
- open and close a window
- Javascript variable as method
- Help with basic onClick mechanism please
- JavaScript inheritance: How to call my parent method?
- Making a "quiz" using Javascript
- Drag a file from Desktop and Drop into Browser File Element
- X-JSON encoding problem
- Can't change text field value in IE
- why file upload cannot work?
- assigning event with attachEvent instead of onmouseover
- Baffling array problem
- regx, global efficiencies?
- Should the webserver add "Content-Type: text/xml header" to the requested XML file?
- Working more efficiently in Javascript
- inherited private variables
- converting js file into dll
- Window.open. Works in ie6. Does not work in firefox
- No access to variables in parent document
- Resize IFRAME
- Show/Hide ... Need help in simple funcion
- Javascript parameters
- onfocus after alert box.
- calling function with "return function()"
- knowing where the user comes from
- how can I overwrite a prototype function?
- IE bug?
- Logo for Single Page Interface (SPI) web applications
- Hide Divs
- HTML Help
- count words
- creating forms dynamically from a flat file
- Javascript in an HTML table
- Any way to disable CSS via javascript?
- Learning Javascript
- Pick value in dropdown combo on WebBrowser page
- Another AJAX question
- How to send collection of parameters as options to an format function
- Closures for undo: bad idea?
- onClick not firing for an ImageMap Area
- Firefix VS IE
- Is it possible to get a function's scope chain?
- javascipt to bust out of iframe
- How Mozilla implements the Extension Functions
- waiting for page to load
- Save link As
- Regexp : invalid quantifier +
- stack size limit ?
- FireFox Problem
- Fast search for all positions in a string
- How to display a child element while hiding a parent
- Disabling System menu in a modal window with Javascript
- Prototype: Update with multiple elements and texts
- newbie question: who clicked on me?
- Need JavaScript based drawing/signature box
- onClick vs Enter Key
- Can someone fix this watermark cut-n-past script by Paul Anderson to work with a Transitional Doctype
- Dynamically Assigning OnChange Handler
- {J,Java}Script improvements/changes in IE 8
- Creating custom methods to use with HTML DOM objects
- Question with AJAX
- page event to hide floating div
- Getting size of window?
- Once Per Session Cookie
- <xmp> with innerHTML to display source code
- Trim functions
- missing : after property id error
- document.lastModified help
- get a single word from point(x,y)
- Linked dropdowns
- DOM dynamically built table and addEventListener....
- Re: field value AFTER numeric validation
- Can JS bring up the Open With/Save As dialog?
- Javascript onClick question
- IE6 Garbage Collection and general IE6 slowness problems
- constructor/destructor
- Disabling a table
- JavaScript assign by value vs reference
- slow response in table cells <TD> to mouseover with IE6 but fine inFirefox.
- onSubmit and Internet Explorer = trouble
- Javascript on the client as an alternative to Perl/PHP/Python on theserver
- Submitting Forms
- Form Gray Filter
- Re: field value AFTER numeric validation
- Can you make them table insertRow and insertBefore (element) worktogether?
- onchange event in IEMobile
- IE7 works worse than IE6 on web pages - Can javascript save thesituation?
- how to retrieve the data in array with html element access?
- Local storage question
- List events of an element wired up with addEventListener
- clip board data as html
- regex failing
- Array manipulation question
- instanceof operator
- Trouble With Date Code
- Can I change a p into a textarea?
- Turn of the "Ding" sound when user presses enter
- Method of element identification and emulation of click event
- javascript programming idiom
- buscar y mostrar div segun datos de entrada
- Attach a class method to event handler
- Dynamically loading JS into iFrames - preventing IE7 popups whenleaving/entering secure connection
- Client side validations for dynamically added user control
- Individual XmlHttpRequest requests over HTTPS??
- tree in ajax for mysql
- iframe src variables
- setTimeout and anonymous functions
- How do i getElementById("a") and add a class to it, using JavaScript,halfway there?
- Re: Weird Javascript "test is not defined" error.
- small application in java.script
- download file
- how to pass a parameter to some bound function?
- Moving the cursor (insertion point) in an input (text) field
- Replacing document.getElementById with $ (dollar sign)
- checking results - a silly mistake?
- Show GreyBox Pop Up Only Once?
- 404 errors
- cursor lost it hand
- Access to <img> pixels
- What is causing error with this call to a .js file
- Lots of noise about user agent strings
- Doctype use kills some javascripts
- Remove Empty Tags on page
- unknown runtime error in IE
- arcane quotes problem again
- document.forms[formName].elemName
- Add new text box after entered text
- Can someone explain the purpose of this syntax
- disable slider onchange
- Basic Question
- function call
- Looking For Online/Book References...
- Changing <div> width in IE
- how to submit iframed form to top or whole window
- Differences between perhaps-similar constructs?
- Foglio dati malleabile
- leaving the space when the function is clicked (getting problem inIE) in monzilla its fine
- The mothod "on" not available for a button?!
- Hidden Element
- Iterating through nested associative arrays
- Removing plus signs from URL query string
- Why Doesn't This Work In Firefox?
- createElement('div') into HTML table problem in IE 6.
- How to mimic Excel download?
- Connecting a callback action listener WITH parameters
- Problem with loading image in FF-Win
- Calender(date picker) table is scrolling with the popup window.
- How optimized ar eif-statements in JS
- javascript weird problem ( a newbie)
- Getting a click from the PC-speaker?
- popup in javascript
- little endian
- Is it possible to retrieve http response status?
- Script won't work in IE
- Calling internal 'public' methods within js objects
- Using jS to display an image from file
- object.onmouseover
- <a href='#' onClick="fun()"; is not working in IE
- submitting a page
- Cross domain iframe access
- Mouseover and print and screen shot
- Problem with InnerHTML require alternative
- wait for event
- newbie question - how do you *require* a response?
- hi
- Question about a select list? (code attached)
- Black screen with trasparent photo
- Capturing scroll bar usage on textarea
- Get text content of a div with YAHOO Dom.getFirstChild(div)?
- Noobie onclick, confirm, return false ??
- Retrieving document's certificate in JS
- textbox validation
- Function is not defined (but it is)
- table.rows vs. table.getElementsByTagName (+ a regex question)
- cyclic_proto_value
- Efficiently detecting a click in a large table
- Re: A Newbie's Must-Have Library
- javascript to move a DIV using the DOM
- Moving a string from client to server (JS -> ASPX)
- keyboard events and dead letters
- Problem with calling a function within a newly created element
- JS Stops working in IE6
- How to detect if a dialog is present
- Google Maps API Javascript Problem
- How can 'this' be two different things
- Howto Get a Variable's Name (NOT VALUE) - Introspection????
- time to render table
- Javascript recursion limit
- JS 1.7 support: Who has it, etc.?
- Force update of on screen render after DOM element change
- My ajax class - not handling multiple requests
- offsetParent and XUL/SVG
- Coding
- DOM problem with Konqueror
- computer platform assignment
- "Goal Seek" from Excel in Javascript
- wait on button click
- Guidance Request (and a specific question)
- 'this', event handlers, and namespaces
- Script to do a simulated popup window with divs
- text selection
- odd javascript behaviour with Safari??
- Re: A Newbie's Must-Have Library
- Disable form input in IE7
- Contradiction of Advice?
- 15 Java Programming ebook.
- JavaScript Validation Works In Firefox But Not IE
- Add Element to Form
- Javascript Read Content Directory
- Please help on IE problem
- javascript:close() for tab in Firefox
- Album Javascript
- browser compatibility
- Reload parent while maintaining current scroll position.
- Inserting a line break
- DOM error: "node cannot be inserted". Why not?
- if Flash not installed?
- Javascript effect
- problem with floating animation
- trying to get an attribute value
- How to set default home page using javascript function(?
- JS Function to Insert Values Across Child Frames - Need Help
- Debugger
- Google Map
- Javascript Function Question
- How do I get the image to repeat the correct height?
- How to set the default home page using php code in Firefox
- Error: uncaught exception: [Exception... "Component returned failure
- Small Javascript Question
- A site for all your programming language needs
- a numbers puzzle?
- insert javascrpt into textarea?
- TransModal modal dialog project : v. 0.0.4 beta released
- Map button on form to key on keyboard
- replace question
- Trying to get a list of available JavaScript functions/methods
- Access 3rd-frames in Firefox or MSIE
- tree menu from current folder
- FAQ Topic - My element is named myselect[] , how do I access it? (2008-05-10)
- InnerHTML Question
- Fixed-position navigation buttons
- pasteHTML for Firefox?
- Is it possible to create dynamic var
- show/hide javascript
- Siple AJAX, of course
- Passing strings between functions XMLHTTP.open
- Re: innerHTML with AJAX problem
- Keeping a option,select drop down list open on refresh / postback
- Re: innerHTML with AJAX problem
- Limit <textarea> length without losing caret position
- How can I set an object's property read-only to public?
- Time picker in javascript just like in MS Windows
- Novice Seeks Help
- Digg-Like Images from Url fetcher.
- My Very Strange Webhost, SBI! -- Opinions, Please
- Is it poss. to use alt. stylesheet switching and still bebookmark-friendly?
- replacement expression
- Is it possible to get the text from browser location bar *before*navigation (e.g. not location.href)
- Current index of an array of form elements?
- 'this' and <A HREF="...">
- Real-time database monitor
- problem with html entity in string
- Javascript form control element validation
- Security violation foreign domain?
- getAttribute question
- window width
- help - can anyone tell me how to get this code snippet to work
- PHP form processing (with Javascript)
- file upload with JSON+AJAX?
- Dynamic content, I need idea
- Prevent copy of hidden elements
- Re: Help needed: document true width and height?
- javascript stopped working?
- Pop-up menu in Dreamweaver
- Could you tell me why ?
- Singleton
- Opera shows up bad code?
- why do both lines of code work?!
- Limit textarea alert message
- Why do this? <SCRIPT TYPE="text/javascript"
- Why do mouseup events sometimes fire if the mouse is not released?
- Ugh
- JavaScript A* Path Finding Prototype
- AJAX innerHTML problem
- TransModal modal dialog project : beta testing
- Dynamic form processing
- setTimeout() syntax
- Name of class instance
- customerisnotalwaysright.
- Re: Using innerhtml
- eBay-style drop down menu
- How to re-print values from combobox selection
- how to force page down to see AJAX return info?
- Javascript and the combobox printing issue
- Appending Events
- Unknown runtime error
- still hoping for a little help!
- naming array values?
- Really annoying flickering
- reading json object with jquery
- On thickbox content loading?
- Invoking scroll method for an IFRAME object in HTML javascript
- Prototype bug or feature?
- How to hide parts of a document, using Javascript
- Possible to detect Windows desktop style?
- Re: Rethinking My Use of Modal Windows....
- Tab with IE logo spinning and Item remaining at the bottom of pageHelp?
- FAQ Topic - How do I get a perl/asp/php variable into client-side js? (2008-05-03)
- iframe losing reference to top?
- setTimeout() ignored in loop
- Client side waiting & timeout
- maximum rows added to table
- How to get Natural image width and height?
- Waiting for an element to be ready in js
- aPossible to Make A "Dummy" Anchor Tag **without** Jumping Back Up???
- FAQ Topic - How do I force a reload from the server/prevent caching? (2008-05-02)
- Conditional Operator and style/correctness
- Optgroup causes blank line in Select; Firefox but not IE
- Show the selected item in a long list after a submit
- Resizing of the TextArea on border or scrollbar
- Exit page. Where do my users go?
- Strategies for Non-JavaScript-Enabled Visitors...
- show hide divs - show last state upon reload/post
- Frame pages force refresh
- Change id of element in DOM, IE7...
- line 1 error invalid character
- Which DOM property for determining vertical size?
- "window.document.style.opacity=0.4"??
- Display 'loading' message when scripts are executed and page is stillloading
- Re: Class not defined
- FAQ Topic - How do I modify the current page in a browser? (2008-04-30)
- help w/ appending nodes
- Re: Class not defined
- Replace Table Help
- Java Applet vs. AJAX for continuous data
- Re: Class not defined
- a better way of clicking images in sequence?
- What happened to my code
- Re: putting data into js vars
- simple code for selecting matching text in a listbox
- Help with dropdownlist validation using javascript
- Same Origin Policy -- clarifications?
- IE is driving me crazy
- Possible Cookie Usage?
- IE bug/issue with changing the frameset properties through DHTML
- Looking for jquery like example
- Missing event targets with mouseover/mouseout in Firefox 2.0
- problem with method reset()
- Using scriptaculous, how to trigger mouseover effect ONLY if mousedover for a period of time
- get parent ID in nested script
- regards method reset()
- background image
- Memory and markers (adding/removing)
- memorize form settings
- memorize all form's setting
- Re: Preload images
- How Does JavaScript Call Forth CSS??
- Binding Javascript Class Method with Element Event
- dropdown box change index to matching
- Re: Making Site Opaque -- This Strategy Feasible?
- Re: Making Site Opaque -- This Strategy Feasible?
- PageFade() with onLoad in <body> Good, with onClick in <a href> Bad??
- Executing multiple XMLHttp requests
- help with RegEx
- XHR, responseXML and this
- XHR and responseXML == null why ?
- importNode and root node name
- Does this code snippet look okay? | https://bytes.com/sitemap/f-286-p-12.html | CC-MAIN-2021-10 | refinedweb | 3,113 | 53.51 |
Last week I snatched an hour here and there to work on my Feedzilla app. I like Feedzilla because it has an api that is free for me to use, so it's easy to write the app. However, I'm not totally enamored with the content, it seems like it is often out of date, though I suppose I can apply a filter to limit the content to new stuff from this week, or whatever.
However, what really stopped me working on it was that my implementation was just depressingly ugly. I'd look at all the cool and beautiful things that other people were doing with their apps, and be totally unmotivated to work on TechNews. Last week, I decided to ask for some help in how to improve my app, and I was told about ListItems. For TechNews, it was like the sun coming out from behind the clouds.
Now, the thing abut Ubuntu.Components is that the project is fundamentally a design project. Yes, the components need, and have, an awesome development team that makes them "real", but the components are really about providing developers with the tools for making a well designed "Ubuntu App". This couldn't be more clear than when using ListItems.
For an example, to turn the categories list from this:
to this:
I just had to use Standard list items. First, I went ahead and imported the ListItem namespace:
import Ubuntu.Components.ListItems 0.1
Then this is what my delegate for each list item looks like. The "progression: true" declares that the item will navigate somewhere. The designers ensured that this means the list item adds that ">", so it is standard navigation in all apps!
delegate: Standard
{
progression: true;
text: articlesListView.model[index]["title"]
onClicked:
{
articleSelected(articlesListView.model[index]["url"])
}
}
So my app went from ugly duckling to beautiful swan just by using the right components and getting all the benefit of the designers' abilities that I so sorely lack. Thanks SDK team!
I guess you'll also have to don a designer's mindset too as you go on. Great work so far!
Balliro Trade Collection provides highest regarded pattern as well as improvement services,app developer.
Balliro Trade Collection provides highest regarded pattern as well as improvement services,best app developer. | http://theravingrick.blogspot.com/2013/05/ugly-duckling-to-beautiful-swan-or-how.html | CC-MAIN-2015-22 | refinedweb | 383 | 64.51 |
0
I have been working on this program for a few days and have most of it working, the only issue that I am having is when a word has multiple iterations pf the same letter. I need the program to print out all the letters that are the same when they are guessed. example if the word is apple and the user guesses p then I need both letter p's to be printed on the output line. Any help would be greatly appreciated, here is what I have.
import random #Program 4 Hangman #print the hangman partition def hangman(turn, correct): if correct > 0: turn = turn - correct if turn == 1: print('|') elif turn == 2: print('|') print('O') elif turn == 3: print(' |') print(' O') print('/') elif turn == 4: print(' |') print(' O') print('/|') elif turn == 5: print(' |') print(' O') print('/|\\') elif turn == 6: print(' |') print(' O') print('/|\\') print('/') elif turn == 7: print(' |') print(' O') print('/|\\') print('/ \\') #function to play the hangman game def game(word): word = word.upper() #capitalize the word print(word) hint = "-" * len(word) #setup the for the hidden word count = 0 # counter for the while loop for the 7 user inputs wrong = [] number = 0 badGuess = 1 correctguess = 0 i = 1 while (count == 0): print (hint) guess = input('Please enter guess # ' + str(i) + ':') guess = guess.upper() #capitalize the user inputs #loop to see if the guess is in the hidden word if guess in word: print('That letter is in the word') index = word.find(str(guess)) x = list(hint) x[index] = guess hint = "".join(x) correctguess += 1 hangman(i, correctguess) # if guess is not in the hidden word go to the function to draw hangman else: hangman(i, correctguess) wrong.append(guess) w = " ".join(wrong) print ('The incorrect letters you have guessed: ' + w) badGuess += 1 if hint == word: print('Congratulations you have guessed the word.') break elif badGuess > 7: print('Sorry you took too many guesses that the word was ' + word) break i += 1 #open the file and read it into a list file= open('words.txt') word = file.readlines() #select a word at random for the game and pass that word to the function game select = random.choice(word) selection = select.rstrip() game(selection) | https://www.daniweb.com/programming/software-development/threads/486545/help-with-hangman-program | CC-MAIN-2017-47 | refinedweb | 368 | 72.39 |
How to Calculate Yield to Maturity
Calculation HelpCalculating Yield to Maturity
Edited by DifuWu, Flickety, Zareen, Maluniu and 7 others
Yield to Maturity (YTM) for a bond is the total return, interest plus capital gain, obtained from a bond held to maturity. Yield to maturity is a useful measure of the attractiveness of a seasoned bond that is held to maturity and redeemed at par value. For example, suppose you buy a $1000 par value ABC Company bond with a 5% coupon rate maturing in five years, and the market price for the bond is $900. The coupon rate is the annual interest rate payable on the $1000 par value, which is $50 per year. The current yield of the bond is the interest divided by the current price of the bond, which is $50/$900, or 5.56%. On redemption of the bond after 5 years, you get $1000 for the matured bond, and realize $100 capital gain.
Yield to maturity takes into account both interest and capital gain return on the bond, and is calculated using the following steps.
Steps
Calculation Help
Calculating Yield to Maturity
- 1Subtract the purchase price ($900) from par ($1000). This results in a discount of $100.Ad
- 2Divide the discount ($100) by the remaining years to maturity (5) of the bond. You arrive at the annualized capital gain ($20).
- 3Add the annualized capital gain ($20) to the yearly interest ($50), to obtain total annualized return ($70).
- 4Divide the annualized return ($70) by the purchase price ($900), to obtain yield "A", or 7.78%.
- 5Subtract annualized capital gain ($20) from par ($1000), to obtain $980.
- 6Divide the annualized return ($70) by the result from the previous step ($980), to obtain yield "B", or 7.14%.
- 7Average yield "A" and "B", or (7.78%+7.14%)/2. This results in 7.46% yield to maturity.Ad
Video
Tips
- When bonds are not held to maturity, current yield is the more important measure of a bond's attractiveness. When bonds are held to maturity, yield to maturity is the more important measure.
- A bond selling at discount has a yield to maturity greater than its coupon rate (capital gain at redemption contributes to the higher yield to maturity relative to coupon rate). A bond selling at a premium has a yield to maturity smaller than its coupon rate (capital loss at redemption contributes to the lower yield to maturity relative to coupon rate). A bond selling at par has yield to maturity equal to its coupon rate (no capital gain or loss at redemption).
- P = c * (1 - (1 + Y)^(-n))/Y + (1 + Y)^(-n)
(* is multiplication. ^ is exponentiation.)
The method described in the first section gives a good approximation for yield to maturity. It is accurate but not precise. In the current era of near-zero interest and inflation rates, this method works quite well. When interest rates near or exceed eight or 10 per cent (as they did in the United States in the 1980s, and as perhaps they do today in 2011 in Greece), consider using more careful mathematics.
To calculate Y, yield to maturity per coupon period, more precisely, consider the formula
P = c * (1 - (1 + Y)^(-n))/Y + (1 + Y)^(-n)
Y is the value that makes this equation true when P is the Price of the bond in pennies per dollar of maturity value, c is the coupon amount in pennies per dollar of maturity value, and n is the number of coupons remaining to (and including) the last payment at maturity. Conventionally, bonds in the United States have a maturity value of $1,000, with a coupon paid every six months. For example, a bond with "a 4% coupon" would pay $20 every six months, plus a final payment with the last $20 coupon of $1,000 at maturity. Variations and idiosyncrasies commonly occur. Watch out for variations. The variations will change the yield to maturity.
To apply the formula, start with Y=0.04 (that is, 4 per cent or 4 pennies per dollar of maturity value), and calculate P. If the value of P that you calculate is lower than the market price, then reduce Y and recalculate. If the value of P that you calculate is higher than the market price, then increase Y a little, and recalculate. If you try this several times, you will soon get two successive values of Y, one of which gives P higher than the market price, and the other lower. Average the two values of Y to get a new Y. Recalculate with the new Y. Stop recalculating when you can't see any value in performing another calculation.
Warnings
- Avoid buying bonds selling at a premium or even close to par if it is callable (meaning that the company issuing the bond has a right to redeem the bond at par value before its maturity). If you buy a $1000 par value bond for $1075, you could realize an immediate loss of $75 if the company decides to call the bond the next day. Bonds selling at a significant discount, on the other hand, are rarely called before maturity, because the company loses money corresponding to the bond's discount when it redeems the bond at par.
Things You'll Need
- Bond par value, or face value
- Bond coupon rate
- Bond years until maturity
- Current bond price
- Number of coupon (interest) payments per year
- Date of next coupon payment
Article Info
Featured Article
Categories: Featured Articles | Financial Bonds
Recent edits by: Jeff, Snow Wolf, Allie
In other languages:
Português: Como Calcular o Rendimento à Maturidade, Español: Cómo calcular rendimiento al vencimiento de un bono
Thanks to all authors for creating a page that has been read 229,307 times. | http://www.wikihow.com/Calculate-Yield-to-Maturity | CC-MAIN-2014-10 | refinedweb | 960 | 59.33 |
I have written a lot of database apps. Most of them have been small, and I soon realized that
the CRecordset class was the only class requiring MFC for the majority of those apps. So, I
sat down and wrote these classes to provide most of the functionality I needed and so I could
get rid of MFC dependancies.
CRecordset
These classes are extremely basic, and provide little use for someone who does not use the
ODBC API directly. However, for those of you that do use the API, you might find them useful.
There are three classes in this collection, CODBCCnx, CODBCQuery and
CODBCFatQuery (you can find them all in the files ODBC.h and ODBC.cpp.) CODBCCnx is
the most complex (so far), it creates the connections to the DBMS and allows you to easily share those connections.
CODBCQuery and CODBCFatQuery really don't do much yet, but sometime in the near future
I plan on adding functionality to them. For now, they are basically coming along for the ride, because they are
in the same files
CODBCCnx
CODBCQuery
CODBCFatQuery
CODBCCnx provides three functions, Connect(), Disconnect() and
IsOk(). The Connect() function allows you to connect either through a DSN or by
using the computer's network name.
Connect()
Disconnect()
IsOk()
//connecting to a DBMS through a DSN, "foodsn"
CODBCCnx dsn();
dsn.Connect("foodsn","username","password");
//NOTE: CODBCCnx dsn("foodsn",username","password"); is the same as above
//checking to see if we are connected
if(!dsn.IsOk()){
//we are connected
}
else{
//we are NOT connected
}
//connecting using a computer name on the network
CODBCCnx name("SQL Server","CompName","username","password");
//again, checking to see if we are connected
if(!name.IsOk()){
//we are connected, and there was much rejoicing
}
else{
//not connected
}
Ok so now we are connected, lets disconnect from the database. The Disconnect() function forces you to
make a decision on how you want to disconnect. Because there might possibly be transactions still going on, you can
either roll them back, or wait for them to commit. If you do not provide a value for the parameter,
calling Disconnect rolls the transactions back by default.
Disconnect
//disconnecting from above connection (dsn)
dsn.Disconnect(); //this rolls all uncommitted transactions back
//NOTE: dsn.Disconnect(SQL_ROLLBACK) is the same thing
//disconnecting from above connection, name
name.Disconnect(SQL_COMMIT); //this forces all uncommitted transactions to finish.
Ok, so we have connected and disconnected, big deal. The nice thing about these classes is being able to share that
connection we just made. This is where CODBCQuery comes in. CODBCQuery is not really
useful by itself, but it is quite a handy class if you use it as a base class. The only thing note worthy about it,
is the constructor, and the public statement handle. Code speaks well....
//establish a connection using dsn
CODBCCnx *pDsn = new CODBCCnx("foodsn", "username", "password");
CODBCQuery qry1, qry2;
if(!pDsn->IsOk())
{
//connected!! now lets share some connections :)
pDsn->Connect(qry1.h_qstmt);
pDsn->Connect(qry2.h_qstmt);
}
else{
//not connected
}
//or we can do everything in one step
CODBCQuery qry(new CODBCCnx("foodsn", "username", "password"), true);
//or we can take the pDsn and pass it to a bunch of new query objects
CODBCQuery qry2(pDsn), qry3(pDsn,false);
//or we can have the CODBCQuery class connect itself
CODBCQuery qry4("SQL Server", "CompName", "username", "password");
//using a DSN
CODBCQuery qry5(NULL, "foodsn", "username", "password");
As you can see in the above code snippet, the constructors for CODBCQuery are pretty flexible. The most
important thing to note is the boolean flag. If you pass the value true, CODBCQuery will delete the
pointer. However, if you pass just the pointer or false as well, then CODBCQuery will NOT delete the
pointer.
One final note. There is a global function, SQLSuccess(). You pass it a SQLRETURN variable,
and it will return a non-zero value if the SQLRETURN value is either SQL_SUCCESS or SQL_SUCCESS_WITH_INFO
I just simply grew tired of typing those out
SQLSuccess()
SQLRETURN
SQL_SUCCESS
SQL_SUCCESS_WITH_INFO
The only thing left to do after all this connecting and sharing is to bind variables to result sets. Which I leave for you
to do
I didn't provide a demo, because I feel that these classes are too simple to warrant one. However, if you would like one
give me a holler and I will gladdly provide you with one.
If you look at the code, there are two files, strutil.h and strutil.cpp. They are very simple functions to handle char*. I
found all the work you have to go through allocating memory for strcpy, etc.. annoying. So I replaced them with the funcs in
those files. To prevent name collisions, I put them in the jkl_str namespace. I hope you find them useful.
char*
strcpy
5 Nov 2001 - updated download
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
Table::~Table()
{
if(h_stmt != INVALID_HANDLE_VALUE)
{
SQLFreeStmt(h_stmt,SQL_CLOSE);
SQLFreeHandle(SQL_HANDLE_STMT, h_stmt);
}
}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/script/Articles/View.aspx?aid=707 | CC-MAIN-2014-52 | refinedweb | 885 | 63.09 |
django-eggnog 0.0.1
Displays available egg updates from PyPi
View all available updates for your installed eggs right from within the administration console.
Eggnog is a simple wrapper on Yolk. Eggnog works best when it is scheduled to run at a periodic internal. It fetches the list of installed eggs and queries PyPI for any available updates.
If there's a feature that you're missing and you'd like added, please create an issue on the project page at Github or create the fix yourself and send me a pull request. Adding a few small features here and there are okay but this is in no way aimed to encompass all the functionality of a full-blown package management tool like Pip.
Installation
Grab the latest release from PyPI by running:
pip install django-eggnog
Please note that this requires Django 1.3+ to work properly.
Configuration
Add eggnog to your project's INSTALLED_APPS setting and run syncdb (or migrate if you're using South).
django-eggnog relies on the apscheduler module to provide the periodical checks for updates. In order to configure this, please add the following two lines to your urls.py:
import eggnog eggnog.periodicallycheckforupdates()
If you have a very small Django installation, I suggest you stick with this but if you wish to not use apscheduler, disregard the above step and uninstall apscheduler by running:
pip uninstall apscheduler
There isn't much else than that to get it up and running.
Scheduling
Eggnog works best when it is shcheduled to run at periodic intervals. Checking for updates once a day is quite enough.
Eggnog has a management-command built-in caleed checkupdates that it relies on to check for updates and here a few ways that that you can use to schedule it:
- Cron: You can configure cron to execute the management command once a day using this: * * * * * cd /home/path/to/project && python manage.py checkupdates
- Use a package like django-kronos or django-chrnonograph. Both the Django modules . once configured . make it extremely simple schedule management-commands using cron. They are both available on PyPI and you should consult their documentation on further instructions.
- Celery: If your Django project already deals with distributed task queues, it's extremely likely that you're using django-celery. In that case, configure django-celery to execute checkupdates periodically. Explaining the configuration of django-celery is outside the scope of this document.
- APScheduler: APScheduler is is an extremely lightweight module to running tasks periodically within Python. This is what django-eggnog ships with.
- Downloads (All Versions):
- 6 downloads in the last day
- 43 downloads in the last week
- 162 downloads in the last month
- Author: Mridang Agarwalla
- Maintainer: Mridang Agarwalla
- Bug Tracker:
- Download URL:
- License: BSD License
- Categories
- Package Index Owner: mridang
- DOAP record: django-eggnog-0.0.1.xml | https://pypi.python.org/pypi/django-eggnog/0.0.1 | CC-MAIN-2014-15 | refinedweb | 475 | 54.32 |
Synopsis
#include <libgnome/gnome-desktop-utils.h> void gnome_desktop_prepend_terminal_to_vector (
int *argc,
char ***argv);
Details
gnome_desktop_prepend_terminal_to_vector ()
void gnome_desktop_prepend_terminal_to_vector (
int *argc,
char ***argv);
Prepends a terminal (either the one configured as default in
the user's GNOME setup, or one of the common xterm emulators) to the passed
in vector, modifying it in the process. The vector should be allocated with
g_malloc, as this will g_free the original vector. Also all elements must
have been allocated separately. That is the standard glib/GNOME way of
doing vectors however. If the integer that
argc points to is negative, the
size will first be computed. Also note that passing in pointers to a vector
that is empty, will just create a new vector for you. | http://developer.gnome.org/gnome-desktop/stable/gnome-desktop-Miscellaneous-Functions.html | crawl-003 | refinedweb | 121 | 54.83 |
Meshes with Python & Blender: The 2D Grid
Procedural generation is awesome! In this tutorial series we’ll look at making meshes using Blender’s Python API.
Creating meshes programmatically opens many possibilities. You can create parametric objects that respond to real world settings, generative art, math based shapes or even procedural content for games. Blender is a great choice for this kind of work since it combines a full blown modeling and animation suite with a powerful (and fairly well documented) Python API.
In this series we will be looking at making several primitives and some basic transformations, I’ll also drop some tips along the way to make development easier. I’m assuming you already know some basic Python, and enough Blender to get around. For this introduction we’ll skip the 3D and focus on making a simple flat grid instead.
Pro Tip: Save often while working on meshes! You will make Blender crash more than once 🙂
Tutorial Series
- Part 1: The 2D Grid
- Part 2: Cubes and Matrices
- Part 3: Icospheres
- Part 4: A Rounded Cube
- Part 5: Circles and Cylinders
Setting it up
The Blender data system makes a distinction between mesh data and objects in the scene. We have to add a mesh and link it to an object, and then link that object to a scene before we can see any results.
Let’s start by importing bpy (surprise!) and setting up some variables.
import bpy # Settings name = 'Gridtastic' rows = 5 columns = 10
Name will be both the mesh and object’s name, while
rows and
columns will control how many vertices the grid has. Next we set up the mesh and object adding part. We have to add a mesh datablock first, then an object that uses that mesh and finally link them to the current scene. I’ve also added some empty lists for verts and faces. We will be filling those later.
verts = [] faces = [] #
The most interesting part is
from_pydata(). This function creates a mesh from three python lists: vertices, edges and faces. Note that If you pass a faces list you can skip edges. Check the API Docs for more info on this function
Try running the script now. You will see a new object has been added but there’s no geometry to be seen (since we haven’t added it yet). With the basic scaffolding done, delete that object and read on to start building the grid.
A grid of vertices
Let’s begin by adding a single vert. Vertices are represented by 3 coordinates (X, Y and Z). Our grid will be 2D so we only care about X and Y, Z will always be zero. We will place the vert in the center of the scene, which is also the origin for global coordinates. In other words, at coordinates (0, 0, 0). Each vertex is a tuple of 3 floats, so modify the list like this:
verts = [(0, 0, 0)]
Try running the script again and you will see a lonely dot. You can actually go into edit mode now and play with it. Lets ramp up and make a row of verts. To do this we need to loop and add as many vertices as the number of columns we set up. This is really easy to do with a list expression:
verts = [(x, 0, 0) for x in range(columns)]
range() returns integers, so the vertex X coordinate will be their column number. That means each column will be 1 Blender Unit (or meter) wide. Run the script again you will see 10 vertices lined up on the X axis. To complete a grid all we have to do is more rows. We can easily extend the expression to loop through rows as well:
verts = [(x, y, 0) for x in range(columns) for y in range(rows)]
Now we can see the vertex grid in all it’s glory.
We can start making faces now, but first we need to understand how.
Understanding faces
Each vert we added has an index number. Indices are set as we add each vert, so the first one is 0, the second is 1 and so on.
To make a face you need to add a tuple of indices to the faces list. This tuple can be 3 (tri), 4 (quad) or more (ngon) indices. These are all integers by the way. Blender won’t fail or complain, but it will round them. Since we are making quads we will need to find four vertex indices for each face. But how? You could try guessing them, but there’s a better way. We can enable debug mode in Blender. Open a Python Console in Blender and type the following:
bpy.app.debug = True
If you get anything from this tutorial I hope it is debug mode. It’s the most useful setting you can have for mesh making and even general addon development. To see the vertices indices, select the 2D vertex grid and go into edit mode. Open up the N-panel and toggle “Indices” in the Mesh Display Panel. It’s under the “Edge Info” column. If you can’t see it, you might not have enabled debug mode yet. Now any vertex you select will show it’s index, so select them all to see their indices.
Let’s focus on the first face. As you can see it’s made up of vertices 0, 1, 5 and 6. Let’s try making a single face with those indices:
faces = [(0, 1, 5, 6)]
Try running the script again and… wait, something looks wrong! It looks as if we connected the wrong vertices.
Well, we did connect the right vertices but in the wrong order. Yes, there is an order to follow when setting up faces: counter-clockwise starting from the lower-left.
Therefore the order for the face is 0, 5, 6, 1. Fix that line and run the script again.
Now we are in business. Anytime you see problems like this, try swapping the first or last two sets of indices between themselves. Alright, this is where things get funny. We need to figure out how to calculate all the indices to make a row of faces. If we look closely at the vertices indices we can see a pattern:
- All indexes jump by 5 in the X axis. This is equal to the number of rows.
- The first index starts at 0, while the second starts at 1
We can figure out the first index in a loop by multiplying the current column by
rows. Since the second one is offset by 1, we just have to add 1 to get it.
Try printing these values to check them out.
for x in range(columns - 1): print(x * rows) print((x + 1) * rows)
You might be wondering why we are looping over
columns - 1. We have 10 columns of vertices, but these only create 9 columns of faces. The last column doesn’t connect to anything after it.
The third and fourth indices are
(x + 1) * rows + 1 and
x * rows + 1 respectively. We add 1 to X before multiplying to set the index on the next row.
Here’s a loop to print all the indices:
for x in range(columns - 1):
print('first:', x * rows)
print('second:', (x + 1) * rows)
print('third:', (x + 1) * rows + 1)
print('fourth:', x * rows + 1)
print('---')
Fleshing out the mesh
Armed with all this knowledge we can now build the first row of faces. But before we get to that, let’s separate the face code into it’s own function so we can keep the code nice and clean. I have also added support for making a face on any row. Rows make indices increase by 1 as you they up the Y axis, so we can just add the row number at the end.
def face(column, row): """ Create a single face """ return (column* rows + row,
(column + 1) * rows + row,
(column + 1) * rows + 1 + row,
column * rows + 1 + row)
Let’s put this into an expression like we did with vertices:
faces = [face(x, y) for x in range(columns - 1) for y in range(rows - 1)]
We use rows – 1 for the same reason we did columns. Run the script and behold.
And with that the grid is now complete. You have made a script that can create 2D grids! Pat yourself in the back and keep reading for some finishing tweaks and challenges.
Scaling
We can control how many vertices our grid has, but the squares are always exactly 1 BU in size. Let’s change that.
All we have to do is multiply the X and Y coordinates by a scale factor. Start by adding a size variable. We can add this directly to the verts expression but again, it is cleaner if we do it in it’s own function.
size = 1 def vert(column, row): """ Create a single vert """ return (column * size, row * size, 0) verts = [vert(x, y) for x in range(columns) for y in range(rows)]
Try setting size to something other than 1 and check the grid.
Final code
import bpy # Settings name = 'Gridtastic' rows = 5 columns = 10 size = 1 # Utility functions def vert(column, row): """ Create a single vert """ return (column * size, row * size, 0) def face(column, row): """ Create a single face """ return (column* rows + row,
(column + 1) * rows + row,
(column + 1) * rows + 1 + row,
column * rows + 1 + row) # Looping to create the grid verts = [vert(x, y) for x in range(columns) for y in range(rows)] faces = [face(x, y) for x in range(columns - 1) for y in range(rows - 1)] #
Wrap up
Hope you’ve enjoyed this introduction to making meshes in Python. This is only the most basic example I could think of, and there’s plenty of other interesting things to do. Here’s some easy things you can try to do for yourself:
- Make it use 2 scaling factors: X and Y
- Add an offset so the Grid doesn’t start at (0, 0).
- Isolate all this nicely into it’s own function (or class)
Stay tuned for the next tutorial where we finally go 3D with cubes.
4 Comments
Hi there,
thanks for this series. However I found a little error:
verts = [(x, 0, 0) for x in range(columns)]
will create 10 vertices. Not 5 as stated in the text.
Nice catch, thanks!
Hate to say this,
but theres more…
For creating the first face you state we should use the verts in a counter clockwise fashion. So shows your diagram. But your order of (0, 1, 5, 6) is actually clockwise counting. CC would be (0, 6, 5, 1). The difference?
Actually its in the way the normal is facing. Yours is pointing away from us and an actual cc order would point towards the creator. Please don’t get me wrong here. I don’t want to offend you in any way. I had absolutely no idea of mesh construction with Python prior to reading this and I am here to learn about this stuff. But I think you can agree, that it’s important ( especially in my early stage ) that the gathered infos is correct. Anyway’s it’s kind of enhancing the learning experience when you actually spot such things ;P
I’d rather told you this in a PM but I’m new to this whole Diqus thingy and don’t even know if thats possible. So I hope it’s not to bothering here in public.
Hey, no problem. Everyone makes mistakes, and I make a _ton_ of them. I don’t know how I managed to get clockwise and CC mixed up, but I’ll get that fixed. And you’re right that the normals are pointing downwards. If you change the code to actually go counter clockwise, they point up as they should 🙂
That said I tried to avoid going into the normals thing for this series, unless they were giving trouble (like in the last part).
Disqus doesn’t have DMs AFAIK, but you can always send me an email at diego@sienstesia.co. This was only the 2nd or 3rd tutorial I made, so I do appreciate some constructive feedback! | http://sinestesia.co/blog/tutorials/python-2d-grid/ | CC-MAIN-2018-39 | refinedweb | 2,059 | 80.11 |
Is there a key shortcut to execute the "Close Other Tabs" command?
Here is the content of Packages/Default/Tab Context.sublime-menu
<item caption="Close Tab" command="closeUnder"/>
<item caption="Close Other Tabs" command="closeAllExceptUnder"/>
<item caption="Close Tabs to the Right" command="closeToRightOfUnder"/>
<item caption="Close All" command="closeAll"/>
<separator/>
<item caption="Save" command="saveUnder"/>
<separator/>
<item caption="New view into %s" command="cloneUnder"/>
<separator/>
<item caption="Buffer Name..." command="editBufferNameUnder"/>
So just add the following to your Packages/User/Default.sublime-keymap (feel free to change the key assignement )
<!--
Place your key bindings in here, this will ensure they don't get overwritten
when installing new versions of Sublime Text
-->
<bindings>
....
<binding key="ctrl+alt+w" command="closeAllExceptUnder"/>
</bindings>
The commands in the tab context menu rely on a bit of magic, and they won't work outside of the right click context menu (as they operate on the tab under the mouse cursor, not the one that has input focus).
There isn't a built in command that does what you want, but it is possible to make one via the python API.
OK, I'll dig into it. If anyone has already written an extension, please let me know!
This should do the trick:
[code]
class CloseAllOtherTabsCommand(sublimeplugin.WindowCommand): def run(self, window, args): active_group = window.activeGroup() curr_view_id = window.activeViewInGroup(active_group).id()
for v in window.viewsInGroup(active_group):
if v.id() == curr_view_id: continue
window.focusView(v)
window.runCommand("close")[/code]
Thanks for the code! But, how would I take this and bind it to a key? I placed the code in a Python file and put it in the Users/Packages directory. I also changed it to extend sublimeplugin.TextCommand instead of WindowCommand.
I added the following code in my bindings:
<binding key="ctrl+t" command="closeAllOtherTabs"/>
But still no dice...
Here is the entire package that I saved in User/Packages
import sublime, sublimeplugin
# tab_management.py
class CloseAllOtherTabsCommand(sublimeplugin.TextCommand):
def run(self, window, args):
active_group = window.activeGroup()
curr_view_id = window.activeViewInGroup(active_group).id()
for v in window.viewsInGroup(active_group):
if v.id() == curr_view_id: continue
window.focusView(v)
window.runCommand("close")
It doesn't make sense to extend TextCommand because you're not operating on text, does it?
Also, if you do so you will get a view object passed to .run instead of a window, so the first version won't work. You could modify the code to make it work as a TextCommand, but I see little reason to do so.
view
.run
window
Thanks for the response. I'm still a little unclear how to take the code you wrote and have it run when I hit a given key combination (let's say ctrl+t). I changed it back to your original code and placed it in Packages/User. I also added the key binding shown above, but it still doesn't close all other tabs when I press the key combination. Any ideas?
Hm... It works here on Sublime 1.4. What version are you using?
I'm also running 1.4. I must be making a noob mistake somewhere. I'll try again fresh in a bit and see if I can get it working.
Some ideas:
Have you many tab_management.py files? Leave just one.
Try this from the console:
import sublimeplugin
sublimeplugin.windowCommands"closeAllOtherTabs"].run(view.window(), ''])
If it works, your problem should be with the key binding. If you get a KeyError, it means Sublime can't find the plugin.
hey -stumbled upon this when trying to get close all tabs keyboard shortcut and it helped alot.-based on gullermooo's solution and with a few syntax adjustments here is a working plugin for build 3114.- added extra explanations that will hopefully help newbs like me entering this amazing sublime ecosystem1. generate a tab_managment.py inside user directory2. paste this code:import sublime, sublime_pluginclass close_tabs_pluginCommand(sublime_plugin.WindowCommand): def run(self): print("running close_tabs_pluginCommand") window=self.window active_group = window.active_group() curr_view_id = window.active_view_in_group(active_group).id() for v in window.views_in_group(active_group): if v.id() == curr_view_id: continue window.focus_view(v) window.run_command("close")3.make sure plugin is working when running from console:window.run_command('close_tabs_plugin')4. adding keyboard shortcut: add a file called Default.sublime-keymap to same user directory, add this json:[{ "keys": ["ctrl+shift+x"], "command": "close_tabs_plugin"}] thats it, hope this helps someoneariel | https://forum.sublimetext.com/t/shortcut-to-close-other-tabs/1056 | CC-MAIN-2016-36 | refinedweb | 728 | 52.97 |
In this tutorial, you will learn
What is Cluster analysis?
Cluster analysis is part of the unsupervised learning. A cluster is a group of data that share similar features. We can say, clustering analysis is more about discovery than a prediction. The machine searches for similarity in the data. For instance, you can use cluster analysis for the following application:
- Customer segmentation: Looks for similarity between groups of customers
- Stock Market clustering: Group stock based on performances
- Reduce dimensionality of a dataset by grouping observations with similar values
Clustering analysis is not too difficult to implement and is meaningful as well as actionable for business.
The most striking difference between supervised and unsupervised learning lies in the results. Unsupervised learning creates a new variable, the label, while supervised learning predicts an outcome. The machine helps the practitioner in the quest to label the data based on close relatedness. It is up to the analyst to make use of the groups and give a name to them.
Let's make an example to understand the concept of clustering. For simplicity, we work in two dimensions. You have data on the total spend of customers and their ages. To improve advertising, the marketing team wants to send more targeted emails to their customers.
In the following graph, you plot the total spend and the age of the customers.
library(ggplot2) df <- data.frame(age = c(18, 21, 22, 24, 26, 26, 27, 30, 31, 35, 39, 40, 41, 42, 44, 46, 47, 48, 49, 54), spend = c(10, 11, 22, 15, 12, 13, 14, 33, 39, 37, 44, 27, 29, 20, 28, 21, 30, 31, 23, 24) ) ggplot(df, aes(x = age, y = spend)) + geom_point()
A pattern is visible at this point
- At the bottom-left, you can see young people with a lower purchasing power
- Upper-middle reflects people with a job that they can afford spend more
- Finally, older people with a lower budget.
In the figure above, you cluster the observations by hand and define each of the three groups. This example is somewhat straightforward and highly visual. If new observations are appended to the data set, you can label them within the circles. You define the circle based on our judgment. Instead, you can use Machine Learning to group the data objectively.
In this tutorial, you will learn how to use the k-means algorithm.
K-means algorithm
K-mean is, without doubt, the most popular clustering method. Researchers released the algorithm decades ago, and lots of improvements have been done to k-means.
The algorithm tries to find groups by minimizing the distance between the observations, called local optimal solutions. The distances are measured based on the coordinates of the observations. For instance, in a two-dimensional space, the coordinates are simple and .
The algorithm works as follow:
- Step 1: Choose groups in the feature plan randomly
- Step 2: Minimize the distance between the cluster center and the different observations (centroid). It results in groups with observations
- Step 3: Shift the initial centroid to the mean of the coordinates within a group.
- Step 4: Minimize the distance according to the new centroids. New boundaries are created. Thus, observations will move from one group to another
- Repeat until no observation changes groups
K-means usually takes the Euclidean distance between the feature and feature :
Different measures are available such as the Manhattan distance or Minlowski distance. Note that, K-mean returns different groups each time you run the algorithm. Recall that the first initial guesses are random and compute the distances until the algorithm reaches a homogeneity within groups. That is, k-mean is very sensitive to the first choice, and unless the number of observations and groups are small, it is almost impossible to get the same clustering.
Select the number of clusters
Another difficulty found with k-mean is the choice of the number of clusters. You can set a high value of , i.e. a large number of groups, to improve stability but you might end up with overfit of data. Overfitting means the performance of the model decreases substantially for new coming data. The machine learnt the little details of the data set and struggle to generalize the overall pattern.
The number of clusters depends on the nature of the data set, the industry, business and so on. However, there is a rule of thumb to select the appropriate number of clusters:
with equals to the number of observation in the dataset.
Generally speaking, it is interesting to spend times to search for the best value of to fit with the business need.
We will use the Prices of Personal Computers dataset to perform our clustering analysis. This dataset contains 6259 observations and 10 features. The dataset observes the price from 1993 to 1995 of 486 personal computers in the US. The variables are price, speed, ram, screen, cd among other.
You will proceed as follow:
- Import data
- Train the model
- Evaluate the model
Import data
K means is not suitable for factor variables because it is based on the distance and discrete values do not return meaningful values. You can delete the three categorical variables in our dataset. Besides, there are no missing values in this dataset.
library(dplyr) PATH <-"" df <- read.csv(PATH) %>% select(-c(X, cd, multi, premium)) glimpse(df)Output
## Observations: 6, 259 ## Variables: 7 ## $ price < int > 1499, 1795, 1595, 1849, 3295, 3695, 1720, 1995, 2225, 2... ##$ speed < int > 25, 33, 25, 25, 33, 66, 25, 50, 50, 50, 33, 66, 50, 25, ... ##$ hd < int > 80, 85, 170, 170, 340, 340, 170, 85, 210, 210, 170, 210... ##$ ram < int > 4, 2, 4, 8, 16, 16, 4, 2, 8, 4, 8, 8, 4, 8, 8, 4, 2, 4, ... ##$ screen < int > 14, 14, 15, 14, 14, 14, 14, 14, 14, 15, 15, 14, 14, 14, ... ##$ ads < int > 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, ... ## $ trend <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
From the summary statistics, you can see the data has large values. A good practice with k mean and distance calculation is to rescale the data so that the mean is equal to one and the standard deviation is equal to zero.
summary(df)
Output:
## price speed hd ram ## Min. : 949 Min. : 25.00 Min. : 80.0 Min. : 2.000 ## 1st Qu.:1794 1st Qu.: 33.00 1st Qu.: 214.0 1st Qu.: 4.000 ` ## Median :2144 Median : 50.00 Median : 340.0 Median : 8.000 ## Mean :2220 Mean : 52.01 Mean : 416.6 Mean : 8.287 ## 3rd Qu.:2595 3rd Qu.: 66.00 3rd Qu.: 528.0 3rd Qu.: 8.000 ## Max. :5399 Max. :100.00 Max. :2100.0 Max. :32.000 ## screen ads trend ## Min. :14.00 Min. : 39.0 Min. : 1.00 ## 1st Qu.:14.00 1st Qu.:162.5 1st Qu.:10.00 ## Median :14.00 Median :246.0 Median :16.00 ## Mean :14.61 Mean :221.3 Mean :15.93 ## 3rd Qu.:15.00 3rd Qu.:275.0 3rd Qu.:21.50 ## Max. :17.00 Max. :339.0 Max. :35.00
You rescale the variables with the scale() function of the dplyr library. The transformation reduces the impact of outliers and allows to compare a sole observation against the mean. If a standardized value (or z-score) is high, you can be confident that this observation is indeed above the mean (a large z-score implies that this point is far away from the mean in term of standard deviation. A z-score of two indicates the value is 2 standard deviations away from the mean. Note, the z-score follows a Gaussian distribution and is symmetrical around the mean.
rescale_df <- df % > % mutate(price_scal = scale(price), hd_scal = scale(hd), ram_scal = scale(ram), screen_scal = scale(screen), ads_scal = scale(ads), trend_scal = scale(trend)) % > % select(-c(price, speed, hd, ram, screen, ads, trend))
R base has a function to run the k mean algorithm. The basic function of k mean is:
kmeans(df, k) arguments: -df: dataset used to run the algorithm -k: Number of clusters
Train the model
In figure three, you detailed how the algorithm works. You can see each step graphically with the great package build by Yi Hui (also creator of Knit for Rmarkdown). The package animation is not available in the conda library. You can use the other way to install the package with install.packages("animation"). You can check if the package is installed in our Anaconda folder.
install.packages("animation")
After you load the library, you add .ani after kmeans and R will plot all the steps. For illustration purpose, you only run the algorithm with the rescaled variables hd and ram with three clusters.
set.seed(2345) library(animation) kmeans.ani(rescale_df[2:3], 3)
Code Explanation
- kmeans.ani(rescale_df[2:3], 3): Select the columns 2 and 3 of rescale_df data set and run the algorithm with k sets to 3. Plot the animation.
You can interpret the animation as follow:
- Step 1: R randomly chooses three points
- Step 2: Compute the Euclidean distance and draw the clusters. You have one cluster in green at the bottom left, one large cluster colored in black at the right and a red one between them.
- Step 3: Compute the centroid, i.e. the mean of the clusters
- Repeat until no data changes cluster
The algorithm converged after seven iterations. You can run the k-mean algorithm in our dataset with five clusters and call it pc_cluster.
pc_cluster <-kmeans(rescale_df, 5)
- The list pc_cluster contains seven interesting elements:
- pc_cluster$cluster: Indicates the cluster of each observation
- pc_cluster$centers: The cluster centres
- pc_cluster$totss: The total sum of squares
- pc_cluster$withinss: Within sum of square. The number of components return is equal to `k`
- pc_cluster$tot.withinss: Sum of withinss
- pc_clusterbetweenss: Total sum of square minus Within sum of square
- pc_cluster$size: Number of observation within each cluster
You will use the sum of the within sum of square (i.e. tot.withinss) to compute the optimal number of clusters k. Finding k is indeed a substantial task.
Optimal k
One technique to choose the best k is called the elbow method. This method uses within-group homogeneity or within-group heterogeneity to evaluate the variability. In other words, you are interested in the percentage of the variance explained by each cluster. You can expect the variability to increase with the number of clusters, alternatively, heterogeneity decreases. Our challenge is to find the k that is beyond the diminishing returns. Adding a new cluster does not improve the variability in the data because very few information is left to explain.
In this tutorial, we find this point using the heterogeneity measure. The Total within clusters sum of squares is the tot.withinss in the list return by kmean().
You can construct the elbow graph and find the optimal k as follow:
- Step 1: Construct a function to compute the total within clusters sum of squares
- Step 2: Run the algorithm times
- Step 3: Create a data frame with the results of the algorithm
- Step 4: Plot the results
Step 1) Construct a function to compute the total within clusters sum of squares
You create the function that runs the k-mean algorithm and store the total within clusters sum of squares
kmean_withinss <- function(k) { cluster <- kmeans(rescale_df, k) return (cluster$tot.withinss) }
Code Explanation
- function(k): Set the number of arguments in the function
- kmeans(rescale_df, k): Run the algorithm k times
- return(cluster$tot.withinss): Store the total within clusters sum of squares
You can test the function with equals 2.
Output:
## Try with 2 cluster
kmean_withinss(2)
Output:
## [1] 27087.07
Step 2) Run the algorithm n times
You will use the sapply() function to run the algorithm over a range of k. This technique is faster than creating a loop and store the value.
# Set maximum cluster max_k <-20 # Run algorithm over a range of k wss <- sapply(2:max_k, kmean_withinss)
Code Explanation
- max_k <-20: Set a maximum number of to 20
- sapply(2:max_k, kmean_withinss): Run the function kmean_withinss() over a range 2:max_k, i.e. 2 to 20.
Step 3) Create a data frame with the results of the algorithm
Post creation and testing our function, you can run the k-mean algorithm over a range from 2 to 20, store the tot.withinss values.
# Create a data frame to plot the graph elbow <-data.frame(2:max_k, wss)
Code Explanation
- data.frame(2:max_k, wss): Create a data frame with the output of the algorithm store in wss
Step 4) Plot the results
You plot the graph to visualize where is the elbow point
# Plot the graph with gglop ggplot(elbow, aes(x = X2.max_k, y = wss)) + geom_point() + geom_line() + scale_x_continuous(breaks = seq(1, 20, by = 1))
From the graph, you can see the optimal k is seven, where the curve is starting to have a diminishing return.
Once you have our optimal k, you re-run the algorithm with k equals to 7 and evaluate the clusters.
Examining the cluster
pc_cluster_2 <-kmeans(rescale_df, 7)
As mention before, you can access the remaining interesting information in the list returned by kmean().
pc_cluster_2$cluster pc_cluster_2$centers pc_cluster_2$size
The evaluation part is subjective and relies on the use of the algorithm. Our goal here is to gather computer with similar features. A computer guy can do the job by hand and group computer based on his expertise. However, the process will take lots of time and will be error prone. K-mean algorithm can prepare the field for him/her by suggesting clusters.
As a prior evaluation, you can examine the size of the clusters.
pc_cluster_2$size
Output:
## [1] 608 1596 1231 580 1003 699 542
The first cluster is composed of 608 observations, while the smallest cluster, number 4, has only 580 computers. It might be good to have homogeneity between clusters, if not, a thinner data preparation might be required.
You get a deeper look at the data with the center component. The rows refer to the numeration of the cluster and the columns the variables used by the algorithm. The values are the average score by each cluster for the interested column. Standardization makes the interpretation easier. Positive values indicate the z-score for a given cluster is above the overall mean. For instance, cluster 2 has the highest price average among all the clusters.
center <-pc_cluster_2$centers center
Output:
## price_scal hd_scal ram_scal screen_scal ads_scal trend_scal ## 1 -0.6372457 -0.7097995 -0.691520682 -0.4401632 0.6780366 -0.3379751 ## 2 -0.1323863 0.6299541 0.004786730 2.6419582 -0.8894946 1.2673184 ## 3 0.8745816 0.2574164 0.513105797 -0.2003237 0.6734261 -0.3300536 ## 4 1.0912296 -0.2401936 0.006526723 2.6419582 0.4704301 -0.4132057 ## 5 -0.8155183 0.2814882 -0.307621003 -0.3205176 -0.9052979 1.2177279 ## 6 0.8830191 2.1019454 2.168706085 0.4492922 -0.9035248 1.2069855 ## 7 0.2215678 -0.7132577 -0.318050275 -0.3878782 -1.3206229 -1.5490909
You can create a heat map with ggplot to help us highlight the difference between categories.
The default colors of ggplot need to be changed with the RColorBrewer library. You can use the conda library and the code to launch in the terminal:
conda install -c r r-rcolorbrewer
To create a heat map, you proceed in three steps:
- Build a data frame with the values of the center and create a variable with the number of the cluster
- Reshape the data with the gather() function of the tidyr library. You want to transform data from wide to long.
- Create the palette of colors with colorRampPalette() function
Step 1) Build a data frame
Let's create the reshape dataset
library(tidyr) # create dataset with the cluster number cluster <- c(1: 7) center_df <- data.frame(cluster, center) # Reshape the data center_reshape <- gather(center_df, features, values, price_scal: trend_scal) head(center_reshape)
Output:
## cluster features values ## 1 1 price_scal -0.6372457 ## 2 2 price_scal -0.1323863 ## 3 3 price_scal 0.8745816 ## 4 4 price_scal 1.0912296 ## 5 5 price_scal -0.8155183 ## 6 6 price_scal 0.8830191
Step 2) Reshape the data
The code below create the palette of colors you will use to plot the heat map.
library(RColorBrewer) # Create the palette hm.palette <-colorRampPalette(rev(brewer.pal(10, 'RdYlGn')),space='Lab')
Step 3) Visualize
You can plot the graph and see what the clusters look like.
# Plot the heat map ggplot(data = center_reshape, aes(x = features, y = cluster, fill = values)) + scale_y_continuous(breaks = seq(1, 7, by = 1)) + geom_tile() + coord_equal() + scale_fill_gradientn(colours = hm.palette(90)) + theme_classic()
Summary
We can summarize the k-mean algorithm in the table below | http://www.test3.guru99.com/r-k-means-clustering.html | CC-MAIN-2020-10 | refinedweb | 2,795 | 65.32 |
Red Hat Bugzilla – Bug 505863
Deprecation warnings on F11
Last modified: 2009-06-27 10:29:03 EDT
Description of problem:
Getting this when starting offlineimap on F11; they are two separate warnings. Should I open two bugs?
/usr/lib/python2.6/site-packages/offlineimap/folder/Maildir.py:23: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import os.path, os, re, time, socket, md5
OfflineIMAP 6.0.3
This software comes with ABSOLUTELY NO WARRANTY; see the file
COPYING for details. This is free software, and you are welcome
to distribute it under the conditions laid out in COPYING.
***** Processing account XXX
Copying folder structure from IMAP to Maildir
Establishing connection to XXX
/usr/lib/python2.6/site-packages/offlineimap/imaplibutil.py:172: DeprecationWarning: socket.ssl() is deprecated. Use ssl.wrap_socket() instead.
self.sslobj = socket.ssl(self.sock._sock, self.keyfile, self.certfile)
Thanks for the report.
md5 is already fixed upstream. I have sent a patch for socket.ssl too, I hope John integrates it for the 6.0.4 release. I will build a new package then.
I'll close that bug for now. | https://bugzilla.redhat.com/show_bug.cgi?id=505863 | CC-MAIN-2017-39 | refinedweb | 188 | 52.97 |
/* * HeapRange.h" #include "B3Value.h" namespace JSC { namespace B3 { class JS_EXPORT_PRIVATE FenceValue : public Value { public: static bool accepts(Kind kind) { return kind == Fence; } ~FenceValue(); // The read/write heaps are reflected in the effects() of this value. The compiler may change // the lowering of a Fence based on the heaps. For example, if a fence does not write anything // then it is understood to be a store-store fence. On x86, this may lead us to not emit any // code, while on ARM we may emit a cheaper fence (dmb ishst instead of dmb ish). We will do // the same optimization for load-load fences, which are expressed as a Fence that writes but // does not read. // // This abstraction allows us to cover all of the fences on x86 and all of the standalone fences // on ARM. X86 really just has one fence: mfence. This fence should be used to protect stores // from being sunk below loads. WTF calls it the storeLoadFence. A classic example is the Steele // barrier: // // o.f = v => o.f = v // if (color(o) == black) // log(o) // // We are trying to ensure that if the store to o.f occurs after the collector has started // visiting o, then we will log o. Under sequential consistency, this would work. The collector // would set color(o) to black just before it started visiting. But x86's illusion of sequential // consistency is broken in exactly just this store->load ordering case. The store to o.f may // get buffered, and it may occur some time after we have loaded and checked color(o). As well, // the collector's store to set color(o) to black may get buffered and it may occur some time // after the collector has finished visiting o. Therefore, we need mfences. In B3 we model this // as a Fence that reads and writes some heaps. Setting writes to the empty set will cause B3 to // not emit any barrier on x86. // // On ARM there are many more fences. The Fence instruction is meant to model just two of them: // dmb ish and dmb ishst. You can emit a dmb ishst by using a Fence with an empty write heap. // Otherwise, you will get a dmb ish. // FIXME: Add fenced memory accesses. // FIXME: Add a Depend operation. HeapRange read { HeapRange::top() }; HeapRange write { HeapRange::top() }; protected: Value* cloneImpl() const override; private: friend class Procedure; FenceValue(Origin origin, HeapRange read, HeapRange write); FenceValue(Origin origin); }; } } // namespace JSC::B3 #endif // ENABLE(B3_JIT) | https://opensource.apple.com/source/JavaScriptCore/JavaScriptCore-7607.2.6.1.1/b3/B3FenceValue.h.auto.html | CC-MAIN-2021-49 | refinedweb | 413 | 75.2 |
In Python, everything is an object.
And that includes classes, them are objects too.
In most languages like PHP, classes are just pieces of code that describe how to produce an object instance. But in Python, classes are objects too, seriously, when you use the keyword class, Python executes it and creates an object.
For example:
class Foo: pass
This will create an in memory object named “Foo”
This allows you to do several things that you wouldn’t do in other languages like PHP, for example:
- Assign the class in to a variable
- Add, remove or modify methods and attributes from the class
- Copy it and create new classes in run-time
- Pass the class object as a function parameter
- Decorate the class with functions
- etc
Since classes are objects too, there are metaclasses, which are the classes which creates classes.
And you can define which metaclass will create whichever of your classes.
In Python 2:
from abc import ABCMeta, abstractmethod class Foo(): __metaclass__ = ABCMeta @abstractmethod def bar(self, something): pass
In this example, the class ABCMeta will be the class which will create the class Foo.
I chose a real and useful example, which allows you to design abstract classes and methods in Python.
When you try to instantiate an object of Foo without implementing the abstractmethod, you will receive the following error message:
TypeError: Can’t instantiate abstract class Foo with abstract methods bar
In Python 3 it is different:
from abc import ABCMeta, abstractmethod class Foo(metaclass=ABCMeta): @abstractmethod def bar(self, something): pass
but the metaclass=ABCMeta is not backward compatible with Python 2, that means that you cannot do:
from abc import ABCMeta, abstractmethod class Foo(metaclass=ABCMeta): __metaclass__ = ABCMeta @abstractmethod def bar(self, something): pass
to support both Python 2/3 versions, you can use the following decorator:
def metaclass(mcls): def decorator(cls): body = vars(cls).copy() body.pop('__dict__', None) body.pop('__weakref__', None) return mcls(cls.__name__, cls.__bases__, body) return decorator
Usage example:
... @metaclass(ABCMeta) class Foo: @abstractmethod def bar(self, something): pass ... | http://www.felixcarmona.com/ | CC-MAIN-2015-40 | refinedweb | 344 | 55.07 |
by Kevin Scott
How to set up Tensorflow.js for machine learning in your browser
Until recently, just getting started writing your first line of machine learning code required a hefty upfront investment in time and money.
Last year, I built my own PC specifically for machine learning. I researched the parts and assembled it myself. Just doing that cost me around $1600 and 30 hours of setup time. I’m still trying to wrangle the computer’s configuration and libraries and make it work with various frameworks.
The good news is that getting started with machine learning today has never been easier. In fact, if you’re reading this, it means you already have the tools you need to dive right in. You can now learn the machine learning framework Tensorflow right in your browser, using JavaScript.
Tensorflow.js
Google released Tensorflow.js at the Google I/O 2018. There are some huge use cases for running machine learning algorithms in the browser.
In addition, it’s a great opportunity to use JavaScript to explore machine learning concepts without having to install a thing.
If you’re new to JavaScript, or if it’s been a while since you’ve written any front-end code, some of the recent changes in the JavaScript ecosystem might throw you for a loop. I’ll list the basics of modern Javascript you need to get the Tensorflow.js examples running, and start exploring machine learning.
Setup tutorial
Let me repeat something: all you need to run Tensorflow.js is your web browser.
It’s easy to lose sight amongst all the talk of transpilers, bundlers, and packagers, but all you need is a web browser to run Tensorflow.js. The code you develop locally is the same code you’ll be able to ship to your users to run on their browsers.
Let’s see three quick ways to get the Hello World example working without installing anything. I’ll be using the Getting Started code from the Tensorflow.js documentation.
Getting started with your browser console
Every modern web browser ships with some sort of interactive JavaScript Console built in. I use Chrome, which includes a JavaScript Console you can open with “View > Developer > JavaScript Console”.
This JavaScript Console lets you write JavaScript and execute it immediately. We’ll use this to run the Getting Started example from the Tensorflow.js docs.
First, you’ll need to include the Tensorflow.js JavaScript file. A hosted version of the file is available via the Content Delivery Network (CDN) below. A quick way to include an external
.js file via the console is:
var script = document.createElement('script');script.src = "[email protected]";document.getElementsByTagName('head')[0].appendChild(script);
Copy and paste this into your JavaScript Console, and you’ll have a copy of Tensorflow saved as the variable
tf. (If you type
tf in your console, you'll see a reference to it).
You can then copy and paste the rest of the Getting Started example (the JavaScript between the second
<script> tag) by pasting it directly into your console.
Getting started with a JavaScript hosting platform
An alternative approach is to use an online JavaScript hosting platform. Three popular ones are CodePen, JSFiddle, and JSBin. These platforms can automatically include scripts for you and take care of transpiling your code in the browser, which makes getting started a cinch.
You can view the following example on Codepen to see an implementation working. Make sure to open your browser console, as explained above, to see the output.
Getting started locally
A third option for getting Tensorflow.js working involves saving the code as a
.html file and opening it locally on your computer. And you don't need a web server to do this!
Copy the HTML code into a file, and open it in your web browser. For instance, if you save the file onto your desktop and you’re on a Mac, you might open it in your browser with the following URL:
It is important to note that viewing HTML files this way introduces limitations, including issues with referencing relative links, handling ajax calls, and security, among other things. But it's a quick and easy way to get something running in your browser.
The modern JavaScript development workflow
Hopefully by this point, you can see how easy it is to get something basic to show up in your browser. If you begin looking at the Tensorflow.js examples, you might be thinking:
- how do I organize my files?
- how do I manage third party libraries in my code?
- what’s with these syntax errors?
As soon as you move beyond the basic “Hello World” example above and into some of the other examples, you’ll begin to run into syntax issues and organization issues. That’s where a strong JavaScript pipeline will be your best friend.
A little bit of JavaScript history
As our expectations for web apps have grown over the past decade, the front-end ecosystem has exploded in complexity.
JavaScript in particular has matured a lot as a programming language, adopting a number of forward-thinking changes while continuing to support one of the largest userbases of any programming language.
New changes to the language spec are referenced with acronyms like ES5, ES6, ES2015, and E2016.
‘ES’ stands for ECMAScript, and JavaScript is based on this standard. The numbers 5 and 6 were traditionally used to refer to versions of the standard, but nowadays years are used for additional clarity.
Modern browser support for ES6 is patchy. Some cutting edge or proposed features are not yet supported, and older browsers (in particular Internet Explorer) will never support the latest spec.
Because of this instability, if you want to reach the widest audience possible, you use something called a bundler or transpiler. This is software that converts your JavaScript code written with modern conveniences into a version with wide-spread adoption. ES5 is widely supported, and is generally a good target.
Many of the Tensorflow.js examples make use of new syntax that is not yet widely supported in browsers, and requires transpiling. I’ll explain the syntax first and then explain how to get them working.
import and
export
import and
export are two bits of syntax recently introduced into JavaScript for importing modules. The saga of JavaScript modules is long and winding, but the community has largely settled on
import over
require.
Unfortunately, as of May 2018,
import is not supported by any browsers, so to use it you need to use a transpiler.
In the Getting Started docs, you’ll see an example of
import upfront:
import * as tf from '@tensorflow/tfjs';
This is basically the same as:
var tf = require('@tensorflow/tfjs');
You also might see something like:
import { util, tensor2d } from '@tensorflow/tfjs';
The equivalent using
require is:
var tf = require("@tensorflow/tfjs");var util = tf.util;var tensor2d = tf.tensor2d
async and
await
Javascript has traditionally been used heavily with UIs, which perform a lot of asynchronous actions. There have been three broad patterns for handling asynchronous code over the years: callbacks, promises, and async/await.
async/
await provides a way of defining asynchronous functions in a synchronous way. Many of the Tensorflow.js examples make use of this
async /
await syntax.
Here’s two versions of the same code, the first written with
async/
await, the second using promises:
// With async/awaitasync function loadMobilenet() { const mobilenet = await tf.loadModel( ''); // Return a model that outputs an internal activation. const layer = mobilenet.getLayer('conv_pw_13_relu'); return tf.model({inputs: model.inputs, outputs: layer.output});});// With promisesfunction loadMobilenet() { return tf.loadModel('').then(function (mobilenet) { // Return a model that outputs an internal activation. const layer = mobilenet.getLayer('conv_pw_13_relu'); return tf.model({inputs: model.inputs, outputs: layer.output}); });});
Both of these language features —
import/
export and
async/
await — make writing JavaScript more pleasant. Let's see the tools we need to use them in our own code.
JavaScript Tooling
In the Getting Started docs, you’ll see this note:
Note: because we use ES2017 syntax (such as
import), this workflow assumes you are using a bundler/transpiler to convert your code to something the browser understands. See our examples to see how we use Parcel to build our code. However you are free to use any build tool that you prefer.
Let’s talk about build tools.
Bundlers
Bundlers have taken on the role of conductor of the orchestra of growing front-end codebases. A bundler is a program that takes your JavaScript code and “bundles” it up into a compatible file for the browser.
Bundlers will also transpile code (convert ES2018 code to ES5, along with other dialects like React or Typescript, using something like babel), set up "hot reloading" to refresh the browser with code changes without reloading the page, and many other things to make front-end development better.
Grunt and Gulp used to be popular bundlers, but have recently fallen out of favor to
webpack. Other bundlers include
parcel and
rollup. The Tensorflow.js examples use
parcel.
Package managers
Often, when encountering a JavaScript library, you’ll see installation instructions like
yarn add @tensorflow/tfjs or
npm install @tensorflow/tfjs.
yarn and
npm are both package managers. They're command line tools used to install and keep track of your third party JavaScript dependencies.
yarn and
npm are pretty similar, and the decision of which one to use is largely up to personal preference (though you'll find plenty of hot debates online if you're into that sort of thing).
Either one will save your dependencies into a
package.json file which should be checked into your git repository. This file will enable other developers to quickly install all the necessary dependencies for your project and get things running quickly.
To get all these goodies, the first step is to install
npm or
yarn, along with
Node.js. Once those are in place, you can follow the instructions on any of the Tensorflow.js examples and they should work out of the box. Usually, getting set up with a new front-end project using these tools is a one step process.
Wrapping up
Again, you don’t need any of these tools to work with these examples, but using them makes things so much easier. If you intend to do any sort of serious JavaScript development, I would encourage you to play with these tools, along with other popular JavaScript tools like React and Typescript, which make handling larger codebases much better.
Originally published at thekevinscott.com
Special thanks to Ari Zilnik. | https://www.freecodecamp.org/news/how-to-set-up-tensorflow-js-for-machine-learning-in-your-browser-2540b5c43411/ | CC-MAIN-2019-35 | refinedweb | 1,771 | 65.01 |
In article <address@hidden>, Thien-Thi Nguyen <address@hidden> writes: > I'd like to avoid introducing "#ifdef VMS" newly in a > function that doesn't have it currently. > fully agreed. generally this might be re-conceptualized as "#if > CODING_STOPS_AT_LAST_EOL", where vms just happens to be one beneficiary > (maybe there will be others). the word "stops" is not 100% accurate, > unfortunately. Please note that this problem is not related to the task of encoding_coding. It's wrong to bring in the unrelated task in encoding_coding. And, encoding-coding is used also for encode-coding-region and encode-coding-string that don't have to pay attention to this problem. In addition, the chunking is introduced not only by encode_coding but by annotate functions which may produce a very short chunk that doesn't contain a newline. So, I think we should handle it in the place of "file writing". > struct coding_system > { ... > #ifdef CODING_CARRIES_AFTER_LAST_EOL > /* Last EOL. */ > char *last_eol; > /* Number of bytes to carry over after the last EOL encountered. */ > int carry_over_bytes; > #endif > }; > then macros EMIT_ONE_BYTE and EMIT_TWO_BYTES would set last_eol, > and encode_coding would need: > #ifdef CODING_CARRIES_AFTER_LAST_EOL > coding-> carry_over_bytes = coding->produced - coding->last_eol; > #endif encode_coding is designed so that it can be called with different input buffer. So, if we handle this problem in encode_coding, we have to remember carry over bytes themselves (not only the length) in the struct coding_system by allocating a memory for them, copy them, and re-copy them to the output buffer on the next encoding. It's so inefficient. Even if we do that, it can't solve the problem of thr short chunk produced by an annotate function. So, I strongly suggest to forget about changing encode_coding in such a way. Here's a suggestion to solve this problem. (1) Detect this problem in configure, and define, say, WRITE_ADD_NEWLINE on a problematic system. (2) Write a different version of emacs_write in sysdep.c for such a system. It keeps carry over bytes in a static buffer, and flushes out the bytes when called with NBYTES == 0. (3) Modify e_write to to call emacs_write with NBYTES == 0 at the end. --- Ken'ichi HANDA address@hidden | https://lists.gnu.org/archive/html/emacs-devel/2003-05/msg00345.html | CC-MAIN-2019-39 | refinedweb | 358 | 56.05 |
NAME
nice - change process priority
SYNOPSIS
#include <unistd.h> int nice(int inc); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): nice(): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE
DESCRIPTION
nice() adds inc to the nice value for the calling process. (A higher nice value means a low priority.) Only the superuser may specify a negative increment, or priority increase. The range for nice values is described in getpriority(2).
RETURN VALUE
On success, the new nice value is returned (but see NOTES below). On error, -1 is returned, and errno
SVr4, 4.3BSD, POSIX.1-2001. However, the Linux and (g)libc (earlier than glibc 2.2.4) return value is non-standard, see below. SVr4 documents an additional EINVAL error code.
NOTES
SUSv2 and POSIX.1-2001 specify that nice() should return the new nice value. However, the Linux syscall and the nice() library function provided in older versions of (g)libc (earlier than glibc 2.2.4) return 0 on success. The new nice value can be found using getpriority(2)..
SEE ALSO
nice(1), fork(2), getpriority(2), setpriority(2), capabilities(7), renice(8)
COLOPHON
This page is part of release 3.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.ubuntu.com/manpages/lucid/en/man2/nice.2.html | CC-MAIN-2014-42 | refinedweb | 214 | 60.82 |
#include <GU_Group.h>
Definition at line 122 of file GU_Group.h.
Reimplemented in GU_EdgeGroup, GU_PrimGroup, and GU_PointGroup.
Select just those items that are degenerate, or are zero area faces. Set degenerate flag to select degenerates. Set the zaf flag to select zero area faces. Set the doOpen flag to treat open faces as closed. Set tol for a tolerance used in detecting degeneracies.
Implemented in GU_PrimGroup, GU_EdgeGroup, and GU_PointGroup.
Definition at line 206 of file GU_Group.h.
Definition at line 207 of file GU_Group.h.
Definition at line 133 of file GU_Group.h.
Definition at line 210 of file GU_Group.h. | https://www.sidefx.com/docs/hdk/class_g_u___group.html | CC-MAIN-2021-21 | refinedweb | 101 | 63.46 |
awt list item* - Swing AWT
information.
Thanks...awt list item* how do i make an item inside my listitem...);
choice.add("Java ");
choice.add("Jsp");
choice.add("Servlets
Item Events in Java
events in java. This
demonstrates that the event generated when you select an item...
Item Events in Java
...; items from the item group.
Here, you will see the handling item event through
Java AWT event hierarchy
Java AWT event hierarchy What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy
Java AWT Package Example
Java AWT Package Example
... types of event are used in Java AWT.
Events
In this section, you... item events in java. This
demonstrates that the event generated when you
Event handling in Java AWT
Event handling in Java AWT
... events in java awt. Here, this
is done through the java.awt.*; package
of java... related to the event
handling through this example and used methods through which you
navigation between panels when item is selected from jcombobox - Swing AWT
on JComboBox in Java visit to : between panels when item is selected from jcombobox hi...(2nd panel).the combo box is in main panel. when a item is selected from combobox
Java AWT
Java AWT What interface is extended by AWT event listeners
awt - Swing AWT
,
For solving the problem visit to :
Thanks... market chart this code made using "AWT" . in this chart one textbox when user
Need an Example of calendar event in java
Need an Example of calendar event in java can somebody give me an example of calendar event of java
java awt package tutorial
Java AWT Package
In Java, Abstract Window Toolkit(AWT) is a platform... is used by each AWT component to display itself on the
screen. For example... interaction when an AWT
GUI is displayed. When any event is received by this new
Event Handling In Java
Event Handling In Java
In this section you will learn about how to handle... that happens and your
application behaves according to that event. For example....
In Java event handling may comprised the following four classes :
Event Sources
awt
Java AWT Applet example how to display data using JDBC in awt/applet
java-swings - Swing AWT
://
Thanks.
Amardeep...java-swings How to move JLabel using Mouse?
Here the problem is i... frame = new JFrame("mouse motion event program
Chart Item Event in Flex4
Chart Item Event in Flex4:
Chart uses the ChartItemEvent when you perform the
operation click on the chart Item. This event is the part of chart package...=
"Data Not Found";
}
// Chart Item
Event
public
awt in java
awt in java using awt in java gui programming how to false the maximization property of a frame Dispatcher Thread
;
In the tutorial Java Event Dispatcher thread in Graphics, we'll illustrate
you how to handle events in graphics using Java.
This example... if the current is an AWT event dispatching thread. The method fireTableCellUpdated
(row
Java AWT
Java AWT What is meant by controls and what are different types of controls in AWT
java - question - Swing AWT
Java question I want to create two JTable in a frame. The data.... This query is fixed. This query is "select * from item". Item table has following columns-Item_code,Item_name,Item_Price. When I click on one of the row in first
Event Dispatcher Thread
;
In the tutorial Java Event Dispatcher thread in Graphics, we'll illustrate
you how to handle events in graphics using Java.
This example... is an AWT event dispatching thread. The method fireTableCellUpdated
(row
Java - Swing AWT
Java Hi friend,read for more information,
AWT Tutorials
AWT Tutorials How can i create multiple labels using AWT????
Java Applet Example multiple labels
1)AppletExample.java:
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import how to use JTray in java
give the answer with demonstration or example
please
Java AWT Package Example
java swings - Swing AWT
. swings I am doing a project for my company. I need a to show... write the code for bar charts using java swings. Hi friend,
I am
swings - Swing AWT
:// What is Java Swing Technologies? Hi friend,import... TwoMenuItem{ public static void main(String[] args){ TwoMenuItem item = new TwoMenuItem
query - Swing AWT
java swing awt thread query Hi, I am just looking for a simple example of Java Swing
Java event handling
Java event handling What event results from the clicking of a button AWT
java what will be the code for handling button event in swing? Hi Friend,
Try the following code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ButtonEvent extends JFrame - Swing AWT
:
Thanks...java swing how to add image in JPanel in Swing? Hi Friend,
Try the following code:
import java.awt.*;
import java.awt.image.
Different types of event in Java AWT
Different types of event in Java AWT
... in Java AWT. These are as
follows :
ActionEvent
AdjustmentEvent... that are generated by your AWT Application. These events are used to make the application more
Java event delegation model
Java event delegation model What is the highest-level event class of the event-delegation model
Java event-listener
Java event-listener What is the relationship between an event-listener interface and an event-adapter class
java - Swing AWT
java how can i add items to combobox at runtime from jdbc Hi Friend,
Please visit the following link:
Thanks Hi Friend
Java Swing Key Event
Java Swing Key Event
In this tutorial, you will learn how to perform key event in java swing. Here
is an example that change the case of characters... KeyAdapter to perform the
keyReleased function over textfield.
Example:
import
Java - Swing AWT
....("Paint example frame") ;
getContentPane().add(new JPaintPanel
JList - Swing AWT
is the method for that? You kindly explain with an example. Expecting solution as early... == listModel.getSize()) {
//removed item in last position...();
ename.setText("");
//Select the new item and make BASE PROJECT
JAVA AWT BASE PROJECT suggest meaningful java AWT-base project
java awt calender
java awt calender java awt code for calender to include beside a textfield
Linking JMenu Item with a JPane in Netbeans
Linking JMenu Item with a JPane in Netbeans How do you link a Jpane window to a JMenu Item in Java Netbeans
java - Swing AWT
What is Java Swing AWT What is Java Swing AWT
Java AWT
Java AWT What is the relationship between the Canvas class and the Graphics class
Event management
Event management Hi,
I want event management application like maintaining email notifications while task creation and update in broader way using spring java
Create a Container in Java awt
Create a Container in Java awt
Introduction
This program illustrates you how to create...; }
}
Download this example
Java Ivent Handler - Swing AWT
Java Ivent Handler Is it possible to make two listeners work simultaneously?I used a keyboard listener to detect key press and also a mouse listener... if any key is pressed or released it cannot detect the keyboard event
Java AWT
Java AWT How can the Checkbox class be used to create a radio button
Java - Event Listeners Example in Java Applet
Java - Event Listeners Example in Java Applet
Introduction
The event...
on the several objects.
In this example you will see that how to use the event
SWINGS - Swing AWT
more information,Examples and Tutorials on Swing,AWT visit to :
How to save data - Swing AWT
to :
Thanks... the Dimensions of an Item in a JList Component");
JPanel panel = new JPanel...());
if (-1 < index) {
String item = (String)getModel
displaying image in awt - Java Beginners
to display image using awt from here and when I execute the code I am getting... ActionListener{
JFrame fr = new JFrame ("Image loading program Using awt");
Label... void actionPerformed(ActionEvent event){
Button b = (Button)event.getSource
Handling Key Press Event in Java
Handling Key Press Event in Java
... the handling key press event in java. Key
Press is the event is generated when you press any key to the specific
component. This event is performed by the KeyListener
Problem to display checkbox item
;/div>
2) gettable.jsp:
<%@page language="java" import
Click event
Click event hi............
how to put a click event on a particular image, so that it can allow to open another form or allow to display result in tabular form????????/
can u tell me how to do that????????/
using java swings
Java JComboBox Get Selected Item Value
Java JComboBox Get Selected Item Value
In this section we will discuss about how to get the selected item value form JComboBox.
javax.swing.JComboBox... example into which I shall get the combo box
selected item value and stored jdbc
awt jdbc programm in java to accept the details of doctor (dno,dname,salary)user & insert it into the database(use prerparedstatement class&awt
Handling Mouse Clicks in Java
the mouse click event in the
awt application.
This program simply implements the left click event of the mouse. When you
click "Click
Me" button...
Handling Mouse Clicks in Java
JFrame Components Printing - Swing AWT
...
but i go through the link that you have specified
and downloaded the codes and compiled it got...(ActionEvent event) {
PrintableDocument.printComponent(this);
}
class
JFrame components printing - Swing AWT
...
but i go through the link that you have specified
and downloaded the codes and compiled it got...);
}
public void actionPerformed(ActionEvent event) {
PrintableDocument.printComponent
mouse event - Java Beginners
=getContentPane();
setLayout(new FlowLayout());
setTitle("Mouse Event... Event");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(btnClose-awt - Swing AWT
Java Swings-awt Hi,
Thanks for posting the Answer... I need to design a tool Bar which looks like a Formating toolbar in MS-Office Winword(Standard & Formating) tool Bar.
Please help me... Thanks in Advance
Event Handling - Java Beginners
Event Handling import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame
{
JLabel lblNumber=new JLabel("Number");
JLabel lblSquareRoot=new JLabel("Square Root... menu item in it. assume that the user pressing down key 3 times. I need to show
The Window Event - Swing AWT
void actionPerformed(ActionEvent event) {
}
public static void swing button click event
java swing button click event java swing button click event
public void doClick()
Java Swing Tutorials
code - Swing AWT
code i want example problem for menubar in swings Hi Friend,
Please visit the following links:
Program for Calculator - Swing AWT
Program for Calculator write a program for calculator? Hi Friend,
Please visit the following link:
Hope that it will be helpful
Tree and a desktoppane - Swing AWT
Tree and a desktoppane Hi ,
Iam kind of new to Java... on top, a tree (separate java class outside using JTree and the corresponding... frame on the desktop pane.
I do not know how to fire the event in the tree
swings - Swing AWT
swings how to develope desktop applications using swing Hi Friend,
Please visit the following link:
Here you will get lot of swing applications
Image Selection - Swing AWT
click on any item, the image of that item should be selected as done in windows...();
}
}
------------------------------------------------
Read for more informaton.
Drag and Drop Example in SWT
Drag and Drop Example in SWT
Drag and Drop in Java - This section is going to illustrates you how to
create a program to drag and drop the tree item in Java .
In SWT
remove item from list box using java script - Java Beginners
remove item from list box using java script remove item from list box using java script Hi friend,
Code to remove list box item using java script :
Add or Remove Options in Javascript
function addItem | http://www.roseindia.net/tutorialhelp/comment/96275 | CC-MAIN-2014-10 | refinedweb | 1,932 | 62.38 |
Tea.pm - The Tiny Encryption Algorithm in Perl and JavaScript
Usage:
use Crypt::Tea; $key = 'PUFgob$*LKDF D)(F IDD&P?/'; $ascii_cyphertext = &encrypt ($plaintext, $key); ... $plaintext_again = &decrypt ($ascii_cyphertext, $key); ... $signature = &asciidigest ($text);
In CGI scripts:
use Crypt::Tea; print &tea_in_javascript; # now the browser can encrypt and decrypt ! In JS: var ascii_ciphertext = encrypt (plaintext, key); var plaintext_again = decrypt (ascii_ciphertext, key); var signature = asciidigest (text);
This module implements TEA, the Tiny Encryption Algorithm, and some Modes of Use, in Perl and JavaScript.
The $key is a sufficiently longish string; at least 17 random 8-bit bytes for single encryption.
Version 2.12, #COMMENT#
(c) Peter J Billam 1998
Encrypts with CBC (Cypher Block Chaining)
Decrypts with CBC (Cypher Block Chaining)
Returns an asciified binary signature of the argument.
Returns a compatible implementation of TEA in JavaScript, for use in CGI scripts to communicate with browsers.
The following routines are not exported by default, but are exported under the ALL tag, so if you need them you should:
import Crypt::Tea qw(:ALL);
Provides an ascii text encoding of the binary argument. If Tea.pm is not being invoked from a CGI script (as judged by the existence of $ENV{REMOTE_ADDR}), the ascii is split into lines of 72 characters.
Provides the binary original of an ascii text encoding.
At the browser end, the following functions offer the same functionality as their perl equivalents above:
Of course the same Key must be used by the Perl on the server and by the JavaScript in the browser, and of course you don't want to transmit the Key in cleartext between them. Let's assume you've already asked the user to fill in a form asking for their Username, and that this username can be transmitted back and forth in cleartext as an ordinary form variable.
On the server, typically you will retrieve the Key from a database of some sort, for example:
$plaintext = "<P>Hello World !</P>\n"; dbmopen %keys, "/home/wherever/passwords"; $key = $keys{$username}; dbmclose %keys; $cyphertext = &encrypt ($plaintext, $key);
At the browser end there are various ways of doing it. Easiest is to ask the user for their password every time they view an encrypted page, or submit a form.
print &tea_in_javascript(), <<EOT; <SCRIPT LANGUAGE="JavaScript"> <!-- var key = prompt("Password ?",""); document.write(decrypt("$cyphertext", key)); // --> </SCRIPT> EOT
To submit an encrypted FORM, the neatest way is to contruct two FORMs; one overt one which the user fills in but which never actually gets submitted, and one covert one which will hold the cyphertext.
print <<'EOT'; <SCRIPT LANGUAGE="JavaScript"> <!-- function submitter (form) { // NB: a javascript: url passes the frame var <INPUT TYPE="hidden" NAME="username" VALUE="$username"> <INPUT TYPE="hidden" NAME="cyphertext" VALUE=""> </FORM> <FORM NAME="overt" onSubmit="return submitter(this)"> <TABLE> <TR><TH>Contact</TH><TD><INPUT TYPE="text" NAME="contact"></TD></TR> <TR><TH>Date </TH><TD><INPUT TYPE="text" NAME="date"> </TD></TR> <TR><TH>Report </TH><TD><INPUT TYPE="text" NAME="report"> </TD></TR> </TABLE> <INPUT TYPE="submit"> </FORM> EOT
See the cgi script examples/tea_demo.cgi in the distribution directory.
If you want the browser to remember its Key from page to page, to form a session, then things get harder. If you store the Key in a Cookie, it is vulnerable to any imposter server who imitates your IP address, and also to anyone who sits down at the user's computer. However, this remains the most practical option.
The alternative is to store the Key in a JavaScript variable, but unfortunately all JavaScript variables get anihilated when you load a new page into the same target frame. Therefore you have to store the Key in a JavaScript variable in a frameset, open up a subframe covering almost all the screen, and load the subsequent pages into that subframe; they can then use parent.key to encrypt and decrypt. This can become intractable. See CGI::Htauth.pm for attempts to use this kind of technique.
Crypt::Tea works fine with most browsers. You can check out yours by viewing the test page test.html which is generated in the install directory when you run perl test.pl or make test. If you can read the paragraphs at the end, then everything works.
There is believed to be a problem with MacOS 10.2 Safari and IE browsers, in which binary operations like xor and shift mess up the leftmost bit of the word. The work-around would probably be to re-implement these machine instructions in JavaScript :-(
There is believed to be some problem in the core functions tea_code and tea_decode on the version of Konqueror reporting itself as Konqueror 5.0 (compatible; Konqueror/3.1; Linux) although the very similar Konqueror 5.0 (compatible; Konqueror/3.2; Linux) works fine.
Versions 2.xx can decrypt files encrypted by 1.xx, and version 1.45 can decrypt files encrypted by versions 2.xx. However, the digest (signature) functions of 1.xx and 2.xx differ in their use of '+' and '-' characters respectively. Version 1.45 will remain the final version in the 1.xx branch; the '+' character it used in the ascii-encoding is a reserved character in the query part of URLs.
Crypt::Tea can conflict with a similarly-named Crypt::TEA by Abhijit Menon-Sen. The functionality of Crypt::Tea is different from Abhijit's Crypt::TEA; here the encryption is done in pure Perl, all cyphertext is ascii-encoded, and notably there is a subroutine to return JavaScript code which implements compatible functions. Unfortunately, Microsoft operating systems confuse the two names and are unable to install both.
This version (2.11) is mature, and apart perhaps from minor bug fixes it will probably be the final version of Crypt::Tea. Further development will take place probably under the name Crypt::Tea_JS.
Crypt::Tea_JS will use some C for extra speed, and will use the new version of the TEA algorithm. The calling interface will be identical. Backward compatibility will be available for files encrypted with Crypt::Tea, but it will not be the default.
Peter J Billam ( ).
Based on TEA, as described in , and on some help from Applied Cryptography by Bruce Schneier as regards the modes of use. Thanks also to Neil Watkiss for the MakeMaker packaging, and to Scott Harrison for suggesting workarounds for MacOS 10.2 browsers, to Morgan Burke for pointing out the problem with URL query strings, and to Rolf Wagner for testing.
examples/tea_demo.cgi,, CGI::Htauth.pm, tea(1), perl(1). | http://search.cpan.org/dist/Crypt-Tea/Tea.pm | CC-MAIN-2016-40 | refinedweb | 1,087 | 55.95 |
In this tutorial, I will teach you how to create an Autocomple in a Combobox using C#.net and SQL Server 2005. With this, it will suggest the records when you start to type in the combobox then, you don’t have to click anymore the dropdown or scroll down the list of records that you’re going to select.
Let’s begin:
Create a database and name it “dbcombo”.
After creating database, do the following query for creating a table in the database that you have created.
Now , open Microsoft Visual Studio and create new Windows Form Application for C#. Then do the following design of a Form as follows.
After that, go to the Solution Explorer, double click the “View Code” to display the code editor.
In the code editor, declare all the classes that are needed.
Note: Put using System.Data.SqlClient; above the namespace to access sql server library.
After declaring the classes, establish a connection between SQL server and C#.net and retrieve the data in the database to display in the datagridview in the first load of the Form.
Now, go back to the design views, double click the TextBox and do the following codes for searching data in the datagridview.
Output:
For all students who need programmer for your thesis system or anyone who needs a sourcecode in any programming languages. You can contact me @ :
Mobile No. – 09305235027 – tnt | https://itsourcecode.com/free-projects/csharp/c-searching-data-datagridview-sql-server/ | CC-MAIN-2021-43 | refinedweb | 236 | 65.42 |
Right now I am using fread() to read a file, but in other language fread() is inefficient i'v been told. Is this the same in C? If so, how would faster file reading be done?
views:377
answers:7
I'm thinking of the read system call.
Keep in mind that fread is a wrapper for 'read'.
On the other hand fread has an internal buffer, so 'read' may be faster but i think 'fread' will be more efficient.
What's slowing you down?
If you need the fastest possible file reading (while still playing nicely with the operating system), go straight to your OS's calls, and make sure you study how to use them most effectively.
- How is your data physically laid out? For example, rotating drives might read data stored at the edges faster, and you want to minimize or eliminate seek times.
- Is your data pre-processed? Do you need to do stuff between loading it from disk and using it?
- What is the optimum chunk size for reading? (It might be some even multiple of the sector size. Check your OS documentation.)
If seek times are a problem, re-arrange your data on disk (if you can) and store it in larger, pre-processed files instead of loading small chunks from here and there.
If data transfer times are a problem, perhaps consider compressing the data.
If you are willing to go beyond the C spec into OS specific code, memory mapping is generally considered the most efficient way.
For Posix, check out
mmap and for Windows check out
OpenFileMapping
If
fread is slow it is because of the additional layers it adds to the underlying operating system mechanism to read from a file that interfere with how your particular program is using
fread. In other words, it's slow because you aren't using it the way it has been optimized for.
Having said that, faster file reading would be done by understanding how the operating system I/O functions work and providing your own abstraction that handles your program's particular I/O access patterns better. Most of the time you can do this with memory mapping the file.
However, if you are hitting the limits of the machine you are running on, memory mapping probably won't be sufficient. At that point it's really up to you to figure out how to optimize your I/O code.
It really shouldn't matter.
If you're reading from an actual hard disk, it's going to be slow. The hard disk is your bottle neck, and that's it.
Now, if you're being silly about your call to read/fread/whatever, and say, fread()-ing a byte at a time, then yes, it's going to be slow, as the overhead of fread() will outstrip the overhead of reading from the disk.
If you call read/fread/whatever and request a decent portion of data. This will depend on what you're doing: sometimes all want/need is 4 bytes (to get a uint32), but sometimes you can read in large chunks (4 KiB, 64 KiB, etc. RAM is cheap, go for something significant.)
If you're doing small reads, some of the higher level calls like fread() will actual help you by buffering data behind your back. If you're doing large reads, it might not be helpful, but switching from fread to read will probably not yield that much improvement, as you're bottlenecked on disk speed.
In short: if you can, request a liberal amount when reading, and try to minimize what you write. For large amounts, powers of 2 tend to be friendlier than anything else, but of course, it's OS, hardware, and weather dependent.
So, let's see if this might bring out any differences:
#include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #define BUFFER_SIZE (1 * 1024 * 1024) #define ITERATIONS (10 * 1024) double now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.; } int main() { unsigned char buffer[BUFFER_SIZE]; // 1 MiB buffer double end_time; double total_time; int i, x, y; double start_time = now(); #ifdef USE_FREAD FILE *fp; fp = fopen("/dev/zero", "rb"); for(i = 0; i < ITERATIONS; ++i) { fread(buffer, BUFFER_SIZE, 1, fp); for(x = 0; x < BUFFER_SIZE; x += 1024) { y += buffer[x]; } } fclose(fp); #elif USE_MMAP unsigned char *mmdata; int fd = open("/dev/zero", O_RDONLY); for(i = 0; i < ITERATIONS; ++i) { mmdata = mmap(NULL, BUFFER_SIZE, PROT_READ, MAP_PRIVATE, fd, i * BUFFER_SIZE); // But if we don't touch it, it won't be read... // I happen to know I have 4 KiB pages, YMMV for(x = 0; x < BUFFER_SIZE; x += 1024) { y += mmdata[x]; } munmap(mmdata, BUFFER_SIZE); } close(fd); #else int fd; fd = open("/dev/zero", O_RDONLY); for(i = 0; i < ITERATIONS; ++i) { read(fd, buffer, BUFFER_SIZE); for(x = 0; x < BUFFER_SIZE; x += 1024) { y += buffer[x]; } } close(fd); #endif end_time = now(); total_time = end_time - start_time; printf("It took %f seconds to read 10 GiB. That's %f MiB/s.\n", total_time, ITERATIONS / total_time); return 0; }
...yields:
$ gcc -o reading reading.c $ ./reading ; ./reading ; ./reading It took 1.141995 seconds to read 10 GiB. That's 8966.764671 MiB/s. It took 1.131412 seconds to read 10 GiB. That's 9050.637376 MiB/s. It took 1.132440 seconds to read 10 GiB. That's 9042.420953 MiB/s. $ gcc -o reading reading.c -DUSE_FREAD $ ./reading ; ./reading ; ./reading It took 1.134837 seconds to read 10 GiB. That's 9023.322991 MiB/s. It took 1.128971 seconds to read 10 GiB. That's 9070.207522 MiB/s. It took 1.136845 seconds to read 10 GiB. That's 9007.383586 MiB/s. $ gcc -o reading reading.c -DUSE_MMAP $ ./reading ; ./reading ; ./reading It took 2.037207 seconds to read 10 GiB. That's 5026.489386 MiB/s. It took 2.037060 seconds to read 10 GiB. That's 5026.852369 MiB/s. It took 2.031698 seconds to read 10 GiB. That's 5040.119180 MiB/s.
...or no noticeable difference. (fread is winning sometimes, sometimes read)
Note: The slow
mmap is surprising. This might be due to me asking it to allocate the buffer for me. (I wasn't sure about requirements of supplying a pointer...)
In really short: Don't prematurely optimize. Make it run, make it right, make it fast, that order.
Back by popular demand, I ran the test on a real file. (The first 675 MiB of the Ubuntu 10.04 32-bit desktop installation CD ISO) These were the results:
# Using fread() It took 31.363983 seconds to read 675 MiB. That's 21.521501 MiB/s. It took 31.486195 seconds to read 675 MiB. That's 21.437967 MiB/s. It took 31.509051 seconds to read 675 MiB. That's 21.422416 MiB/s. It took 31.853389 seconds to read 675 MiB. That's 21.190838 MiB/s. # Using read() It took 33.052984 seconds to read 675 MiB. That's 20.421757 MiB/s. It took 31.319416 seconds to read 675 MiB. That's 21.552126 MiB/s. It took 39.453453 seconds to read 675 MiB. That's 17.108769 MiB/s. It took 32.619912 seconds to read 675 MiB. That's 20.692882 MiB/s. # Using mmap() It took 31.897643 seconds to read 675 MiB. That's 21.161438 MiB/s. It took 36.753138 seconds to read 675 MiB. That's 18.365779 MiB/s. It took 36.175385 seconds to read 675 MiB. That's 18.659097 MiB/s. It took 31.841998 seconds to read 675 MiB. That's 21.198419 MiB/s.
...and one very bored programmer later, we've read the CD ISO off disk. 12 times. Before each test, the disk cache was cleared, and during each test there was enough, and approximately the same amout of, RAM free to hold the CD ISO twice in RAM.
One note of interest: I was originally using a large malloc() to fill memory and thus minimize the effects of disk caching. It may be worth noting that
mmap performed terribly here. The other two solutions merely ran,
mmap ran and, for reasons I can't explain, began pushing memory to swap, which killed its performance. (The program was not leaking, as far as I know (the source code is above) - the actual "used memory" stayed constant throughout the trials.)
read() posted the fastest time overall, fread() posted really consistent times. This may have been to some small hiccup during the testing, however. All told, the three methods were just about equal. (Especially
fread and
read...)
The problem that some people have noted here, is that depending on your source, your target buffer size, etc, you can create a custom handler for that specific case, but there are other cases, like block/character devices, i.e. /dev/* where standard rules like that do or don't apply and your backing source might be something that pops character off serially without any buffering, like an I2C bus, standard RS-232, etc. And there are some other sources where character devices are memory mappable large sections of memory like nvidia does with their video driver character device (/dev/nvidiactl).
One other design implementation that many people have chosen in high-performance applications is asynchronous instead of synchronous I/O for handling how data is read. Look into libaio, and the ported versions of libaio which provide prepackaged solutions for asynchronous I/O, as well as look into using read with shared memory between a worker and consumer thread (but keep in mind that this will increase programming complexity if you go this route). Asynchronous I/O is also something that you can't get out of the box with stdio that you can get with standard OS system calls. Just be careful as there are bits of read which are `portable' according to the spec, but not all operating systems (like FreeBSD for instance) support POSIX STREAMs (by choice).
Another thing that you can do (depending on how portable your data is) is look into compression and/or conversion into a binary format like database formats, i.e. BDB, SQL, etc. Some database formats are portable across machines using endianness conversion functions.
In general it would be best to take a set of algorithms and methods, run performance tests using the different methods, and evaluate the best algorithm that serves the mean task that your application would serve. That would help you determine what the best performing algorithm is.
Maybe check out how perl does it. Perl's I/O routines are optimized, and are, I gather, the reason why processing text with a perl filter can be twice as fast as doing the same transformation with
sed.
Obviously perl is pretty complex, and I/O is only one small part of what it does. I've never looked at its source so I couldn't give you any better directions than to point you here. | http://ansaurus.com/question/3002122-fastest-file-reading-in-c | CC-MAIN-2017-47 | refinedweb | 1,858 | 74.9 |
Information to Semantically Enable Your Systems
Semantic Information Integration
Smarter Integration
Smarter Access
The ontoprise ontobroker system is a main memory deductive, object oriented database system. It provides compilers for different languages to describe ontologies, rules and facts. Ontobroker may be used in three different ways: i) it may be used as a separate application which reads input files containing facts, rules and queries, which then evaluates the queries and finally prints the answer s, ii) it may be used as a server which reads input files containing facts and rules and which then evaluates queries sent to the server and sends the results back and iii) it may be used as a library for integrating inferencing services in own applications. For the last point it is important that ontobroker is entirely written in Java and that there exists a well documented small API to the internal data model and to methods to generate facts and rules and to evaluate queries.
Ontobroker may be seen as a middle ware run time system to provide an information delivering base for intranet and extranet applications, for knowledge management systems for e-commerce systems and in general for intelligent applications. Ontobroker integrates the access to different information sources like databases, keyword based search engines etc. It reads various input formats like EXCEL, XML, RDF, DAML+OIL, F-Logic, Prolog. Thus it provides a homogeneous access to an inhomogeneous set of information sources and input formats.
Ontobroker is normally accomplied by a set of other tools. The ontoprise OntoEdit is an interactive editor to define ontologies, describe nstances, define rules etc. OntoEdit may be configured with a light-wight version of our inference engine to support the development and debugging of rules. OntoCollect is a tool to annotate documents. These annotations may be used to acquire facts out of the documents or to have a template to acquire facts from other similarily structured documents. This may be used as a wrapper to repeatedly acquire actual information out of the web.
Ontobroker may be accessed from the web- and application-server Zope using an External Python script. For the connection you can use the “ontobroker_client.py” script. It consist of a core class named “Client”. It also supports you with a function named “query(q, h, p)”, where the q,h,p stands for query, host, and port respectively. The second function named “makeSearchList(q, h, p)” separates the query strings and puts them into a list.
A simple way of testing is putting these three lines in a script:
import ontobroker_client
list = ontobroker_client.query("FORALL X,Y <- X::Y.", "localhost", 1234)
for item in list: print item
You may have to correct the host and/or the port. You can add further functions, specialised for your purpose of use and access them from within Zope by adding an External Method which calls the required function. | http://old.zope.org/Members/ontoprise/obc/ | CC-MAIN-2015-27 | refinedweb | 481 | 50.87 |
menu_userptr(3) UNIX Programmer's Manual menu_userptr(3)
menu_userptr - associate application data with a menu item
#include <menu.h> int set_menu_userptr(MENU *menu, void *userptr); void *menu_userptr(const MENU *menu);
Every menu and every menu item has a field that can be used to hold application-specific data (that is, the menu-driver code leaves it alone). These functions get and set the menu user pointer field.
Except for menu_userptr (which returns NULL on error), each function returns one of the following: E_OK The routine succeeded. E_SYSTEM_ERROR System error occurred (see errno).
curses(3), menu(3).
The header file <menu.h> automatically includes the header file <curses.h>.
These routines emulate the System V menu. | http://mirbsd.mirsolutions.de/htman/sparc/man3/menu_userptr.htm | crawl-003 | refinedweb | 115 | 58.38 |
Subject: Re: [OMPI devel] Bug in openmpi-1.5/opal/config/opal_config_asm.m4
From: George Bosilca (bosilca_at_[hidden])
Date: 2011-02-23 16:59:37
Jay,
Thanks for the code. The code you pointed out is only used during configure, so I don't think is that critical. However, we use similar code deep into our voodoo assembly generation, for opal_atomic_add_32 and opal_atomic_sub_32.
So if I understand your statement the correct version of the code should be
static inline int32_t opal_atomic_add_32(volatile int32_t* v, int i)
{
int ret = i;
__asm__ __volatile__(
SMPLOCK "xaddl %1,%0"
:"=m" (*v), "+r" (ret)
>> new >> :"m" (*v)
);
return (ret+i);
}
On the GCC extended ASM documentation (), it is specified:
`=' Means that this operand is write-only for this instruction: the previous value is discarded and replaced by output data.
`+' Means that this operand is both read and written by the instruction.
Based on this info, I would rather rewrite this function like this:
static inline int32_t opal_atomic_add_32(volatile int32_t* v, int i)
{
int ret = i;
__asm__ __volatile__(
SMPLOCK "xaddl %1,%0"
: "=m" (*v), "=r" (ret)
: "m" (*v), "1" (ret)
: "memory", "cc"
);
return (ret+i);
}
Can you ask the kindly GCC expert which version is "correct" (whatever the definition of correct might means related to GCC extended assembly). Do I have to specify = for the output if I put the register on the input? Aren't this conflicting?
george.
On Feb 23, 2011, at 13:04 , Jay Fenlason wrote:
> I was recently handed
>
> for which a kindly GCC expert attached the enclosed patch. Apparently
> this only causes problems on 32-bit i686 machines, which could by why
> it has gone undetected until now.
>
> -- JF
>
> --- openmpi-1.5/opal/config/opal_config_asm.m4.jj 2010-09-28 23:33:51.000000000 +0200
> +++ openmpi-1.5/opal/config/opal_config_asm.m4 2011-02-23 01:39:21.191433509 +0100
> @@ -885,7 +885,7 @@ AC_DEFUN([OMPI_CONFIG_ASM],[
>-*)
> _______________________________________________
> devel mailing list
> devel_at_[hidden]
>
"I disapprove of what you say, but I will defend to the death your right to say it"
-- Evelyn Beatrice Hall | https://www.open-mpi.org/community/lists/devel/2011/02/9014.php | CC-MAIN-2016-18 | refinedweb | 342 | 60.14 |
I’ve been asked to make a Java JTable tutorial by many people. Today I’ll show you how to display database query results from my Sabermetrics Tutorial into a Java JTable.
I then cover most everything about Java JTables. How to display data into a JTable. How to change fonts in a JTable. How to change row height in a JTable. How to sort a JTable. How to align a JTable column and much more.
All of the code follows the tutorial and it has even more tricks.
If you like videos like this, please tell Google [googleplusone]
Code from the Video
import java.awt.BorderLayout; import java.awt.Font; import java.sql.*; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; public class Lesson36{ // Used to hold the column data for each player static Object[][] databaseInfo; // The column titles for the JTable static Object[] columns = {"Year", "PlayerID", "Name", "TTRC", "Team", "Salary", "CPR", "POS"}; // A ResultSet contains a table of data filled // with the results of the query. static ResultSet rows; // ResultSetMetaData contains information on // the data returned by the query static ResultSetMetaData metaData; // DefaultTableModel defines the methods JTable will use // I'm overriding the getColumnClass static DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo,; } }; public static void main(String[] args){ JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);/lahman591","mysqladm","turtledove"); // Statement objects executes a SQL query // createStatement returns a Statement object Statement sqlState = conn.createStatement(); // This is the query I'm sending to the database, s.salary AS Salary, " + "CAST( s.salary/(((b.H+b.BB)+(2.4*(b.AB+b.BB)))*(t.TB+(3*(b.AB+b.BB)))/(9*(b.AB+b.BB))-(.9*(b.AB+b.BB))) as decimal(10,2)) AS CPR, " + "f.POS AS POS FROM Batting b, Master m, Salaries s, TOTBYR t, Fielding f " + "WHERE b.playerID = m.playerID AND t.playerID = m.playerID " + "AND t.yearID = 2010 AND b.yearID = t.yearID AND s.playerID = b.playerID " + "AND s.yearID = b.yearID AND b.AB > 50 AND b.playerID = f.playerID " + "AND b.playerID = t.playerID GROUP BY b.playerID ORDER BY TTRC DESC LIMIT 200;"; /* Have to cut out salary because it isn't in database for 2011, 0 AS Salary, " + "0 AS CPR, f.POS AS POS " + "FROM Batting b, Master m, Fielding f, TOTBYR as t " + "WHERE b.playerID = m.playerID AND t.playerID = m.playerID " + "AND t.yearID = 2011 AND b.yearID = t.yearID " + "AND b.AB > 100 AND f.playerID = b.playerID " + "GROUP BY b.playerID ORDER BY TTRC DESC LIMIT 200;"; */ // A ResultSet contains a table of data representing the // results of the query. It can not be changed and can // only be read in one direction rows = sqlState.executeQuery(selectStuff); /* int numOfCol; // Retrieves the number, types and properties of the Query Results metaData = rows.getMetaData(); // Returns the number of columns numOfCol = metaData.getColumnCount(); // One way to get the column titles columns = new String[numOfCol]; for(int i=1; i<=numOfCol; i++) { // Returns the column name columns[i] = metaData.getColumnName(i); System.out.println(i); } */ // Temporarily holds the row results Object[] tempRow; // next is used to iterate through the results of a query while(rows.next()){ // Gets the column values based on class type expected tempRow = new Object[]{rows.getInt(1), rows.getString(2), rows.getString(3), rows.getDouble(4), rows.getString(5), rows.getInt(6), rows.getDouble(7), rows.getString(8)}; // Adds the row of data to the end of the model(); } // Create a JTable using the custom DefaultTableModel JTable table = new JTable(dTableModel); // Increase the font size for the cells in the table table.setFont(new Font("Serif", Font.PLAIN, 20)); // Increase the size of the cells to allow for bigger fonts table.setRowHeight(table.getRowHeight()+10); // Allows the user to sort the data table.setAutoCreateRowSorter(true); /* If you want to right justify column * TableColumn tc = table.getColumn("TTRC"); RightTableCellRenderer rightRenderer = new RightTableCellRenderer(); tc.setCellRenderer(rightRenderer); */ // Disable auto resizing table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Set the width for the columns TableColumn col1 = table.getColumnModel().getColumn(0); col1.setPreferredWidth(100); TableColumn col2 = table.getColumnModel().getColumn(1); col2.setPreferredWidth(190); TableColumn col3 = table.getColumnModel().getColumn(2); col3.setPreferredWidth(260); TableColumn col5 = table.getColumnModel().getColumn(5); col5.setPreferredWidth(200); TableColumn col6 = table.getColumnModel().getColumn(6); col6.setPreferredWidth(200); // Change justification of column to Center TableColumn tc = table.getColumn("Team"); CenterTableCellRenderer centerRenderer = new CenterTableCellRenderer(); tc.setCellRenderer(centerRenderer); tc = table.getColumn("POS"); centerRenderer = new CenterTableCellRenderer(); tc.setCellRenderer(centerRenderer); JScrollPane scrollPane = new JScrollPane(table); frame.add(scrollPane, BorderLayout.CENTER); frame.setSize(800, 500); frame.setVisible(true); } } // How to change justification to the right class RightTableCellRenderer extends DefaultTableCellRenderer { public RightTableCellRenderer() { setHorizontalAlignment(JLabel.RIGHT); } } // Change justification to the center class CenterTableCellRenderer extends DefaultTableCellRenderer { public CenterTableCellRenderer() { setHorizontalAlignment(JLabel.CENTER); } }
Thanks again, we were waiting for this one, and after 5 days we have got this nice tutorial. Wish u have a nice day.
I’m glad you like it. I thought it would be fun to actually make a nice tool instead of just covering the API. I have a much bigger project planned. This tutorial series seems to be losing interest so I’m going to experiment with more tutorials like this one.
I kind of like it when a tutorial loses its audience. Can you tell that I don’t make tutorials just to make money 🙂
I never comment on tutorials but I had to comment on yours. THIS WAS A FANTASTIC TUTORIAL ON JTABLE!!!!! It answered most of my questions and I am truly greatful.
I’m very happy that I was able to explain this often confusing subject. I just made another video on Java JTables. It and part 38 will cover everything you can do with them. Thank you for taking the time to show your appreciation 🙂
I never expected there is something like your tutorials on the internet.
…..THANK YOU
You’re very welcome 🙂 I’m glad you found me because I don’t think many people know about my site
Why is there a table named “TOTBYR” on line 87 when there is no such table given in this database? Error that shows up on my console says: “Table ‘lahman591.totbyr’ doesn’t exist”.”
I downloaded the this sql database.
Any idea how to fix this? :-/
The reason why is because this tutorial was meant to be used in combination with my SQL review tutorial using sabermetrics. This is the tutorial in which I created TOTBYR Sabermetrics Video Tutorial. I have all the tutorials on this page Baseball Sabermetrics.
I decided to cover a real world topic while talking about SQL and Java. I hope that helps – Derek
Cool =) Looking forward to it =)
Dear Derek,
thanks for your awesome tutorials on JTable and SQL, I am a student who is trying to practise some SQL and java coding skills during the winter holiday, your tutorials have been extremely helpful. as you said in this video, this one is a good example for model view controler design. if you are making any totorials about MVC, I was wondering if you could use this JTable and SQL to illustrate MVC, please? (I asked you about MVC tutorial a few days ago) many thanks
You’re very welcome 🙂 Yes, I’m going to cover MVC in its on tutorial very soon. I’ll do my best to make it completely understandable so it can be used in any context. Thanks for the request
many thanks derek, happy new year!
Happy New year!
SIR kindly teach me how to make a download manager in java and how RMI works
plz sir………..
I will definitely cover those topics asap. Thank you for the request
This tutorials are THE BEST OF THE BEST – THANKS A LOT !!!
You’re very welcome 🙂
This tutorials are THE BEST OF THE BEST -THANKS A LOT !!!
Please, add the MVC version of this code in your MVC tutorial
I’ll be doing a great deal more with MVC in upcoming tutorials. I’m glad you like them 🙂
I have seen so many tutorial’s but urs is to the point i realy appreciate for your time hope you will have some new ones for other languages.
Thank you 🙂
Derek,
I have been looking at tutorials on different ways to process ResultSets into JTables for about the past 168 hours straight! I either just couldn’t understand or couldn’t get the other methods to work at all… 🙁
I found your tutorial today and within an hour I have a working program that processes my ResultSet into a JTable. You are awesome bro! Thank you for taking the time and effort to help people like me.
– James
p.s. Before I even saw your post about the e-cig I had been trying to quit smoking for about a week… I still smoke 3 or 4 real ones per day, but it is way better than my usual pack a day! So glad it worked for you, just don’t start again… Who will write these wonderful tuts if you aren’t here for us?
I’m very happy that I was able to help.
Yes I had quit smoking for a few weeks now and then over the years, but I could never eliminate them 100%. I quit a few months ago so I won’t go back. I’m pretty good at hypnosis, so with a bit of that and the E Cigs I’m good to go now. Keep at it and try a bunch of different devices. I’m still messing around with devices now, but the eGo Twist is pretty great
What do you hypnotize us to do?
Because it is quite unbeliveable
you create those quality tutorials
just for fun.
Just kidding of course. (Or am I?)
Anyway, many thanks from Poland.
(yes, we DO have computers here)
That’s funny 🙂 I receive an infinite amount of pleasure from helping so many people! I also get to talk to a ton of extremely nice people all over the world like yourself. Being pretty much a country boy, you can’t imagine how amazing that is to me.
Thank you for visiting my site
” Unknown column ‘t.playerID’ in ‘where clause’ ” thats what I get when I run the program….I copied your sql code I didnt add and remove anything from it
Nice tutorial but I get problem. ” Unknown column ‘t.playerID’ in ‘where clause’ ” thats what I get when I run the program….I copied your sql code I didnt add and remove anything from it
Thank you 🙂 There must be a typo some place. Sorry I can’t think of anything else
This makes creating JTables easy. I have been looking for something. Most of the tutorials I found make JTable sound and feel more complicated. Many thanks.
That is the best compliment I can get 🙂 I work very hard to find the simplest way to teach these topics. Thank you
Hi!
This is great. Thank you.
You’re very welcome 🙂
Hi Derek,
thank you very much for these works. It’s Perfekt.
Can you help me please? I get error while reading from database. Error is “SQLException: Table ‘lahman.Batting’ doesn’t exist
VendorError: 1146”
But i have the table. Do you know why is this Error? GUI is there without any results 🙁
Thank you.
Regards,
Jan
Hallo again,
sorry for bothering you. I found my fault. But i have another problem. I dont have the table TOTBYR. Where is this from?
Thank you.
Regards,
Jan
Hi Jan,
I created that table in my Sabermetrics tutorial. It was my idea to teach MySQL using a fun topic like baseball. You can find all the code and videos here Sabermetrics Tutorial.
Hello Derek,
Your teaching style is not making me gaining programming sense.
For example: For displaying data in JTable from Database, you involved many new concepts in this tutorial like overriding methods of parent class, Using syntax like ‘Object.class’, using keyword like ‘Class’.
So, Looks like i am feeling difficult to grab the purpose of such 3 concepts(above), as you are directly using it in this context.
It took me one day to understand after runtime debug to know, what is ‘Object.class’, because google also doesn’t show this.
Hello,
I basically require people to watch every video in order like you would in a college course. That is why I don’t give the specific java tutorials names other then just numbers. I can definitely understand why my videos would be hard for some people to grasp because I go very fast. I try to make up for that by recovering topics that people are struggling with.
For best results it helps to print out the code and take notes as you watch. Then if you have any questions you can pass them to me and then write out the answers in your own words.
Sorry the tutorials didn’t work for you.
Derek
Hello Derek,
I think your tutorial looks perfect for people who already played around with basic java concepts and i understand it would be too difficult for you to teach examples on each basic concept after you worked for 30 years in the industry. I would contradict myself with my point, when i talk about C tutorial where you teach all such basics, instead of going in depth ):
May be i will come to this tutorial after i go to another java tutorial which teaches all such building blocks separately.
I write my code according to yours, but it doesn’t work. Can you help me solve it?
public class View extends JFrame{
JFrame frame;
JTable table;
JButton makeAppointment;
public Login3Doctor( String[][] viewInfo,String[] columns){
DefaultTableModel dTableModel = new DefaultTableModel(viewInfo, columns){
public Class getColumnClass(int column) {
Class returnValue;
// Verifying that the column exists (index > 0 && index = 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
// Returns the class for the item in the column
returnValue = Object.class;
}
return returnValue;
}
};
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table=new JTable(dTableModel);
table.setFont(new Font("Serif", Font.PLAIN, 20));
table.setRowHeight(table.getRowHeight()+10);
table.setAutoCreateRowSorter(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn col1 = table.getColumnModel().getColumn(0);
col1.setPreferredWidth(200);
TableColumn col2 = table.getColumnModel().getColumn(1);
col2.setPreferredWidth(200);
TableColumn col3 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(200);
TableColumn col4 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(200);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(800, 500);
//frame.setVisible(true);
}
public static void main(String[] args){
String[][] b={{"s","m","10","xixi","ha"},
{"h","a","1","a","e"},
{"a","b","2","4","3"}};
String[] c={"name","sex","age","lkj","4342"};
Login3Doctor v=new Login3Doctor(b,c);
v.setVisible(true);
}
What error are you getting?
Can we use text file instead of mysql database….
and we have to get same as now…
if so,pls help me for this code,
i’ve already written the code,but its not giving the contents of the file as columns,
soo,pls help me..
pls respond quickly…
I cover how to use files on this page in parts 31 – 33. I hope it helps 🙂
Hi Derek,
I just wanted to say thank you so much for all the effort you put in! I’m a first year CS student and I learn faster from you than my lecturers. I’m a long time subscriber, first time commenter though. hehe.
Thanks again! I just wish I could verbally express the extent of my gratitude.
-Mufhim
Hi Mufhim,
Thank you 🙂 I’m glad you are finding the videos useful. Many more are coming.
Hi Derek
Thanks for the great tutorials. Just one question please. I get an error on line 045.
returnValue = getValueAt(0, column).getClass();
-what does the 0 represent?
Thanks very much Derek for the series. They are great. I just have one question please.
Line 045 what does 0 represent in the statement
returnValue = getValueAt(0, column).getClass(); | http://www.newthinktank.com/2012/04/java-video-tutorial-36/?replytocom=19139 | CC-MAIN-2019-43 | refinedweb | 2,677 | 59.5 |
in reply to Control Flow - Multiple returns or nested conditionals
Thanks for creating this node. I've often wondered if what I'm doing is the right thing. I tend to flip-flop between both methods based on the following criteria:
* If the routine has flow modifiers like goto or next, I use a single return statement.
* If the routine has no flow modifiers and has code duplication that aids readability, I use multiple return statements to keep each duplicated section independent (they can now be jettisoned on-demand).
* If the routine has flow modifiers and code duplication, I use multiple return statements with a debug print statement before every return (during development). I also suddenly turn religious and start praying.
Writing mostly baby Perl (see "Baby" Perl versus "Bad" Perl), though, means I don't really adhere to "coding standards".
~RecursionBane
My spouse
My children
My pets
My neighbours
My fellow monks
Wild Animals
Anybody
Nobody
Myself
Spies
Can't tell (I'm NSA/FBI/HS/...)
Others (explain your deviation)
Results (52 votes). Check out past polls. | http://www.perlmonks.org/index.pl?node_id=864276 | CC-MAIN-2016-50 | refinedweb | 178 | 54.32 |
Distributing Candies equally
Sign up for FREE 1 month of Kindle and read all our books for free.
Get FREE domain for 1st year and build your brand new site
Reading time: 20 minutes | Coding time: 10 minutes
Given n candy boxes, each box contains different number of candies. We need to distribute the candies amongst k friends such that:
- All friends get equal number of candies
- All the candies which a particular friend gets must be from a single box only.
Solving this problem will require concepts of Binary Search. This will take O(N * logM) time complexity where there are N boxes and M is the maximum number of candies in a box.
Find the maximum number of candies that can be distributed.
Number of candies in each box: 3, 1, 4
Number of friends: 2
Output: 3
Explanation: For 2 friends, 3 is the maximum number. We cannot have 4, because 3 and 1 are in different boxes and each person can get candies from one box only so we took
Number of candies in each box: 3, 2, 3, 9
Number of friends: 1
Output: 9
Here, I need you to note one thing.
More than one person can get the candies from the same box i.e. if there are 4 candies in the box, it’s possible that 2 persons take 2 candies each. Here’s a test case that can explain it:
k = 4
2, 4, 1, 3, 1
We can distribute maximum 2 candies to each person. Here box with 4 candies is used two times.
Alright, let’s see how we can do it.
What’s the maximum candies you can distribute to each person?
The sum of all the candies in the array? No!!!
Because remember, the candies given to a person can be from the same box only. So the maximum candies you can distribute to each person is the maximum element from the array. You cannot go beyond that. And since we have non zero candies in the box, the minimum we can give is 1. So, to any person, you can give candies ranging from 1 to max.
You can do one thing, starting from 1 to max, try to find if you can serve all the k people. Following example will make it clear:
In the case of 2, 4, 1, 3, 1
K = 4 people,
Max = 4,
We can distribute either 1, 2, 3, or 4 candies to each person.
- If I decide to distribute 1 candy to each person,
Total people I can serve is : 2/1 + 4/1 + 1/1 + 3/1 + 1/1 = 11 and 11>k (4). Thus I can give 1 candy.
We did sum(arr[i] / candyToEach) to find the number of people who can get candies. Why? You think about it by yourself before moving on.
It’s simple. 10 candies in a box, I can give 2 to each. How many people I can serve to the max? 10/2 = 5. If there are n boxes, I will find out how many people I can serve with each box, and sum it over n to find the total number of people that I can serve. Going back to the example…
If I decide to distribute 2 candies to each person.
Total people I can serve is: 2/2 + 4/2 + ½ + 3/2 + ½ = 4 and 4==k. Thus I can give 2 candies to each person as well.
If I decide to distribute 3 candies to each person.
Total people I can serve is : ⅔ + 4/3 + ⅓ + 3/3 + ⅓ = 2. I can only serve 2 people which I cannot do.
Since 3 candies cannot fill 4 people equally with given conditions, even 4 candies won’t. Thus the answer is 2 candies.
We are done then, right? We find the max in the array. Starting from 1 to max, we start distributing the candies and find the number of people we can serve. Once that number is less than k we stop.
Could you optimize it?
Optimization
Here’s a hint: let z is the max in the candy box
We are checking the distribution of candies from 1 to z.
If you can give z/2 candies to k or more people, is there a need to check for the number of candies between 1 to z/2? No! Because you have to distribute the maximum amount. You would definitely have to check for candies between z/2 to z.
If you cannot give z/2 candies to k people, you won’t increase the amount of distribution, as that will lead to less than k people. Thus you will decrease your bound and search for a number between 1 to z/2.
What comes to your mind??
Binary search it is! And this way, we solved the given problem.
Read about binary search
This was an interesting problem. I would encourage you to understand it clearly and code it by yourself.
Algorithm
1. Find the maximum in the candy box array (to find the upper bound for binary search). 2. Apply binary search with low = 1 high = max 3. a. If we can distribute candies with mid as the value of candies given to each person, we set low to be mid+1 and result to be mid, i.e our search space shifts to the right side b. Else high = mid-1, i.e our search space shifts to left side. 4. Output the result.
Implementation
Following is the code in java to this problem:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class CandyDistribution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //testcases int t = Integer.parseInt(br.readLine()); while (t-- > 0){ String[] input = br.readLine().split(" "); //n: number of candy boxes int n = Integer.parseInt(input[0]); //k: number of friends long k = Long.parseLong(input[1]); String[] input1 = br.readLine().split(" "); long[] arr = new long[n]; long max = Integer.MIN_VALUE; for(int i=0; i<n; i++){ arr[i] = Long.parseLong(input1[i]); //we need to find max for the upper bound in the binary search. max = Math.max(max,arr[i]); } System.out.println(binarySearch(n, k, arr, max)); } } public static long binarySearch(int n, long k, long[] arr, long max){ long low = 1; long high = max; long mid; long res = 0; while (high>=low){ mid = low + (high-low)/2; if(canDistribute(mid, n, k, arr)){ low = mid+1; res = mid; } else{ high = mid-1; } } return res; } public static boolean canDistribute(long val, int n, long k, long[] arr){ if(k==1){ return true; } long peopleServed = 0; for (int i=n-1; i>=0; i--){ //this is the number of people who can get candy peopleServed += arr[i]/val; } if(peopleServed>=k){ return true; } return false; } }
Complexity
Time complexity
O(log(max)*n)
where n is the number of candy boxes and max is the maximum in the candy box array. log is an optimization because of binary search
Space complexity
O(1)
We are not using any data structure to store anything. | https://iq.opengenus.org/distribute-candies/ | CC-MAIN-2021-17 | refinedweb | 1,198 | 73.27 |
0
This is a homework problem; however I just want some direction. I have to write a module graph.cpp that implements djikstra's algorithm. so far i am at the reading in module and am trying to make an array of structures. here is the code.
// Zachary Dain // CSCI 3300 Assignment 3 // tab stops: every 2 spaces #include <iostream> #include <math.h> using namespace std; enum StatusType {Done, Pending, Peripheral}; struct ListCell { ListCell* next; int adjVertex; double weight; ListCell(int v, double wt, ListCell* n) { adjVertex = v; weight = wt; next = n; } }; struct arrayOfStructs { StatusType s; ListCell* cell; arrayOfStructs() { s = Pending; cell = NULL; } }; // readGraph() reads in the graph and puts the // values into the appropriate lists/PQ void readGraph(int n) { int firstVert, secondVert; double weight; arrayOfStructs[] j = new arrayOfStructs[n+1]; while(firstVert != 0) { cin >> firstVert; if(firstVert != 0) { cin >> secondVert; cin >> weight; j[firstVert].cell = new ListCell(secondVert,weight, j[firstVert].cell); j[secondVert].cell = new ListCell(firstVert,weight, j[secondVert].cell); } } } int main() { int numVertex; cin >> numVertex; readGraph(numVertex); }
I am getting the following errors:
graph.cpp: In function ‘void readGraph(int)’:
graph.cpp:43: error: expected unqualified-id before ‘[’ token
graph.cpp:51: error: ‘j’ was not declared in this scope
make: *** [graph] Error 1
I understand that the second error is due to the first one. I have looked around and have found no solution. Any advice? Should i use a typedef?
Edited by zrd0808: n/a | https://www.daniweb.com/programming/software-development/threads/262635/dijkstra-algorithm | CC-MAIN-2017-17 | refinedweb | 242 | 59.6 |
Hi all, I am so impressed with you, you do great with this stuff. I am at the end of my class, thank goodness. I will always have total respect for you!
I am completely lost. I think I have messed up and can't even figure out what I am doing wrong and what I need to do to make this compile. Please Please help me!!!!
//This is a personal address book that contains many enteries.
#include <iostream.h>
main()
{
struct AddressBook //header for structure and able to enter 10 people
{
char Name[15]; //declaring the name and size of 15 characters
char Address[15];
char City[25];
int age[3]; //declaring the age and 3 intergers
char zip[5];
char phonenumber[10];
};
input (void)
{
cout<<"Welcome to my address book!\n"
cout<<"Enter the information into the address book!\n";);
AddressbookOutput.write((char *)&AddressbookOutput, sizeof(AddressbookList));
} | https://cboard.cprogramming.com/cplusplus-programming/17058-interested-helping.html | CC-MAIN-2017-51 | refinedweb | 148 | 74.9 |
Skip navigation links
java.lang.Object
oracle.ldap.util.JARReader
public class JARReader
JAR Reader read all the resources in the JAR / ZIP file and can return them as Raw bytes. These Raw bytes could interpreted accordingly. For ex. the Raw bytes could be treated as JAVA byte code, image, or a config file Basically it is upto the user of the API to treat raw bytes as whatever he desires to treat it as.
public JARReader(byte[] jarContents) throws java.io.IOException
java.io.IOException
public JARReader(java.util.zip.ZipInputStream zis) throws java.io.IOException
ZipInputStream
java.io.IOException
public byte[] getResource(java.lang.String name)
resource- name
raw- bytes of the resource. Null if the resource does not exist
Skip navigation links | http://docs.oracle.com/cd/E28280_01/apirefs.1111/e10664/oracle/ldap/util/JARReader.html | CC-MAIN-2014-15 | refinedweb | 125 | 53.37 |
Introduction to the .NET Framework Class Library
The .NET Framework includes classes, interfaces, and value types that expedite and optimize the development process and provide access to system functionality. To facilitate interoperability between languages, the .NET Framework types are CLS-compliant and can therefore be used from any programming language whose compiler conforms to the common language specification (CLS).
The .NET Framework types are the foundation on which .NET applications, components, and controls are built. The .NET Framework includes types that perform the following functions:
- Represent base data types and exceptions.
- Encapsulate data structures.
- Perform I/O.
- Access information about loaded types.
- Invoke .NET Framework security checks.
- Provide data access, rich client-side GUI, and server-controlled, client-side GUI.
The .NET Framework provides a rich set of interfaces, as well as abstract and concrete (non-abstract) classes. You can use the concrete classes as is or, in many cases, derive your own classes from them. To use the functionality of an interface, you can either create a class that implements the interface or derive a class from one of the .NET Framework classes that implements the interface.
Naming Conventions
.NET Framework types use a dot syntax naming scheme that connotes a hierarchy. This technique groups related types into namespaces so they can be searched and referenced more easily. The first part of the full name — up to the rightmost dot — is the namespace name. The last part of the name is the type name. For example, System.Collections.ArrayList represents the ArrayList type, which belongs to the System.Collections namespace. The types in System.Collections can be used to manipulate collections of objects.
This naming scheme makes it easy for library developers extending the .NET Framework to create hierarchical groups of types and name them in a consistent, informative manner. It is expected that library developers will use the following guideline when creating names for their namespaces:
CompanyName.TechnologyName
For example, the namespace Microsoft.Word conforms to this guideline.
The use of naming patterns to group related types into namespaces is a very useful way to build and document class libraries. However, this naming scheme has no effect on visibility, member access, inheritance, security, or binding. A namespace can be partitioned across multiple assemblies and a single assembly can contain types from multiple namespaces. The assembly provides the formal structure for versioning, deployment, security, loading, and visibility in the common language runtime.
For more information on namespaces and type names, see Common Type System.
System Namespace
The System namespace is the root namespace for fundamental types in the .NET Framework. This namespace includes classes that represent the base data types used by all applications: Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, String, and so on. Many of these types correspond to the primitive data types that your programming language uses. When you write code using .NET Framework types, you can use your language's corresponding keyword when a .NET Framework base data type is expected.
The following table lists some of the value types the .NET Framework supplies, briefly describes each type, and indicates the corresponding type in Visual Basic, C#, and the Managed Extensions for C++. The table also includes entries for the Object and String classes, for which many languages have corresponding keywords.
In addition to the base data types, the System namespace contains almost 100 classes, ranging from classes that handle exceptions to classes that deal with core runtime concepts, such as application domains and the garbage collector. The System namespace also contains many second-level namespaces.
For more information about namespaces, browse the .NET Framework Reference. The reference documentation provides a brief overview of each namespace as well as a formal description of each type and its members.
See Also
Common Type System | .NET Framework Reference | Inside the .NET Framework | https://msdn.microsoft.com/en-us/library/hfa3fa08(VS.71).aspx | CC-MAIN-2015-32 | refinedweb | 639 | 50.33 |
{-# LANGUAGE CPP #-} module Control.Concurrent.Spawn ( -- * Spawn spawn -- * Spawn with @'try'@ , Result , spawnTry -- * Higher-level functions , parMapIO , parMapIO_ , (|*|) -- * Limiting concurrency , pool ) where import Control.Concurrent import Control.Exception import Control.Monad -- | Two ways a computation of type @'IO' a@ can end. type Result a = Either SomeException a -- | Spawn a concurrent computation. Produces an action which -- demands a @'Result'@. spawnTry :: IO a -> IO (IO (Result a)) -- We block asynchronous exceptions around 'forkIO', then restore -- the parent thread's exception mask state inside 'try'. This -- prevents an exception from interrupting 'putMVar', which would -- deadlock the parent. -- -- The API for doing this changed in base-4.3 with GHC 7.0. #if MIN_VERSION_base(4,3,0) spawnTry m = do v <- newEmptyMVar _ <- mask $ \restore -> forkIO (try (restore m) >>= putMVar v) return (readMVar v) #else spawnTry m = do v <- newEmptyMVar b <- blocked _ <- block $ forkIO (try (if b then m else unblock m) >>= putMVar v) return (readMVar v) #endif -- | Spawn a concurrent computation. Produces an action which -- demands the result. Any exception from the original computation -- is re-thrown when and where the result is demanded. spawn :: IO a -> IO (IO a) spawn m = do r <- spawnTry m return (r >>= either throwIO return) -- | Given /n/, produces a function to wrap @'IO'@ actions. -- No more than /n/ wrapped actions will be in progress at -- one time. pool :: Int -> IO (IO a -> IO a) pool n = do s <- newQSem n return $ bracket_ (waitQSem s) (signalQSem s) -- | Execute a separate thread of IO for each element of a list, and -- collect results. -- -- The analogy to @parMap@ is misleading. The concurrent execution -- of these actions is non-deterministic and can affect results. -- However, @'parMapIO'@ is expected to be most useful for actions -- which do not interact. parMapIO :: (a -> IO b) -> [a] -> IO [b] parMapIO f xs = mapM (spawn . f) xs >>= sequence -- | Execute a separate thread of IO for each element of a list. -- -- Results are discarded, but the @'parMapIO_'@ action does not -- complete until all threads have finished. parMapIO_ :: (a -> IO b) -> [a] -> IO () parMapIO_ f xs = mapM (spawn . f) xs >>= sequence_ infixl 4 |*| -- | A concurrent version of @'ap'@ or @(\<*\>)@ for @'IO'@. -- -- Spawns a thread for the right-hand action, while executing the -- left-hand action in the current thread. (|*|) :: IO (a -> b) -> IO a -> IO b mf |*| mx = spawn mx >>= (mf `ap`) | http://hackage.haskell.org/package/spawn-0.3/docs/src/Control-Concurrent-Spawn.html | CC-MAIN-2016-36 | refinedweb | 385 | 66.13 |
Type: Posts; User: Imam Gains
Hi,
I'm getting the following error when trying to install a specific plugin in wordpress:
Fatal error: Maximum execution time of 30 seconds exceeded in...
So I can use that notation in any file to call a method from a class that the file has access to?
Hi,
The tutorial I am following used the following code to call a function from another file:
echo File::exists('test.php') ? 'it exists' : 'it does not exist';
what is that notation, I...
Hi,
I had an idea the other day to post an ad on the internet to make free websites and other web apps for people, do you think this is a good approach to get work? I want to build up a portfolio...
I know, exactly!
That was just a typo I made, its not on the file. Like I said before, all the other pages indeed working and they require blog.php so the rpoblem is definately not the blog.php file but the index.php...
Aha, I have moved the index.php file, that is in the admin folder, one directory up, so that now it is in the same directory as blog.php (and renamed it index2.php because there is already an...
Interesting..
Even when I remove the namespace declaration and notations, the other pages continue to work fine except admin/index.php, except this time the fatal error says undefined function...
It's a premium tutorial, but I downloaded the source code, sou you can check it.
blog 1 folder is...
this is driving me nuts, I looked at the source code of the tutorial I'm following, and I have the exact same code!
yh, the db.php file has namespace Blog\DB on the top line before any code.
5.5.9
nah now even the other pages are not working
Hi,
This is driving me crazy! Here is my code:
<?php
require '../blog.php';
view('admin/create');
thanks, that worked.
PHP if fun but frustrating!
Hi,
when I run the following code, it works when I change the id value in the query string that is not in the database table, but it also says:
Notice: Undefined offset: 0 in...
Thank you both for clarifying my confusion.
ok got it, thanks.
My XAMPP installation of MySQL is enough right, I don't need to download another one from mysql.com?
I managed to log in to MySQL from the command line, thanks again.
Hey Guys,
Newbie here (to both the forum and the PHP language).:)
I'm currently learning PHP and I'm using the XAMPP server for my localhost. Anyway, I'm now at the stage of learning about... | http://www.webdeveloper.com/forum/search.php?s=02f70f6a0a76711008ae5a001469e04b&searchid=10025261 | CC-MAIN-2015-27 | refinedweb | 454 | 75.61 |
I am trying to use pytorch with tensorboard and I run the tensorboard server with the following command:
tensorboard --logdir=./runs/
Now I am just simulating some fake data as follows:
import numpy as np import time from torch.utils.tensorboard import SummaryWriter train_writer = SummaryWriter(log_dir="./runs/train/") for i in range(100): v = np.random.randint(10, 100) train_writer.add_scalar("loss", v, i) #time.sleep(1) train_writer.close()
Now if I do not put the sleep method in there, the script finishes and I can see the graph on the tensorboard front end.
I put the
sleep in there so that I could see the data arrive in a streaming fashion and be able to see the board updating. However, if I put the
sleep in there, no graph ever shows up and all I see is the message that there is no data or it could not find any.
I am not sure if this is a tensorboard issue or if I am doing something wrong in using it from within pytorch. | https://discuss.pytorch.org/t/pytorch-and-tensorboard-logging/49729 | CC-MAIN-2019-30 | refinedweb | 174 | 72.26 |
We stayed four nights in a family room with bathroom. I'm not sure if every room has an attached bath, and that would make a difference. The decor was simple but beautiful, and the staff were attentive and courteous. This was at the end of a 7 week vacation, so we were tired, and proximity to the train station was one of the chief reasons I selected this hotel. It turned out to be an excellent location all round. I would happily return (and hope to) and highly recommend this hotel. I've stayed in a bigger four star hotel in Rome, but apart from more varied breakfast offerings, I was just as happy at the Andreina.
Suggestion for improvement? The coffee.
- Reservation Options:
- TripAdvisor is proud to partner with Expedia, Booking.com, Hotels.com, Priceline and Odigeo so you can book your Hotel Andreina reservations with confidence. We help millions of travelers each month to find the perfect hotel for both vacation and business trips, always with the best discounts and special offers.
- Also Known As:
- Andreina Hotel Rome | http://www.tripadvisor.com/ShowUserReviews-g187791-d593243-r145477144-Hotel_Andreina-Rome_Lazio.html | CC-MAIN-2015-11 | refinedweb | 181 | 64.91 |
Coding Dojo December 2014
This dojo will be done a bit differently. The problem will be more practical and unlike a normal dojo we encourage you to keep your solution to project I for project II
You will be paired up to work on the Phase I from 7 to 7:45. We will have a 15 minute group discussion, change partners, and work either on project II or more on project I.
Everyone one is at different level, if you can't figure out something together ask another pair or ask the facilitators. The idea is we will all learn something by the end of the night and learn at our pace.
Setup pip
This dojo will make use of 3rd party libraries which don't come with Python. There is a whole ecosystem of interesting libraries you can make use of and once
pip is setup it isn't too hard to access them.
Setting up
pip is still a bit challenging. If you run into a problem please ask some one to help you. We will present two methods, pip 2014 and the direct way.
pip 2014
You can follow the instructions here if you are using a Mac or Linux
You won't need virtualenv or a C compiler for this dojo, but some libraries do excutable requests ... $ python ... >>> from requests import get >>> response = get('') >>> response <Response [200]>
Project 1: Access Open Data
Programs are great working with data. The Internet is a great source of data to experiment with if you can get it in the right format. Fortunately the open data movement makes it easier.
We will be using the Requests Python library to access a web based open data API from the University of Waterloo.
If you tested
pip in the "Success" section above when you already have it. If not use
pip to install it.
$ pip install --user requests
Once Requests is installed it becomes very easy in Python to get the content of webpages. Web APIs tend to provide data in a format called JSON which is similar to Python dictionaries and list. Requests has an easy way to convert JSON data to Python. Try this example:
$ python >>> from requests import get >>> response = get('') >>> data = response.json() >>> print(data)
Your goal is to write a Python function which you can call to find out if today is a holiday at the University of Waterloo or not. Start by making a file called
holiday.py and copy this into it:
import datetime from requests import get def is_holiday(): # TODO: call the open data api, figure out what today is and check to see if today is a holiday # return True if it is and False if it isn't. pass if __name__ == "__main__": if is_holiday(): print("It is a holiday at UW, no school today!") else: print("Not a holiday today, you have to go to school.")
Dates and Times in Python
Handling time is actually one of the harder problems in programming. Most languages provide built in libraries to help and so does Python, a few actually. We recommend you use the datetime library.
>>> import datetime >>> today = datetime.date.today() >>> today.year
Success
If you have successfully implement your function you should be able to do this:
$ python holiday.py Not a holiday today, you have to go to school.
You will have to wait until the Christmas break to see the other output option :).
Instead of writing the function all at once start by making it always return
True or
False and then get it to print the current date. You can keep running the script to test your progress.
Project 2: Simple Dynamic Website
Using the command line isn't the most intuitive. A more flexible interface is the web, and it pretty easy to write and run website on your own computer which interact with a open data API or even your own laptop.
There are a few different Python web frameworks but the easiest to get started with Flask. Like with Requests you can use
pip to install Flask
$ pip install --user flask
With Flask installed let's create the file
web_interface.py beside
holiday.py can start by copying the example
flask provides:
# web_interface.py from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() lets you know that if you open a browser and put "" into the URL bar you will be take to a webpage generated by this Python script. Try it out!
When you make a change you will want to restart the website, also when you are done you will probably want to stop it. Go into your command line where you see output like this:
$ python web_interface.py * Running on 127.0.0.1 - - [15/Dec/2014 17:12:48] "GET / HTTP/1.1" 200 -
And type
control-c that is hold down the
control key you page you will see that it can't find it.
HTML
The web is built on a markup language called HTML, we won't go into too much detail here, but combining HTML with Python enables you to create dynamic websites. Let's use triple quoted string in Python to output some HTML.
# web_interface.py from flask import Flask app = Flask(__name__) html = ''' <html> <head> <title>My Dynamic Website</title> </head> <body> <h1>{}</h1> </body> </html> ''' @app.route("/") def hello(): return html.format("Hello World!") if __name__ == "__main__": app.run()
Run
web_inteface.py again and checkout the difference.
html holds a string of text which is a template we are using to render our webpage. The
{} placeholder is populated with the value "Hello World!" via the
format function on strings.
Bring it together
Your final task is to take your
is_hoilday function from Project 1 and combine it with your dynamic website. Make a website which will tell you if today is a holiday at the University of Waterloo or not. | http://watpy.ca/learn/intro-projects/Python%20Dojo.md | CC-MAIN-2018-13 | refinedweb | 996 | 73.07 |
Hide Forgot
Description of problem:
Since my last update I have my backup system (to a dvd) broken. No link is created for cdrom and dvd.
This is the update details (result of yum history info 63):
Loaded plugins: langpacks, presto, refresh-packagekit
Transaction ID : 63
Begin time : Tue Mar 27 14:51:24 2012
Begin rpmdb : 1599:eb10d0ff66ebec3e5830f695c242ad13e5295aad
End time : 14:52:39 2012 (75 seconds)
End rpmdb : 1599:5f55d6af9205ff432c6631404531b8c562552608
User : System <unset>
Return-Code : Success
Transaction performed with:
Installed PackageKit-yum-0.6.21-2.fc16.x86_64 @updates
Installed rpm-4.9.1.2-6.fc16.x86_64 @updates
Installed yum-3.4.3-7.fc16.noarch @updates
Installed yum-metadata-parser-1.1.4-5.fc16.x86_64 @koji-override-0/$releasever
Installed yum-presto-0.7.1-1.fc16.noarch @koji-override-0/$releasever
Packages Altered:
Updated audit-2.1.3-4.fc16.x86_64 @?fedora
Update 2.2-1.fc16.x86_64 @updates
Updated audit-libs-2.1.3-4.fc16.x86_64 @?fedora
Update 2.2-1.fc16.x86_64 @updates
Updated audit-libs-python-2.1.3-4.fc16.x86_64 @?fedora
Update 2.2-1.fc16.x86_64 @updates
Updated bash-4.2.20-1.fc16.x86_64 ?
Update 4.2.24-1.fc16.x86_64 @updates
Updated chkconfig-1.3.57-3.fc16.x86_64 ?
Update 1.3.59-1.fc16.x86_64 @updates
Updated cpp-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated cups-1:1.5.2-1.fc16.x86_64 ?
Update 1:1.5.2-6.fc16.x86_64 @updates
Updated cups-libs-1:1.5.2-1.fc16.x86_64 ?
Update 1:1.5.2-6.fc16.x86_64 @updates
Updated curl-7.21.7-6.fc16.x86_64 ?
Update 7.21.7-7.fc16.x86_64 @updates
Updated dash-0.5.6-6.fc16.x86_64 ?
Update 0.5.7-1.fc16.x86_64 @updates
Updated exempi-2.1.1-2.fc15.x86_64 @?fedora
Update 2.2.0-1.fc16.x86_64 @updates
Updated foomatic-filters-4.0.8-4.fc16.x86_64 @?fedora
Update 4.0.8-8.fc16.x86_64 @updates
Updated gcc-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated gcc-c++-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated gcc-gfortran-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated google-chrome-beta-18.0.1025.113-127419.x86_64 ?
Update 18.0.1025.140-128625.x86_64 ?
Updated libcurl-7.21.7-6.fc16.x86_64 ?
Update 7.21.7-7.fc16.x86_64 @updates
Updated libgcc-4.6.2-1.fc16.i686 @?fedora
Updated libgcc-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.i686 @updates
Update 4.6.3-2.fc16.x86_64 @updates
Updated libgfortran-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated libgomp-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated libjpeg-turbo-1.1.1-3.fc16.i686 ?
Updated libjpeg-turbo-1.1.1-3.fc16.x86_64 ?
Update 1.2.0-1.fc16.i686 @updates
Update 1.2.0-1.fc16.x86_64 @updates
Updated libquadmath-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated libquadmath-devel-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.x86_64 @updates
Updated libquvi-scripts-0.4.2-1.fc16.noarch ?
Update 0.4.3-1.fc16.noarch @updates
Updated libssh2-1.2.7-1.fc15.x86_64 @?fedora
Update 1.2.7-4.fc16.x86_64 @updates
Updated libstdc++-4.6.2-1.fc16.i686 @?fedora
Updated libstdc++-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.i686 @updates
Update 4.6.3-2.fc16.x86_64 @updates
Updated libstdc++-devel-4.6.2-1.fc16.i686 @?fedora
Updated libstdc++-devel-4.6.2-1.fc16.x86_64 @?fedora
Update 4.6.3-2.fc16.i686 @updates
Update 4.6.3-2.fc16.x86_64 @updates
Updated libtool-2.4-8.fc16.x86_64 ?
Update 2.4-9.fc16.x86_64 @updates
Updated libtool-ltdl-2.4-8.fc16.i686 ?
Updated libtool-ltdl-2.4-8.fc16.x86_64 ?
Update 2.4-9.fc16.i686 @updates
Update 2.4-9.fc16.x86_64 @updates
Updated libuser-0.57.2-1.fc16.x86_64 @?fedora
Update 0.57.4-1.fc16.x86_64 @updates
Updated libuser-python-0.57.2-1.fc16.x86_64 @?fedora
Update 0.57.4-1.fc16.x86_64 @updates
Updated lohit-assamese-fonts-2.5.0-1.fc16.noarch @?fedora
Update 2.5.1-1.fc16.noarch @updates
Updated lohit-bengali-fonts-2.5.0-1.fc16.noarch @?fedora
Update 2.5.1-1.fc16.noarch @updates
Updated lohit-gujarati-fonts-2.5.0-1.fc16.noarch @?fedora
Update 2.5.1-1.fc16.noarch @updates
Updated lohit-kannada-fonts-2.5.0-1.fc16.noarch @?fedora
Update 2.5.1-1.fc16.noarch @updates
Updated lohit-oriya-fonts-2.5.0-1.fc16.noarch @?fedora
Update 2.5.1-1.fc16.noarch @updates
Updated lohit-punjabi-fonts-2.5.0-2.fc16.noarch ?
Update 2.5.1-1.fc16.noarch @updates
Updated lohit-telugu-fonts-2.4.5-13.fc16.noarch @?fedora
Update 2.5.1-1.fc16.noarch @updates
Updated nfs-utils-1:1.2.5-4.fc16.x86_64 ?
Update 1:1.2.5-5.fc16.x86_64 @updates
Updated psmisc-22.13-8.fc15.x86_64 @?fedora
Update 22.16-1.fc16.x86_64 @updates
Updated quvi-0.4.1-1.fc16.x86_64 ?
Update 0.4.2-1.fc16.x86_64 @updates
Updated selinux-policy-3.10.0-75.fc16.noarch ?
Update 3.10.0-80.fc16.noarch @updates
Updated selinux-policy-targeted-3.10.0-75.fc16.noarch ?
Update 3.10.0-80.fc16.noarch @updates
Updated tzdata-2012b-1.fc16.noarch ?
Update 2012b-3.fc16.noarch @updates
Updated tzdata-java-2012b-1.fc16.noarch ?
Update 2012b-3.fc16.noarch @updates
Updated xorg-x11-server-Xephyr-1.11.4-1.fc16.x86_64 ?
Update 1.11.4-2.fc16.x86_64 @updates
Updated xorg-x11-server-Xorg-1.11.4-1.fc16.x86_64 ?
Update 1.11.4-2.fc16.x86_64 @updates
Updated xorg-x11-server-common-1.11.4-1.fc16.x86_64 ?
Update 1.11.4-2.fc16.x86_64 @updates
Scriptlet output:
1 SELinux: Could not downgrade policy file /etc/selinux/targeted/policy/policy.26, searching for an older version.
2 SELinux: Could not open policy file <= /etc/selinux/targeted/policy/policy.26: No such file or directory
3 load_policy: Can't load policy: No such file or directory
history info
I can see the following in the /var/log/messages (dont know what exactly caused these error messages; all I was dong at this time was eject, eject-t and a mount /dev/dvd):
Mar 29 15:00:25 hostname kernel: [15817.472165] EXT4-fs (sr0): VFS: Can't find ext4 filesystem
Mar 29 15:00:25 hostname kernel: [15817.495814] EXT4-fs (sr0): VFS: Can't find ext4 filesystem
Mar 29 15:00:25 hostname kernel: [15817.519424] EXT4-fs (sr0): VFS: Can't find ext4 filesystem
Mar 29 15:00:25 hostname kernel: [15817.637546] ISOFS: Unable to identify CD-ROM format.
Mar 29 15:00:25 hostname kernel: [15817.711226] FAT-fs (sr0): bogus number of reserved sectors
Mar 29 15:00:25 hostname kernel: [15817.711233] FAT-fs (sr0): Can't find a valid FAT filesystem
Mar 29 15:00:25 hostname kernel: [15817.757931] hfs: can't find a HFS filesystem on dev sr0.
Mar 29 15:00:25 hostname kernel: [15817.812323] hfs: unable to find HFS+ superblock
This was working until the last update on 27th Mar.
This is the result of uname -a
Linux hostname 3.3.0-4.fc16.x86_64 #1 SMP Tue Mar 20 18:05:40 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
Have not noticed (yet) any other issues after this update.
Please let me know if you need more information in this regard.
Thanks
Not sure whether I have explained it correctly in my original request. Some more here.
After the above said update there are no links /dev/cdrom /dev/dvd pointing to /dev/sr0 anymore.
When I issue eject (just eject from the command line) I get an error
eject: unable to find or open device for: `cdrom'
(as there is no cdrom link); but if I issue /dev/sr0 it works.
There are links /dev/dvd2 and /dev/dvdrw2 pointing to /dev/sr0.
The nautilus file manager mounts without any problem when a dvd is inserted.
What is the standard way to mount cd/dvd/bd in Fedora(in my case F16 64 bit) with Gnome (in my case Gnome 3)? Should I change my script always to use /dev/sr0 instead of /dev/dvd (or /dev/cdrom)? Will /dev/sr0 not change?
After all there was no problem until the above said software update. But I also can agree that it may be something different from the software update.
Thanks
Please try the procedure detailed in bug #747114 comment #7.
*** This bug has been marked as a duplicate of bug 747114 ***
This seems to be different than the original cause of bug #747114 as it pre-dates the cups "PrivateTmp" change. Marking this as not a duplicate.
*** Bug 806909 has been marked as a duplicate of this bug. ***
*** Bug 808121 has been marked as a duplicate of this bug. ***
Well, now there is a development in this issue; actually more trouble. After a write operation to the disc, I keep seeing the following in the /var/log/messages:
Apr 2 09:30:29 hostname kernel: [340798.622317] VFS: busy inodes on changed media or resized disk sr0
Apr 2 09:30:32 hostname kernel: [340801.845138] VFS: busy inodes on changed media or resized disk sr0
Apr 2 09:31:52 hostname kernel: [340881.552248] VFS: busy inodes on changed media or resized disk sr0
and if I try to write to another disc with growisofs I see the following error:
:-( unable to O_EXCL /dev/sr0: someone was in time to remount?
To get the disc writing (at least once) I have to reboot the machine (I dont know which service that I should restart - I just reboot the machine).
Is this related to the original issue?
Cheers
What does 'rpm -q cups' say?
cups-1.5.2-6.fc16.x86_64
Could you please try with the test update cups-1.5.2-8.1.fc16? See bug #807672 comment #12.
I have installed the package. It did not fix the problem Tim.
Thanks. (Did you try rebooting? Expect so...)
Now could you please try downgrading CUPS to this version?: 1.5.2-1.fc16
Packages are here:
Just download the relevant packages for your architecture and then run:
yum downgrade ./cups-*1.5.2-1.fc16.*.rpm
After rebooting, does the problem persist?
Hi Tim,
The commands
yum downgrade ./cups-*1.5.2-1.fc16.*.rpm
yum downgrade cups-*1.5.2-1.fc16.*.rpm
failed with
Loaded plugins: langpacks, presto, refresh-packagekit
No package ./cups-*1.5.2-1.fc16.*.rpm available.
Error: Nothing to do
Any other suggestions?
Thanks
'yum downgrade cups*.rpm' works for me
guna_pmk: you downloaded the packages?
My apologies Tim. I tried it before finishing the work and completely missed your download instructions. I have downloaded and downgraded cups successfully and tried again; the problem seems to be there still.
I think I have mentioned all the following previously; just to recap:
1. After a reboot, a dvd write works without a problem
2. Once a dvd is written ( I use growisofs for writing), the next one fails most of the time. It works sometime. But it is very inconsistent. All the times it fails to write, there is these lines in the /var/log/messages
VFS: busy inodes on changed media or resized disk sr0
3. All this happens since my software update on 2012-03-29.
4. Since the a software update, I also have no links (/dev/dvd, /dev/dvdrw or /dev/cdrom) created pointing to /dev/sr0 (or whatever the dvd device is); but there are /dev/dvd2, /dev/dvdrw2, /dev/cdrom2 and /dev/cdrw2 links pointing to /dev/sr0.
Additionally, following is the contents of my /etc/udev/rules.d/70-persistent-cd.rules:
=====================================================================================================================
# This file was automatically generated by the /lib/udev/write_cd_rules
# program, run by the cd-aliases-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and set the $GENERATED variable.
# ATAPI_iHBS212_2 "
# CD-ROM (pci-0000:00:1d.0-usb-0:1.6:1.0-scsi-0:0:0:1)
SUBSYSTEM=="block", ENV{ID_CDROM}=="?*", ENV{ID_SERIAL}=="SEMC_CD-ROM_42583930324251573159-0:1", SYMLINK+="cdrom1", ENV{GENERATED}="1"
# ATAPI_iHBS212_2 (pci-0000:00:1f.2-scsi-0:0:0:0)
SUBSYSTEM=="block", ENV{ID_CDROM}=="?*", ENV{ID_PATH}=="pci-0000:00:1f.2-scsi-0:0:0:0", SYMLINK+="cdrom2", ENV{GENERATED}="1"
SUBSYSTEM=="block", ENV{ID_CDROM}=="?*", ENV{ID_PATH}=="pci-0000:00:1f.2-scsi-0:0:0:0", SYMLINK+="cdrw2", ENV{GENERATED}="1"
SUBSYSTEM=="block", ENV{ID_CDROM}=="?*", ENV{ID_PATH}=="pci-0000:00:1f.2-scsi-0:0:0:0", SYMLINK+="dvd2", ENV{GENERATED}="1"
SUBSYSTEM=="block", ENV{ID_CDROM}=="?*", ENV{ID_PATH}=="pci-0000:00:1f.2-scsi-0:0:0:0", SYMLINK+="dvdrw2", ENV{GENERATED}="1"
=====================================================================================================================
Does the above ring any bell?
Please let me know if you need more information in this regard.
Thanks
Hi Tim,
More problems here. Not sure whether the latest downgrade caused the problem. But I have not encountered this problem earlier. I have a UDF image file which I mount to store and remove files.
Now even after umounting, the loop device is not detached. But if I stop cups, the loop device is detached. But the previously stuck devices can not be retrieved. This is exactly the same as issue #758159.
I mount the image as follows:
mount -o loop /path/to/image.iso /mnt/image
to unmount:
umount /mnt/image
Cheers
Your most recent comment refers to bug #758159, which is an unresolved kernel bug. However, in comment #15 you referred to a problem (after writing a DVD) which goes away when cups is not running.
When you tried cups-1.5.2-8.1.fc16, did you reboot before trying the DVD? Please humour me, and try again: the 1.5.2-8.1 package is now a stable update and should be available either now or in the next couple of days.
Once you have cups-1.5.2-8.1.fc16 installed, reboot the machine and try your test again.
If you are still seeing "busy inodes" messages, could you please run "mount" to see if the disc is mounted? If so, could you please run "fuser -mv /mnt/..." on the mount-point and find out which processes are keeping the file system mounted?
Hi Tim,
Sorry for the delay. I was away for some time.
To answer your questions,
"However, in comment #15 you referred to a problem (after writing a DVD)
which goes away when cups is not running." - I could not see any mention about cups in comment #15 Tim. I don't get the point here.
"When you tried cups-1.5.2-8.1.fc16, did you reboot before trying the DVD? " - Yes I did Tim.
I now have the latest cups (I have performed a complete system update). My new kernel is 3.3.1-5.fc16.x86_64. But it is still incosistent.
"If you are still seeing "busy inodes" messages, could you please run "mount" to
see if the disc is mounted? If so, could you please run "fuser -mv /mnt/..."
on the mount-point and find out which processes are keeping the file system
mounted?" - That was the first thing I did when I saw the error messages. I even tried
ls -l /proc/*/cwd | grep -i "cd\|dvd\|sr?"
The dvd device was not in use by any process.
Besides, testing this issue takes all my time; all I do now is reboot the machine once the disc is written. It is very disappointing :(.
We also have not found out the issue with the udev rules :(.
Cheers
OK. Sorry, I must have mis-read the comment.
So I don't think cups is related to this problem any more.
Changing component to kernel.
I also upgraded a kernel and suddenly /dev/dvd disappeared but /dev/dvd2 pointed to sr0. Looks something caused a different scsi address to be used for the same hardware...
< # ATAPI_iHBS212_2 (pci-0000:00:1f.2-scsi-1:0:0:0)
> # ATAPI_iHBS212_2 (pci-0000:00:1f.2-scsi-0:0:0:0)
< # HL-DT-STDVD+-RW_GSA-H31N (pci-0000:00:1f.2-scsi-4:0:0:0)
> # HL-DT-STDVD+-RW_GSA-H31N (pci-0000:00:1f.2-scsi-0:0:0:0)
I removed both sets of rules from /etc/udev/70-persistent-cd.rules and ran:
service udev restart
Now 70-persistent-cd.rules has just one set of rules for the DVD drive and /dev/dvd is).
Isn't this the systemd namespace issue?. | https://bugzilla.redhat.com/show_bug.cgi?id=808109 | CC-MAIN-2019-26 | refinedweb | 2,863 | 62.85 |
NDepends: How you look at code
A tool for code analysis looks at .NET assemblies of an application and generates reports containing design quality metrics, warnings and diagrams.
NDepend:
Continue Reading This Article
Enjoy this article as well as all of our content, including E-Guides, news, tips and more.
By submitting you agree to receive email communications from TechTarget and its partners. Privacy Policy Terms of Use.
- FxCop rules are rigid and are mostly .NET issues-oriented while NDepend rules are customizable (thanks to a dedicated language named CQL) and are mostly design/architecture/code structure-oriented.
- NDepend handles code metric and FxCop doesn't.
Compared to other .NET code metric and static code analyzers, here are the main differences:
- NDepend 2.0 is shipped with an interactive UI (VisualNDepend.exe) which allows you to browse metrics in a unique way thanks to a treemap view.
- NDepend provides a very complete set of type metrics. The list of type metrics is available here and includes Lack of Cohesion Of Methods (LCOM), Cyclomatic Complexity (CC), Size of instance, Afferent Coupling (Ca), Efferent Coupling (Ce), Association Between Class (ABC), Number of Children (NOC), Depth of Inheritance Tree (DIT), Response For a Type (RFT). Trivial metrics such as #IL instructions, #local variables or #parameters are also handled.
- NDepend is the only .NET tool which yields components metrics as defined by Robert C. Martin in his book Agile Software Development: Principles, Patterns, and Practices (Prentice Hall, 2002).
- NDepend yields diagrams about assemblies dependencies, assemblies abstractness vs. instability and treemap view.
- NDepend analyzes assemblies and IL code. Clearly the main drawback is that code source comments are not taken into account; rather, this approach allows NDepend to analyze any .NET application independently from the language in which it is written -- C#, VB.NET, etc.
The support for CQL (Code Query Language) is indeed the main enhancement to the tool. While creating CQL, I wanted a means to express all sorts of design intentions such as the following:
- My business/domain classes shouldn't depend on anything.
- Instances of this particular class shouldn't be created out of this dedicated factory.
- This namespace shouldn't be used by any other namespace than N1, N2 and N3.:
WARN IF Count > 0 IN SELECT TYPES OUT OF NAMESPACES "System.Xml" WHERE DepthOfIsUsing "System.Xml.XmlChildNodes" == 1 // Restrict the possibility to create instances of "System.Xml.XmlLoader" only to certain namespaces.
WARN IF Count > 0 IN SELECT ASSEMBLIES WHERE !NameIs "System.Web" AND DepthOfIsUsing "System.Web.Services" == 1 // Assert that the assembly System.Web.Services will never be referenced by another assembly than System.Web.
WARN IF Count > 0 IN SELECT METHODS OUT OF TYPES "System.Xml.XmlNamedNodeMap", "System.Xml.XmlAttributeCollection" WHERE DepthOfIsCalling "System.Xml.XmlNamedNodeMap.InsertNodeAt(Int32,XmlNode)" == 1 // Restrict the possibility to call the method InsertNodeAt() only to certain types.
I figured out that this approach is also a good means to write metrics thresholds or naming rules such as the following:
WARN IF Count > 0 IN SELECT METHODS WHERE NbILinstructions > 200 ORDER BY NbILinstructions// Methods where NbILInstructions > 200 are extremely complex and should be split in smaller methods.
WARN IF Count > 0 IN SELECT FIELDS WHERE NameLike "^m_" AND IsStatic // A static field should be named 'm_XXX'.).
Numerous minor enhancements are also available. For example the NDepend.Project.exe tool allows editing NDepend projects instead of previous handcrafted XML configuration files. The report layout is now configurable. You can keep historics of NDepend reports.). | http://searchwindevelopment.techtarget.com/tip/NDepends-How-you-look-at-code | CC-MAIN-2014-35 | refinedweb | 579 | 50.73 |
Using DRY: Between Code Duplication and High-Coupling
- |
-
-
-
-
-
-
-
Read later
My Reading List
DRY reduces duplication and the maintenance problems coming with it, but misusing it leads to high coupling and reduced readability. The lesson: a software development principle should be applied considering other corresponding principles, patterns and practices.
DRY stands for Don’t Repeat Yourself, and it is a software development principle first mentioned by Andy Hunt and Dave Thomas in their book The Pragmatic Programmer: From Journeyman to Master. The principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
In this context, Hunt emphasized the negative impact of duplication and consequently the importance of using DRY, on Portland Pattern Repository's Wiki:
Duplication (inadvertent or purposeful duplication) can lead to maintenance nightmares, poor factoring, and logical contradictions.
Duplication, and the strong possibility of eventual contradiction, can arise anywhere: in architecture, requirements, code, or documentation. The effects can range from mis-implemented code and developer confusion to complete system failure.
One could argue that most of the difficulty in Y2K remediation is due to the lack of a single date abstraction within any given system; the knowledge of dates and date-handling is widely spread.
Although DRY seems like a must-apply principle of software engineering, Anders Munch noted that there are exceptions:
There is a pattern to the exceptions to the principle. It is ok to have more than one representation of a piece of knowledge provided an effective mechanism for ensuring consistency between them is engaged.
- Definitions and declarations of C functions: these are usually in sync because the compiler flags inconsistencies, forcing the programmer to take action.
- Unit tests: inconsistency means the tests will fail, again forcing someone to take action.
- Auto-generated stuff: periodic regeneration ensures consistency.
These exceptions actually enforce the rationale behind DRY. But a question arises: aren’t programmers taking DRY to extremes? Isn’t DRY misunderstood and misused sometimes?
Dave Thomas remarked early on that “Most people take DRY to mean you shouldn't duplicate code. That's not its intention. The idea behind DRY is far grander than that,” expanding the DRY principle to an entire software system:).
While the issues of using DRY seemed to be settled long time ago, the principle has been mentioned again at QCon London 2012 by several speakers, including Greg Young and Dan North, who drew attention to its possible misuse. InfoQ followed the trail to find out more details on DRY. When InfoQ asked what problems he sees with DRY, Young said:
The basic argument against following DRY is that there is another side of things. When following "DRY", it is quite common that people start building coupling and complexity into their software. One side of the trade off is very easy to measure (number of face plants per hour when needing to fix bugs multiple places) while the other is rather difficult (coupling and complexity built into software in the name of DRY).
One can argue that if DRY is followed "properly" that there will never be coupling and complexity built into the software. This is even anecdotally visible, I can write you a code base that perfectly follows DRY while not introducing coupling and complexity. This however assumes that I have perfect knowledge.
We also talked to David Chelimsky, author and lead developer of RSpec. He said he has seen DRY been taken “to the line level, and it's not always appropriate there (though it can be sometimes).” He provided the following example:
describe "Person#full_name" do
it "concats the first and last names" do
first_name = "John"
last_name = "Doe"
person = Person.new(:first_name => first_name, :last_name => last_name)
person.full_name.should eq "#{first_name} #{last_name}"
end
end
Although this piece of code avoids duplication and might seem as a good implementation of DRY, Chelimsky said he prefers the following more readable piece of code:
describe "Person#full_name" do
it "concats the first and last names" do
person = Person.new(:first_name => "John", :last_name => "Doe")
person.full_name.should eq "John Doe"
end
end
adding:
To a person who doesn't really understand DRY, but thinks it's the bees knees, seeing "John" and "Doe" twice each in that example is like nails on chalkboard. For me, it's quite the opposite. I find it easier to see the relationship between the first and last names, and the outcome of full_name.
Chelimsky also pointed to another piece of code from the Objectify framework he recently stumbled upon. The following code marked with italics
def request_resolver
klass = Objectify::NamedValueResolverLocator
@request_resolver ||= klass.new.tap do |resolver|
resolver.add(:controller, self)
resolver.add(:params, params)
resolver.add(:session, session)
resolver.add(:cookies, cookies)
resolver.add(:request, request)
resolver.add(:response, response)
resolver.add(:flash, flash)
resolver.add(:renderer, Renderer.new(self))
end
end
was replaced with this:
{:controller => self, :params => params, :session => session, :cookies => cookies, :request => request,
:response => response, :flash => flash, :renderer => Renderer.new(self) }.each do |key, value| resolver.add(key, value)
end
Chelimsky commented on this change: “This is taking DRY too far IMO. This part is more maintainable (easier to read and modify) before this change.”
One of the main problems seen by Chelimsky is that “The words "Don't Repeat Yourself" are intended to be a memory device, but "DRY" has become a memory device for "Don't Repeat Yourself" and that ends up being _the principle_ in many minds,” noting that this approach may lead to another side of the problem: “when we reduce duplication, we increase coupling”:
When two methods on the same object do some of the same work, we typically extract a third method to which they both delegate. Both of the original methods are coupled to the extracted method and, indirectly, to each other. This seems perfectly logical and harmless in the context of a single object, but how about when we recognize similar behavior across two objects? To reduce that duplication we need to either introduce a new object they both depend on or, far worse and sadly too often, we have one object depend on the other. The latter approach often leads to dependencies between objects that are unrelated, reducing their ability to evolve over time. Introducing a new object increases the overall surface of the system, and requires thought and care that it doesn't always receive when introduced when refactoring.
In order to avoid taking DRY to extremes, Chelimsky proposes balancing it with other development principles:
DRY is important, but so are Uncle Bob's SOLID principles, for example, or broader concepts like low coupling and high cohesion. It's not good enough to simply apply one principle all the time - you have to take them all into account and weigh their relative value in each situation. It's sort of like knowing which seasoning to put on fish, and which to put on a steak. Some do really well in both cases, some not so much.
DRY is an important principle, but abusing it can generate problems such as increased coupling and reduced readability. The lesson here is that no matter how great a principle is, it should not be used disregarding other good programming practices.
Rate this Article
- Editor Review
- Chief Editor Action
Hello stranger!You need to Register an InfoQ account or Login or login to post comments. But there's so much more behind being registered.
Get the most out of the InfoQ experience.
Tell us what you think
"balancing" DRY?
by
Ilja Preuß
I also don't see how SOLID enters the picture. As far as I can tell, the SRP works very strongly in favor of DRY, whereas I don't see how any of the other four principles would balance it.
Re: "balancing" DRY?
by
David Chelimsky
"Overdoing DRY", IMO, is when it gets taken to the line level as in the examples Abel quoted from me above. Those examples are really about reducing the number of characters in a file, not reducing duplicated functionality.
When you're talking about functionality, yes, in most cases it is about finding the right abstractions. An example of a bad coupling is when A and B do some of the same work, and rather than extracting a C they can share, a dependency is imposed directly between A and B. This violates the Dependency Inversion principle and probably Open/Closed as well (the D and O in SOLID). Bob Martin demonstrates a case like this in where the code is the same in two places but its intent is different.
Hope that helps to clarify.
Re:
by
Sam Newman
Misunderstanding language powerful
by
Henrique de Miranda Gontijo
i.e.
What could be used in a situation like
map.each do |key, value| <do something> end
"Misused" in that way:
{:controller => self, :params => params, :session => session, :cookies => cookies, :request => request,
:response => response, :flash => flash, :renderer => Renderer.new(self) }.each do |key, value| resolver.add(key, value)
end
Cheers,
- Henrique</do>
Re:
by
Norbert Winklareth | https://www.infoq.com/news/2012/05/DRY-code-duplication-coupling/ | CC-MAIN-2016-30 | refinedweb | 1,498 | 53.81 |
Can't create chart with range containing Excel Formula
I am trying to chart a range that contains Excel Calculations. When I add_serie to the chart the series fails with the following exception: {{{
!python
from openpyxl.workbook import Workbook from openpyxl.chart import ScatterChart, Serie, Reference import random
def test_scatterchart_formula(): """This code demonstrates a bug in the chart code when one of the ranges contains an Excel Formula""" wb = Workbook() ws = wb.get_active_sheet() ws.title = u'scatterdata'
ws.cell(row=0, column=1).value = 'Scatter 1' ws.cell(row=0, column=2).value = 'Scatter 2' for i in range(1,12): ws.cell(row=i, column=0).value = (i-1) / 10. ws.cell(row=i, column=1).value = random.random() ws.cell(row=i, column=2).value = '=A%u+B%u' % (i+1,i+1) xyserie1 = Serie( Reference(ws, (1,1), (11,1)), xvalues=Reference(ws, (1,0), (11,0)), legend=Reference(ws, (0,1))) xyserie2 = Serie( Reference(ws, (1,2), (11,2)), xvalues=Reference(ws, (1,0), (11,0)), legend=Reference(ws, (0,2))) scatterchart = ScatterChart() scatterchart.add_serie(xyserie1) scatterchart.add_serie(xyserie2) scatterchart.x_axis.min = 0 scatterchart.x_axis.max = 1 scatterchart.x_axis.unit = 0.2 scatterchart.y_axis.min = 0 scatterchart.y_axis.max = 1 scatterchart.y_axis.unit = 0.2 # chart container dimensions in pixels scatterchart.drawing.left = 200 scatterchart.drawing.top = 20 scatterchart.drawing.height = 200 scatterchart.drawing.width = 500 # chart area in percentage of the container scatterchart.width = .7 scatterchart.height = .7 scatterchart.margin_top = .2 ws.add_chart(scatterchart) wb.save(r'chart.xlsx')
Traceback (most recent call last): File "./chart_bug.py", line 57, in ? test_scatterchart_formula() File "./chart_bug.py", line 30, in test_scatterchart_formula scatterchart.add_serie(xyserie2) File "//openpyxl/openpyxl/chart.py", line 217, in add_serie self._compute_min_max() File "/openpyxl/openpyxl/chart.py", line 259, in _compute_min_max maxi = math.ceil(maxi * 1.1) TypeError: can't multiply sequence by non-int }}}
The issues is that the cell does not have an actual value until it is opened in Excel (or other spreadsheet). I am not sure if the max/min calculation is vital when the sheet is written or not.
I have found a solution to this problem. The code needs to write a dummy value into the c value in the xml. The value must also be referenced as a numref in the xml document. When the sheet is opened and all the calculations are updated the dummy values will be overwritten with the correct values. The changes to the code are minor. I will create a test and check the code in once I completely tested it on my local cases.
Any update to this?
I'd be happy to accept a pull request for this.
Any update on this?
@Camilla Karud yes, I'm hoping to have this in 2.2. The current 2.2 branch no longer bothers to write out any values so it's no longer essential for the series to have them. Unfortunately, however, there's still quite a bit of code that assumes that there are cell values.
Thank you for the quick reply. Do you have an ETA of when 2.2 might be released or a beta version I could test?
You can check out the 2.2 branch at any time. You'll probably need to patch it but I'll look upon a pull request favourably.
As we no longer write cached values for formula we don't need to enforce logic that depends upon it. More work needed to avoid trying to calclulate any values for the chart based on series. This should be entirely the responsibility of client code. Resolves
#103
→ <<cset 9075e110ea0e>>
This is fixed in 2.2. FWIW the chart API has changed slightly since the issue was filed. The following code now works.
Removing version: NEXT (automated comment) | https://bitbucket.org/openpyxl/openpyxl/issues/103 | CC-MAIN-2018-30 | refinedweb | 634 | 53.47 |
Debugging a Revit Add-In
I often hear the question how to unload a Revit add-in. Unfortunately, this is not possible, due to the fundamental .NET framework mechanisms used to load and manage the plug-ins. Revit manages one AppDomain which is used to load all add-in classes.
It would theoretically be possible to unload the entire AppDomain to remove the loaded add-ins. I once tried to implement a system to unload a Revit plug-in by implementing a cascaded pair of IExternalCommand classes. In the first one A, which I registered as an external command in Revit.ini, I set up my own AppDomain, into which I loaded the second class B. When invoking the command implemented by A, I was able to trap the arguments passed in to A.Execute() and invoke and pass them on to B.Execute() without problems. I was also able to delete the AppDomain I had created, thus removing B from the system memory. Unfortunately, something in the .NET framework was still keeping the secondary assembly DLL file locked, so I was unable to overwrite or delete it.
But what I really want to point out here is that there is normally no need to unload Revit add-ins for debugging purposes, because running Revit from the debugger, opening a ready-prepared test model and loading and executing the add-in can be achieved using just a handful of keystrokes and in a matter of a very few seconds. Let us go through the steps for setting up such a system one by one.
For completeness sake, and to ensure that we are really all on the same page, I suggest we start from scratch with a brand new Revit add-in project. That means that we will be going through the same steps as those described in the DevTV presentation and webcast recording mentioned in the getting started post. Here is the short version of the description to set up a new Revit add-in:
- Start Visual Studio 2005.
- Create a new VB or CS .NET project: File > New > Project... > Visual Basic or Visual C# > Class Library.
- Specify the project name and location, for instance DebugTest and C:\tmp\revit.
- This generates a complete skeleton application.
- Rename the class from Class1 to Command, simply to follow a common Revit add-in practice. I do this by clicking on the file name in the solution explorer and renaming that. It automatically renames the class contained in it as well.
From here on, there are some small differences between C# and VB. For C#, we can proceed as follows:
- Remove the unneeded references to System.Data and System.Xml.
- Add a reference to RevitAPI.dll by right clicking on the project references in the solution explorer and selecting Add Reference.
- Do not forget to set the 'Copy Local' flag to False. You do so by opening the properties of RevitAPI.dll. See The SDK Samples Solution for a more detailed explanation of this step.
- Remove the unneeded using statements for System.Collections.Generic and System.Text in the command class source file.
- Add a line at the top saying 'using Autodesk.Revit;'. Note that Intellisense jumps in as soon as you have typed 'Autodesk.', so you almost never need to fully type out any identifier.
- Specify the IExternalCommand parent class for Command by adding ": IExternalCommand" after "public class Command". Note here as well that Intellisense saves you from typing anything but the first few characters of the class name.
- Implement the Execute() method by right clicking on IExternalCommand in the source code and selecting Implement Interface > Implement Interface. This generates the source code for Execute(), which I generally reformat a little to make it more readable.
- Replace the automatically generated exception throwing code by a valid return value, e.g. "return IExternalCommand.Result.Succeeded;"
The completed C# code might look like this:
using System; using Autodesk.Revit; namespace DebugTest { public class Command : IExternalCommand { public IExternalCommand.Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { return IExternalCommand.Result.Succeeded; } } }
For VB, the equivalent steps are:
- Add a reference to RevitAPI.dll by opening the project, selecting the References tab, and clicking Add...
- Do not forget to set the 'Copy Local' flag to False. You do so by opening the properties of RevitAPI.dll. See The SDK Samples Solution for a more detailed explanation of this step.
- Remove the unneeded references to System.Data and System.Xml.
- Add a line at the top saying 'Imports Autodesk.Revit'. Note that Intellisense jumps in as soon as you have typed 'Autodesk.', so you almost never need to fully type out any identifier.
- Specify the IExternalCommand parent class for Command by adding a new line saying "Implements IExternalCommand" after "Public Class Command". Note here as well that Intellisense saves you from typing anything but the first few characters of the class name.
- Implement the Execute() method. In VB, you do not have the 'Implement Interface' option provided for C#, but you can go to the definition of IExternalCommand and copy the code from there.
The completed VB code might look like this:
Imports Autodesk.Revit Public Class Command Implements IExternalCommand Function Execute( _ ByVal commandData As ExternalCommandData, _ ByRef message As String, _ ByVal elements As ElementSet) _ As Autodesk.Revit.IExternalCommand.Result _ Implements Autodesk.Revit.IExternalCommand.Execute Return IExternalCommand.Result.Succeeded End Function End Class
Both the C# and VB projects now compile and are ready to be loaded into Revit.
Remember that the goal of this exercise is to explain how to set up the debugger and a Revit project to be able to very efficiently run, test and debug the code, make changes to and recompile the source code, and restart Revit to get back to the same testing scenario again with a minimum of fuss.
As we already know, in order to load an add-in into Revit, we need to make it known to Revit first via an entry into Revit.ini, which is located in the same directory as Revit.exe. I add the following lines to Revit.ini:
[ExternalCommands] ECCount=1 ECName1=Debug Test ECDescription1=Sample add-in for Revit API blog ECAssembly1=C:\tmp\revit\DebugTest\DebugTest\bin\Debug\DebugTest.dll ECClassName1=DebugTest.Command
When finished editing Revit.ini, make sure to copy the entire file path to the clipboard by right clicking on the Revit.ini file tab in the Visual Studio editor. The reason is that this almost exactly provides the full path name that we require to specify Revit.exe as the debugging process in the next step.
Now we can set up Revit.exe as the debugging application. In C#, this is done by right clicking on the project in the solution explorer and selecting Properties in the context menu. In VB, we simply double click My Project. Select the Debug tab, select the radio button Start external program, and add the full path of Revit.exe. Since we already have the full path of Revit.ini in the clipboard, all we need to do is paste it in and change the three last characters to replace the file extension ini by exe.
Now we can start up Revit.exe simply by hitting the F5 key, or selecting the Visual Studio menu entry Debug > Start Debugging.
If you do not automatically pre-load a Revit model through the command line arguments, you will have to manually select a project before you can load and start testing, so obviously it is better to specify a start-up model. Once a model has been loaded and the full Revit menu is displayed, you can load the add-in.
Note that if you make sure that your current project appears first in the Revit Tools > External Tools menu, you can run it with a minimum of keystrokes by simply typing Alt + T, <Return>, <Return>.
Once you have tested your current issue and wish to recompile the updated code, the fastest way to exit Revit and get back to the compilation environment is to simply stop the debugger using the Visual Studio menu entry Debug > Stop Debugging or Shift + F5.
Finally, to pre-load a specific model when starting up Revit in the Visual Studio debugger, simply add the full path to the Revit RVT file in the Debug tab Start options, Command line arguments.
Once all of this is set up, and believe me it is faster to set up than to explain, you should be able to jump in and out of your full debugging and testing scenario within a matter of seconds.
Hi, do you have the steps to set debugging up in Visual Basic 2008 Express? it does not have the "Start External Command" radio button
Posted by: krispy | September 25, 2008 at 21:09
Hi,
This post from our sister blog on AutoCAD.NET by Kean Walmsley should help answer your question:
Best regards,
Jeremy
Posted by: Jeremy | September 26, 2008 at 01:10
Hi,
I am not able to run the Revit exe from DOTNET in my machine.
ProcessStartInfo info = new ProcessStartInfo(VALUE_REVIT_EXE, outputFile);
info.RedirectStandardInput = false;
info.RedirectStandardOutput = false;
info.UseShellExecute = false;
Process.Start(info);
Clicking on Revit exe in Program Files/Revit even does not work.
The only way I find it running is by starting a new Task in the Task manager.
Can you help on this.
Posted by: Seshan | April 02, 2009 at 09:38
Dear Seshan,
I tested the following little console application, and it worked fine:
class Program
{
static void Main( string[] args )
{
System.Diagnostics.Process.Start( "C:/tmp/wall.rvt" );
}
}
It also worked fine when I replaced the project file "C:/tmp/wall.rvt" by the application executable "C:/Program Files/Revit Architecture 2009/Program/Revit.exe".
I don't see how I can help you with this. Maybe you need to reinstall Revit, or Windows, or reformat your disk :-)
Cheers, Jeremy.
Posted by: Jeremy Tammik | April 02, 2009 at 10:15 | http://thebuildingcoder.typepad.com/blog/2008/09/debugging-a-rev.html | crawl-002 | refinedweb | 1,668 | 56.86 |
I may just be googling wrong, but I cannot find out a way (read function) to change properties of camera in the new Open CV. I need to disable auto exposure and auto gain of the camera.
Is that even possible?
This is an old question but I want to add a solution to this.
opencv calls underlying v4l methods to query frames, set/get camera properties etc. And the problem is, the calls are not complete. Also for some reason, the library calls v4l methods instead of v4l2 ones. Similar issue here. It is solved through modifying opencv code, it seems.
I also checked if opencv can set a property supported in v4l2 -like "manual exposure", "or exposure auto priority". It couldn't. I played around v4l2 to solve this:
#include <libv4l2.h> #include <linux/videodev2.h> #include <sys/ioctl.h> #include <fcntl.h> // open capture int descriptor = v4l2_open("/dev/video0", O_RDWR); // manual exposure control v4l2_control c; c.id = V4L2_CID_EXPOSURE_AUTO; c.value = V4L2_EXPOSURE_MANUAL; if(v4l2_ioctl(descriptor, VIDIOC_S_CTRL, &c) == 0) cout << "success"; // auto priority control c.id = V4L2_CID_EXPOSURE_AUTO_PRIORITY; c.value = 0; if(v4l2_ioctl(descriptor, VIDIOC_S_CTRL, &c) == 0) cout << "success";
You can then work with opencv.
Full list of camera controls are here. | https://codedump.io/share/IXF58itOsOB1/1/configuring-camera-properties-in-new-ocv-243 | CC-MAIN-2021-25 | refinedweb | 202 | 62.14 |
Long time C++ Qt user tries out QML
I have been using Qt for the past few years to create UIs for various C++ applications but I haven't tried Qt Quick and QML until now. So the thing I found really interesting about Qt Quick was that it lets you specify a UI in a declarative way (instead of imperative, as in C++) One of the things which I was wondering was if you could also specify the way graphics are drawn in a declarative way or weather it was just for the layout of ui widgets (as in the XML files produced by the Qt Designer in Qt 4.x).
After playing with it for a while I ended up with a simple QML file which draws the Koch Kurve using the HTML5 canvas.
@/**
- Koch Curve
- F -> F + F - F - F + F
- F means draw a straight line, + means turn left Pi/2 and - means turn
- right Pi/2.
- See wikipedia for more.
- by NilsB
*/
import QtQuick 2.4
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.0
Rectangle {
width: 400 height: 600 Column { Canvas { id: canvas // NOTE If I make the height and width dependent on the parent, // then it somehow ends in an infinite loop, why? width: 400 height: 500 antialiasing: true property int l: 2 property int nRecursions: 1 function turnLeft(ctx) { ctx.rotate(-Math.PI/2); } function turnRight(ctx) { ctx.rotate(Math.PI/2); } function drawLine(ctx) { ctx.lineTo(l, 0); ctx.translate(l, 0); } function drawBasicShape(ctx) { drawLine(ctx); turnLeft(ctx); drawLine(ctx); turnRight(ctx); drawLine(ctx); turnRight(ctx); drawLine(ctx); turnLeft(ctx); drawLine(ctx); } function rKoch(ctx, n) { if (n === 1) { drawBasicShape(ctx); return; } var m = n - 1; rKoch(ctx, m); turnLeft(ctx); rKoch(ctx, m); turnRight(ctx); rKoch(ctx, m); turnRight(ctx); rKoch(ctx, m); turnLeft(ctx); rKoch(ctx, m); } function kochCurve(ctx, nRecursions) { ctx.lineWidth = 2; ctx.strokeStyle = "darkgray"; ctx.beginPath(); ctx.translate(10, 200); rKoch(ctx, nRecursions); ctx.stroke(); } onPaint: { var ctx = canvas.getContext('2d'); ctx.reset(); kochCurve(ctx, nRecursions); x = 0; y = 100; } } Row { Text { text: "# Recursions: " } Slider { id: sliderRecursions tickmarksEnabled: true stepSize: 1.0 minimumValue: 1 maximumValue: 6 value: 1 onValueChanged: { canvas.nRecursions = value; canvas.requestPaint(); } } } }
}@
This was easy to do by using the HMTL 5 canvas, but I kept wondering weather this is the way to do things the "QtQuick-Way" after all the canvas API is nothing Qt specific. Browsing around a bit and reading some more I figured out that there is also QQuickPaintedItem which is a wrapper around the QPainter API. So.. what is the way to paint something like a Koch Kurve in a way Qt Quick intended?
Also I ran into some problem I could not solve: For example the debugger did not show a proper stack trace when putting a breakpoint int onPaint(), but I want to see where it gets called from. And also for many JavaScript objects it just show "object" as value. So I ended up using console.log.
I also wanted to specify the size of the Canvas in terms of the size of it's parent rectangle:
@
width: parent.width
height: parent.height - 100
@
But doing so it gets stuck in some kind of endless loop where onPaint(..) gets called all the time. I could not figure out why and from where using the debugger.
One more thing I also could not figure out is weather I have to use JavaScript or I can just use QML and C++ for all the non-declarative code.
The Canvas api is a convenience api. If your onPaint function is relatively CPU intensive, you may get a performance boost by implementing the element as a QQuickPaintedItem. You can still keep the property interface the same for the rest of the declarative usage.
QQuickPaintedItem still isn't the fastest way to paint in QtQuick. You can do faster painting in c++ using QSG-nodes or even using direct OpenGL drawing before or after rendering of the QtQuick scene.
In your case, the contents of the Canvas seem to update rarely, while the GUI could be refreshed due to other animating items. Therefore it makes sense to use QQuickPaintedItem so the gui can refresh as fast as possible since its contents are available directly as a texture.
The reason you get a binding loop if you make the Canvas item depend on the size of the parent is because the parent is a Column. The Column item resizes itself based on the sizes of its children, therefore the loop.
Thanks a lot for the detailed answer! So the canvas API is the only way to paint from QML/JavaScript? For all the other options you still have to relay on C++. What about a delarative way to specify vector graphics? I could only find QML Rectagle and wonder if I could recursivley declare them somehow that the will form a Koch Curve :D
However I am a bit disappointed by the fact that you can create binding loops by doing something simple as possible. I mean I thought QML is as an easy to use solution for fronteds, like HTML but with a cleaner syntax and IIRC you cannot create binding loops in HTML. | https://forum.qt.io/topic/49592/long-time-c-qt-user-tries-out-qml | CC-MAIN-2017-43 | refinedweb | 875 | 62.88 |
import java.util.Scanner; import java.lang.Math; public class Exercise1 { public static void main(String[] args){ double x,sum = 0.0 ; Scanner scan = new Scanner(System.in); System.out.print("Enter the number : "); x = scan.nextInt(); for(double i=0;i<=(x+1);i++){ Math.pow(x, i); fact(i); double y = (Math.pow(x, i)/fact(i)); sum += y; } System.out.println("The e^"+x+" for "+x+" is :"+sum); } public static double fact(double i ){ double val; if(i == 0){ val = 1;} else{ val = i*fact(i-1);} return val; } }
Recommended Answers
Answered by JamesCherrill 4,278 in a post from
Line 10 you calculate Math.pow(x, i); but you don't do anything with the result.
All 3 Replies
JamesCherrill 4,278 Most Valuable Poster Moderator Featured Poster
Tarek_2 commented: This answer resolves the problem. +0
Be a part of the DaniWeb community
We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge. | https://www.daniweb.com/programming/software-development/threads/474981/not-accurate | CC-MAIN-2020-45 | refinedweb | 170 | 52.26 |
Red Flags that might affect analysts' decisions.
This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!
One step in assessing the quality of earnings is to look for red flags. An example of a red flag is a significant increase in accounts receivable without commensurate growth in sales (that is, accounts receivable turnover decreases). can you list and discuss at least five other red flags the astute analyst might look for, explain why each is a red flag, and identify where the analyst might find this information© BrainMass Inc. brainmass.com June 3, 2020, 10:47 pm ad1c9bdddf
Solution Preview
Operating an investment where the project's cost of capital is higher than the internal rate of return (IRR). IRR is the project's expected rate of return. If this return exceeds the cost of the funds used to finance the project, then the excess goes to the firm's stockholders (Brigham & Houston, 2007). Therefore, when IRR is less than the cost of capital, the project will not generate enough revenues to provide stockholders with enough returns. The analyst may find this information in the analysis of capital budgeting.
A shorter payables deferral period with an increase in days sales outstanding (DSO) is another red flag. A longer period of days' sales outstanding with shorter payables deferral period will cause cash ...
Solution Summary
This solution is comprised of events that may result in red flags impression in financing that may cause a change in the analysts' decisions. | https://brainmass.com/business/capital-budgeting/red-flags-that-might-affect-analysts-decisions-249878 | CC-MAIN-2020-34 | refinedweb | 255 | 61.97 |
Yes... its interesting...
Problems usually aren't in the place you look... I was looking for
problems with subversion. Turned out to be a Mac issue. I just assumed
Mac would follow UNIX naming rules with ChangeLog and changelog being
different files...
Ah well... you learn something new everyday...
Ajay
On Tue, Feb 3, 2009 at 10:23 AM, David Weintraub <qazwart_at_gmail.com> wrote:
> As soon as you said you were on a Mac, I was thinking that this may be
> a case sensitivity issue.
>
> The Mac's OS is an interesting amalgam of BSD Unix and the old System
> 9 - not in structure or programming, but in the way the OS handles
> certain issues. For example, a file can consist of two separate parts:
> a data fork and a resource fork. Unix utilities don't usually
> understand this, so tools like SugarSync have problems on a Mac. Also,
> some Mac files (such as applications) are really folders in structure.
> This causes a lot of pains with Mac development using tools such as
> Subversion.
>
> Another issue is file namespace. On standard Unix, there is a
> difference between ChangeLog and changelog. But, in Subversion, these
> are two different files.
>
> There are other issues like the EOL issue. Macs seem to do all three
> <CR> <CRLF> and <LF> depending upon the tool used. Older based Mac
> programs using the GUI still put just a <CR> on the ends of the files.
> The command line Unix utilities do a <LF>, and some developer tools
> (such as VIM) seem to prefer a <CRLF> to match their PC counterpart.
>
> This is no slam against the Mac. I have Macs at home and hope to help
> the U.S. out of these economic doldrums by buying a new MacBook. I
> also use Subversion and do a lot of development work on the Mac. I
> like the Mac as a development platform -- mainly because all of the
> standard OSS tools are there: Apache, PHP, Perl, gcc, JDK, etc. And,
> I've noticed that the Mac versions of many tools come out before the
> PC version.
>
> But, you do get some rather interesting results on the Mac that you
> wouldn't get on a PC or Linux box.
>
> I'm glad you found the problem.
>
> On Tue, Feb 3, 2009 at 12:13 AM, Ajay Gautam <ajay610_at_gmail.com> wrote:
>> David,
>> I think your post solved the issue.
>> After re-reading your explanation, I decided to get rid of ChangeLog:
>> svn rm
>>
>> After that, the checkout works fine...
>>
>> As it turns out, there was another file called "changelog" in the same
>> folder. Different cases, same name... I think thats what was screwing
>> up the contents in .svn
>>
>
> --
> David Weintraub
> qazwart_at_gmail.com
>
--
Happiness is a long walk with a putter.
------------------------------------------------------
To unsubscribe from this discussion, e-mail: [users-unsubscribe_at_subversion.tigris.org].
This is an archived mail posted to the Subversion Users
mailing list. | https://svn.haxx.se/users/archive-2009-02/0099.shtml | CC-MAIN-2017-43 | refinedweb | 483 | 75.61 |
C Alive and Well Thanks to Portable.NET 582
rhysweatherley writes "So C is dead in a world dominated by bytecode languages, is it? Well, not really. Portable.NET 0.6.4 now has a fairly good C compiler that can compile C to IL bytecode, to run on top of .NET runtimes. We need some assistance from the community to port glibc in the coming months, but it is coming along fast. The real question is this: would you rather program against the pitiful number API's that come with C#, or the huge Free Software diversity that you get with C? The death of C has been greatly exaggerated. It will adapt - it always has."
FOR THE LAST TIME... (Score:4, Insightful)
Re:FOR THE LAST TIME... (Score:4, Funny)
couldn't resist (Score:4, Funny)
You don't need to be a Kreskin [amazingkreskin.com] to predict C's future. The hand writing is on the wall: C faces a bleak future. In fact there won't be any future at all for C because C is dying. Things are looking very bad for C. As many of us are already aware, C continues to lose market share. Red ink flows like a river of blood. FreeC is the most endangered of them all, having lost 93% of its core developers.
Let's keep to the facts and look at the numbers.
OpenC leader Theo states that there are 7000 users of OpenC. How many users of NetC are there? Let's see. The number of OpenC versus NetC posts on Usenet is roughly in ratio of 5 to 1. Therefore there are about 7000/5 = 1400 NetC users. C/OS posts on Usenet are about half of the volume of NetC posts. Therefore there are about 700 users of C/OS. A recent article put FreeC at about 80 percent of the C market. Therefore there are (7000+1400+700)*4 = 36400 FreeC users. This is consistent with the number of FreeC Usenet posts.
Due to the troubles of Walnut Creek, abysmal sales and so on, FreeC went out of business and was taken over by CI who sell another troubled OS. Now CI is also dead, its corpse turned over to yet another charnel house.
All major surveys show that C has steadily declined in market share. C is very sick and its long term survival prospects are very dim. If C is to survive at all it will be among OS hobbyist dabblers. C continues to decay. Nothing short of a miracle could save it at this point in time. For all practical purposes, C is dead.
Fact: C is dead
Re:FOR THE LAST TIME... (Score:5, Insightful)
It is at best stupid to talk about how 'C is dying' anyway, seeing as it is still the most popular language in many areas, as well as the single biggest inspirator for 'new' languages.
I can't remember how many times the impending deaths of such things as COBOL, FORTRAN, BASIC, mainframes etc etc have been announced, but they are still going strong all of them.
Following the same arguments, C# and
This is a weird one (Score:5, Insightful)
So now we have a new slashdot story running with the mistake...
The majority of CPUs in today's world are not running desktops.
Things with C
Linux
compilers
Automotive
engine controllers
ABS controllers
Airbag controllers
Memory seat controllers
etc...
Calculators
desktop BIOS and chipsets
Cell phones
etc...
Most code written to run on the hardware is written in C. So the contention being refuted is faulty in the first place.
Re:FOR THE LAST TIME... (Score:5, Funny)
I agree 100% that C is the biggest inspirator for new languages. One can only take being burned by C's shortcomings so much before deciding that there has to be a better way.
Re:FOR THE LAST TIME... (Score:3, Funny)
What about C++? (Score:4, Informative)
Re:What about C++? (Score:3, Insightful)
Re:What about C++? (Score:4, Insightful)
All three were fresh out of school and were working as professional C++ programmers!
When I say "unable to program in C", I mean that exactly; they were unable to deal with pointers, didn't understand the basic variable types, couldn't write an application without the Visual C++ application-wizard generating a skeleton for them!
"What's a main?"
"ints have a range?"
"why is my unsigned variable never decrementing to -1?"
"Pass by reference???" *blank stare*
If I asked any questions like - "How do you think printf is implemented?"
I'd get a typical response like "dunno"
OK you say, printf is big, etc...
But when I'd ask "What does this code you wrote last month do?" and get "dunno" as an answer, it was sort of shocking.
You see, I think everyone trying to lower the bar by getting rid of C and anything low-level like that will backfire, if these fresh-out-of-school examples are any indication:
After finding them so useless at getting the job done except when everything was just about completely pre-chewed and put into their mouths, I did what I had to.
I laid-off one of them.
Another left out of boredom and apathy because I gave him the task of fixing his own bugs.
If we lower the bar, it won't prevent problems from existing and needing to be solved, you see, and only the programmers with TRUE aptitude will succeed, and they won't mind C one bit.
Re:What about C++? (Score:5, Insightful)
Re:What about C++? (Score:3, Interesting)
No it is not. Been there. Done it. For ultra fast solving of linear equation systems actually. A good hand coded vector library written in ASM will beat it outright. Been there done it. 12 years ago. Wrote vector libraries for TP which used routines specific to each of the CPUs at the time 286/287 (standard, AMD and Harris), 386/387, 386/IIT and forgot what else (it was just before 486 came out). Took 4 weeks of work to write an
Re:What about C++? (Score:4, Funny)
to drop an equation solver into your OO program.
Re:What about C++? (Score:3, Insightful)
Objective C is compatible with the underlying C (it's compatible with C99 too, last time I checked), while using a different "new" syntax for the object orientation, as well as providing a nifty class library and dynamic type checking.
In some respects, it's like C#, including the decently poor class library API (compar
Re:What about C++? (Score:4, Insightful)
As classes are first class objects, I love it. However since its only used on Macs, I cry.
Re:What about C++? (Score:3, Funny)
Obj-C on the other hand looks like the designers thought to hell with C , we'll design our own new-look language and shoehorn it kicking and screaming into C.
After meeting the designer, I'm inclined to agree.
Re:What about C++? (Score:3, Informative)
Re:What about C++? (Score:3, Informative)
Re:What about C++? (Score:3, Interesting)
Re:What about C++? (Score:3, Interesting)
Yes, it is a more bloated, complex and difficult to learn version of C.
No, I have always taken it that C++ is good if you dont know C and C is good if you dont know C++. Once you learn the one you become suddendly jaded towards the other.
Please stop C++ calling portable (Score:5, Insightful)
The story may change if you are writing C++ code that can stay in some kind of boundy, without using much library code, but unfortunately, i did not have that chance.
IMHO, java is really successfull in cross platform software development, without much work i can make java software work on another platform.
If C# had the same future, i'd be really glad, since i like it too, but as Microsoft works harder and harder on
Don't get me wrong, i loved the work they've done, but the result will be a platform inferior to java 1.5 and
So i'll be using C++ for platform spesific, high performance apps, C# for windows apps that require rapid development, and JAVA for cross platform. That's my 2 cents...
What type of documentation? (Score:3, Insightful)
Well, duh, the claim is c++ is portible not "all libraries that c++ uses are portable"
Having said that I would say that there are degrees of cross-platform-ness. Java being much closer to the ideal than c++.
Please stop JAVA calling portable (Score:3, Insightful)
Also, if you want protabe C++ code, all you have to do is draw a firm line in your design between platform specfic and the rest of your code.
Re:What about C++? (Score:3, Informative)
Re:What about C++? (Score:4, Informative)
I'm not very familiar with KDE's language binding availability right now, but I know that being written in C++ would make it more difficult to provide alternate bindings. C, being the lowest portable denomiator of programming languages is simple to create alternate bindings for.
language bindings Re:KDE, language support (Score:3, Informative)
Re:What about C++? (Score:3, Insightful)
I cannot believe this tripe is modded as 'insightful'. What ignorant rubbish (both the comment and the moderation of it).
It is relatively easy (as easy as with C) to create bindings for C++. And even if it wasn't, you can create
Re:What about C++? (Score:4, Interesting)
The problem is in trying to make use of C++'s more advanced features, such as templates and classes, from some other language. Many C++ libraries depend upon the use of these features to function correctly. Mapping a C++ class heirarchy to some other language is almost sure to require a large amount of work. While I agree that a C binding can be created for a C++ library, this may not be a trivial task.
Consider, for example, trying to crate a C binding for STL vectors. Since C does not support templates, the work will not be easy. One option would be to create some kind of C preprocessor that could add generics to C; but this is exactly how C++ started in the first place (as a preprocessor). Another option is to create a pure C interface, then to implement that interface using vectors.
The problem is that there is a huge semaintic difference between C++ and C. Most languages include some sort of C interface, since C is low-level and an easy target for interoperability. Few languages come with support for interacting with C++. For interoperability, C's semantics are simple: just functions and data structures. Calling C functions from some other language usually boils down to just a wrapper for the function, along with appropriate marshalling code to convert data types. On the other hand, C++'s model of OOP is a one-of-a-kind. Higher level languages simply do not share C++'s view of OOP. While there are definitely similarities that are shared among most object-oriented languages, the differences are so wide as to make a general interface to C++ impossible.
Er.. (Score:5, Insightful)
Re:Er.. (Score:5, Interesting)
C is going strong on Macintosh also. Cocoa programmers use mainly Objective-C which is fully backwards-compatible to C. You get the best of both worlds there. You can use C for the parts of your program where you really need the speed of C and can you use Objective-C where the advantages of object-oriented design best suit your program. Programmers who use the Carbon libraries instead of the Cocoa libraries also mainly program in C or C++.
There are many other languages available for Mac OS X but I would say that C, C++, and Objective-C are by far the most used. Since C++ and Objective-C are largely supersets of C, I would say that C is doing just fine under Mac OS X!
C?? (Score:5, Funny)
Yeah, just kill it off already... I wanna go back to using Commodore 64 BASIC.
Wow! (Score:4, Funny)
Can I get them to compile asm to java bytecode next?
Re:Wow! (Score:4, Interesting)
Not as funny as you think. It would be a truly awesome program that can do that. Why? take MS office, disassemble make it java byte code then run it on the platform and OS of your choice.
dont see anything like that happening for a while, but it certainly is not funny.
Not that simple (Score:5, Insightful)
Re:Not that simple (Score:5, Funny)
(it's a _joke_, laugh!)
Yup that exists (Score:5, Informative)
Re:Wow! (Score:5, Informative)
Takes compiled mips binaries and converts them to functional java classes.
Re:Wow! (Score:5, Informative)
You do know that the
One the app is running, the processor is dealing with native, optimised machine code rather than the IL bytecode.
Dan.
Re:Wow! (Score:3, Informative)
C# is not run as interpreted bytecode (which would be slow); it is "compiled" to bytecode and then, when the program is first run, compiled to native code. It is about 10-20% slower than a similar program written in C++, but for most GUI apps on modern machines, this does not matter.
Of course, for "real programmers", C and C++ still grant you much more power. Function pointers, inline assembly, easy bitwise operations... C# is fine for many programs, but just TRY to implement a network pro
Weren't you guys beaten to it by CNet? (Score:3, Funny)
Because there was no more room in hell? (Score:5, Funny)
Keep it real... (Score:5, Insightful)
Now what a spin. The
Re:Keep it real... (Score:5, Insightful)
I'm not sure or clear of why one would want to code in C instead of C# when developing for a
So is this because someone feels that OO could be too big for very small devices (Java MIDP showed us this very clearly, since it is completely missplaced and awful on mobile phones)? I can buy that.
Or is it because of some form of hatred towards C#? That makes it sad. The APIs for
Re:Keep it real... (Score:3, Insightful)
Re:Keep it real... (Score:4, Insightful)
For example, if you need good JPEG decompression routines in your ".net" application you could recompile libjpeg with pnet's cscc compiler and keep your application 100% "managed".
Far too many people on this thread know *nothing* and are talking crap.
Importance of compiling C to portable executables (Score:5, Insightful)
Sure, but this helps only if you can assume that those compiled C and C++ binaries are already installed on the user's computer. The main point of "compile once, run anywhere" is to be able to distribute a compiled program that will run anywhere. Of course in DotGNU [dotgnu.org], we don't define "anywhere" as narrowly as the Microsoft monopolists do:
Unlike Microsoft's C compiler, whose output will only run on i386-based Microsoft Windows systems, our compiler turns portable ANSI C code into a truly portable executable that will run any platform that has a CLR ("Common Language Runtime"), regardless whether the system is 32-bit or 64-bit, little-endian or big.
Or is it because of some form of hatred towards C#
No. It's because there's a lot of C code out there that people might want to use from C# and other modern languages. Throwing that C code away and re-implementing in another language would be a waste of time.
C's not dead because nothing better.... (Score:5, Insightful)
Re:C's not dead because nothing better.... (Score:3, Informative)
Re:C's not dead because nothing better.... (Score:5, Interesting)
For general purpose programmming, C++ is often overlooked because it suffers from the same problem as C in this scenario, which is that there isn't really much in the standard library to draw from. C#, Java, Perl, Python, etc, all have lots of "foundation" underneath which allow you to build applications quickly.
However, this is not so much an issue of language as it is of API, and C++ has the language features necessary to build a good API. All that is needed is a good library then, such as the Qt C++ library [trolltech.com]. With Qt, you get nearly the same foundational API as Java, but with natively compiled code. C++ may not be the end-all be-all of languages (no language can claim this), but it is much more capable than many people think. If you wouldn't touch C/C++ with a 10 foot pole, you haven't tried Qt. You can have your cake (large, well constructed API) and eat it too (native code).
Re:C's not dead because nothing better.... (Score:5, Insightful)
C has no problems. It does exactly what it's supposed to do.
You create problems when using C for business purposes. Business programmers don't want to waste time chasing memory leaks and array overflows.
Re:C's not dead because nothing better.... (Score:3, Interesting)
But you are right most of the new languages really don't touch the areas where C is successfully today. I think one of the major problems, at least in the Unix world, is that pretty much every library is written in C, so if another language should take over, you would have either to rewrite all libraries out there or at least create bindings to your new language and since that is a
Re:C's not dead because nothing better.... (Score:5, Informative)
Actually some of them that look like they're written in C are actually written in C++. They're just careful to make sure that all the public interfaces are extern "C". They can then use whatever fancy C++ features they want in implementing the library.
I think this is one of the real strengths of C: because the ABI is so simple, pretty much anything can link to C and almost anything can create C bindings.
Re:C's not dead because nothing better.... (Score:5, Informative)
Hardly.
One of the problem with modern languages is, you can't write an operating system in them.
Sure you can, with little more ASM code than is required for a C-based operating system. Heck, lots of OSs have been written in things like Lisp. Actually, C is a terrible language for writing operating systems. Because its not safe, you have to have an MMU to protect programs from each other. This sucks for performance. Not only do you have the hit of memory protection, but you have to have bounderies between userspace and kernelspace, and between programs. That's why it takes 600(!) clock cycles on my P4 to do something trivially simple like gettimeofday()! If you use a safe language, you don't need memory protection, or even a kernel/userspace boundry for that matter. You get completely fine-grained protection for all objects. See this SF project [sourceforge.net] for an OS written in a safe language.
One of the problems is half the new languages are scripting perl/python like langauges and the rest compile to byte code.
I don't know what's the current fetish with VMs, but most of the really advanced languages (Lisp, ML) compile to well-optimized native code. Look at the recent comp.lang.lisp thread where they ported Almabench to CMUCL, and got within a few percent the performance of C.
Maybe C would go away if there was a compiled langauge that wasn't largely controlled by one company that produced fast code and was portable.
Common Lisp [cons.org]
Another Common Lisp [sourceforge.net]
Ocaml [ocaml.org]
Scheme [inria.fr]
Dylan [gwydiondylan.org]
Another Dylan [functionalobjects.com]
We have lots of languages that are much more powerful than C (hell, they're much more powerful than Java/C#), safer than C, and very close in performance. It is merely a failure of programmers and the software industry that we have not been able to utilize them.
Huh? (Score:3, Funny)
In the meantime I'll just risk being labeled "old-fashioned" and compile C straight to binary
Declaring "X is dead" is just a cheap shot. (Score:5, Insightful)
,"Apple is dead". [macobserver.com]
When technologies really do die, its when noone gives a damn about them, and so noone will be writing a story about it.
Insightful (Score:5, Interesting)
Broader Perspective (Score:5, Funny)
> Queens English is so dead.
> Yo, it's all about Ebonics.
> Dude, Southern Drawl is *soo* slow... Surfer speak is a way better language.
> Like, Valley Speak is, like, the best networking dialect to know!
> Well, if you want a job with a blue-chip company, go with Chicago Twang.
> I hear that they're porting the Queens English libraries to Chicago English, btw.
> See? Queens English is not dead...
Dialects, people... just dialects. Try to see things in the broader scheme of things. (punny, eh?).
It's not dead. (Score:4, Funny)
Embedded/Real-time systems still need C (Score:5, Informative)
As an example, our lab works with humanoid robots that run in a 5ms control loop, which means that the next command (computation of inverse dynamics, etc.) has to be ready in that timeslice. If you want to do fancier stuff like machine learning and AI, you'll have to squeeze in many more operations into that tiny window. Sure, additional processors are a plus, but you still need very fast and memory efficient code.
Re:Embedded/Real-time systems still need C (Score:3, Insightful)
[1] as long as you disable exceptions & RTTI and stay away from virtual/multiple inheritance & pointers to member functions.
C is Dead (Score:5, Funny)
Saying C will be killed by a runtime architecture (Score:5, Insightful)
The C design paradigm (low level, varied environment, highly optimized, developer control) is intended to solve an entirely different class of problem than Business runtimes (higher level, standard interface, managed resource, developer handholding). The two aren't in competition much at all.
Nor do I think much about trying putting a racing-wheel on a bus either. We already have C# and "Managed C++", both which can look quite a bit like C, if you want them to. All you have to do is ignore that they're fundimentally different in the way they treat resources due to the underlying runtime or lack thereof. (Which is like equating a bus to a sports car, ignoring the size and speed issues.)
Didn't RTFA but have some questions anyway :) (Score:3, Interesting)
- Pointer arithmetic
- Hardcoded type sizes instead of using sizeof() (i.e. assuming sizeof(int) == 4)
- Lax rules for casting
- And so on
Re:Didn't RTFA but have some questions anyway :) (Score:3, Informative)
- Pointer arithmetic
A: YES
- Hardcoded type sizes instead of using sizeof() (i.e. assuming sizeof(int) == 4)
A: WTF ?
- Lax rules for casting
A: YES
- And so on
A: Hey, porting glibc
Why C needs help (Score:5, Insightful)
Or we can look at it like this: "Wouldn't it be better to have many different toolkits that allow string concatenation and tokenization than one standard library of string functions?"
Or maybe this: "Isn't it great that we have several different native APIs for threads, processes, and IPC depending on underlying platform, five different and incompatible implementations for cross-platform usage, and no way to easily switch between implementations after the project is underway?"
And next shall we talk about databases? Or maybe sound processing? Or regular expressions? Hmmm...
The thing that C zealots fail to recognize is the need for clean, standardized APIs (NOT implementations). If you write code that uses strncmp(...), aren't you glad that you don't have to worry if the C implementation is the BSD libc or glibc or MS Windows' C library? Don't you wish the same could be said for the user interface libraries -- for example being able to swap out the Qt or GTK+ implementations at compile or link time? Or the database libraries? (ODBC? Don't make me laugh.) But you can't because each implementation has its own interface even though a button is a button, a checkbox is a checkbox, a database connect is a database connect, a regexp is a regexp, etc.
This is what
.NET gives; Not the mandated implementation, but much better it gives the recommended interface. If the C folks get it together and standardize more than just things like printf(...) and linked lists, you will get no end of gratitude from me and the gratitude of folks who are tired of reinventing the wheel and solving problems that were adequately solved twenty years ago. Unless that happens, you're gonna see more and more people moving to things like .NET and Java, warts and all.
POSIX was a good start, but it has stagnated and is showing its age.
Re:Why C needs help (Score:3, Interesting)
I wrote a shopping cart application that uses 23K of RAM and processes more than $2M in transactions online a week. I can handle more than 300 times the traffic than a comparable Windows server with this application and it's rock solid. I don't worry about bugs
I would take C++ over Java/C# anytime (Score:5, Informative)
The way I see it, the benefit of garbage collection is nearly canceled by the lack of stack variables and guaranteed destructor calls. I want to just declare a "Socket" variable in the middle of my function and have a guarantee that the socket will be closed when the block is existed in whatever way. finally or with just don't cut it. Say, I use 2 sockets, 1 file, a mutex and a temporary hash table entry at different points in a function. Imagine the mess of nested blocks, especially since Socket.close can actually throw an exception!
By contrast, memory management problems in C++ can be mitigated by destructors, reference counting and containers that automatically free members. Not ideal, but usually doesn't disfigure your code.
Now add other things missing from Java and/or C# - preprocessor, templates, multiple inheritence, operator overloading, unsigned types - and the new languages are really not that compeling for large projects that need heavy-duty, "dirty" features to manage complexity and can afford a regression suite that runs under Purify to fix memory corruption or leaks.
I know Java 1.5 has generics and C# has some more of C++ features compared to Java, but the matter of fact is that both languages are still tradeoffs compared to C++ in terms of productivity and stability rather than a clear step forward.
I would like to see a language that preserves as many features of C++ as possible while adding garbage collection, memory safety, language-based security and guaranteed binary compatibility between platforms/OSes. I don't think managed C++ is "it". Why can't a VM support multiple inheritence? Any pointers?
languages are tools god dammit (Score:5, Interesting)
Fortran is extremely good for producing high performance number crunching code (it forbids array overlapping, and thus several assumptions can be made by the compiler). C is very low level and I would hardly chose another language when writing an operating system, it is also a fairly general purpose language, good for many things. If I am writing a GUI-app I would surely pick an object oriented language such as C++, Java or Objective-C. If I write a 3d engine, I'd like performance and an object oriented approach and I would chose either C (combined with self discipline) or C++.
The portability of Java and other byte code languages is surely appealing, but they usually produce a terrible user experience since the applications produced tend to have a user interface compliant with the developer's OS (mixed with the language's own HI guidelines). A Java app written by a Windows developer would probably look like a Windows app, even on a Mac, and the other way around. Consistency in user interface is very important I think, so my hope is that people write code according to the MVC principle, and thus ease porting of the application to other platforms. Just to note, I'm not condemning Java, it is a very useful language if you want an internal application that is to be deployed on different systems. Say that the graphics departement (using Macs) and the economics departement (using Windows) both need access to some internal database or application, then clearly Java is the way to go.
Anyway, select your language after the task at hand and write code with discipline!
C is alive, not becoz of Portable.Net (Score:3, Interesting)
C will not die becoz,
Most of the real high performance stuff is still written in C. Take Windows drivers for example. The only other option would be C++, but then when it gets down to that level you try to squeeze out every bit of performance. What I have noticed it that when you look at the complexity of writing a Windows device driver, the relative complexity of C versus C++ becomes a non-issue in most cases.
You cant write OS/drivers in bytecodes.
But:
There is no point in a
Maybe i exagerated when i said no point. Maybe for small projects, components that need to interoperate with the rest of
Re:C is alive, not becoz of Portable.Net (Score:4, Informative)
Forth? OpenBoot? The currently alive OpenBIOS project?
QED
And how is this going to work? Paradigm clash! (Score:5, Interesting)
All languages on
That will not always work in all cases.
And what about interlanguage operability? An assembly in IL can be referenced from any
Computer languages form an ecosystem (Score:5, Insightful)
When I want to solve a program I choose the language I will use, taking into account the abstractions and facilities it offers.
#include "/dev/tty"
popularity (Score:3, Insightful)
This doesn't really tell anyone if the number of people using the language has changed. Given the explosion of programmers in recent years, be they professionally trained, or weekend dabblers, it is likely that they are using the current faddy or new languages, like Java, C# or VisualBASIC (not meant as flamebait; I use them myself when engineering requirements suggest them). This for the most part because their emphasis is on making pretty UIs and not any of the more traditional processing or server applications.
This 'explosion' of users with new languages doesn't mean that the old Fortran, Cobol or C applications will immediately be re-written in BoltsN.Nuts or whatever the latest and greatest is. These people will, quite sensibly, plod along with the tried and tested and will probably even continue developing within these skillsets.
The requirements for these skills may well have stayed the same, while the requirement for GUI apps and amateur (some calling themselves professional) developers has increased.
Before anyone can say a language is dying, lets see the figures. For all we know, these dying languages could even be growing (in numbers, if not percentage). Besides which, who should really give a damn?? If it works for you, use it. If it doesn't, but you're not harmed by it, live with the fact that the Borg haven't yet asssimilated us all
The real question (Score:3, Insightful)
No - that's not the real question; it's: 'Oh no, not yet another C-like language!?'
What's the point, actually? C# is not something new, it's just an attempt to 'get the colour exactly the right shade of pink'. The truth is - C (the language) is precisely what it should be. So perhaps it would be nice to protect the more inept programmers against themselves, but that is simply a question of the runtime- and development environment, or perhaps some improved libraries.
As I always say: a good programmer can write good code in any language, and a bad programmer will not write good code in any language; it's as simple as that, really. This is because good programming is about good coding and debugging practice, both of which are independent of whichever language you use.
pitiful number API's (Score:3, Insightful)
Thank God! (Score:5, Funny)
litmus test for programmers (Score:5, Interesting)
This whole story is a big troll, and if you're not a serious programmer, you wouldn't know it.
Boo hoo... built-in string boundary checking in newer languages. If anything, C is the catalyst for a plethora of invaluable programming habits that today's programmers seem to take for granted.
You Sound Like (Score:3, Informative)
C's only strengths are speed and easy access to hardware.
String boundary checking SHOULD be a feature of any modern language -- or do you enjoy buffer overflow exploits?
Languages don't die (Score:5, Insightful)
I know the quote was wrong, and thus the entire discussion is senseless. But still, there are things to say about a language dying: (computer) languages do not die. Period. All of the languages ever invented are still used somewhere. People still use FORTRAN, COBOL, C64 BASIC and all kinds of other weird languages.
Besides, why would one of the most powerful and widely used and known languages (C) die? It is like saying noone uses a normal screwdriver anymore, just because they own a battery-powered one. Sometimes you just use the normal one, because it is easier, faster and it just works.
Poor Perspective (Score:3, Insightful)
It's like comparing the importance of your spinal cord to the importance of your kidneys. They both kick ass and serve a particular purpose; in many cases they complement each other wonderfully. And let's not forget that Python and Java both use C as an extending languge.
"the pitiful number API's that come with C#" (Score:4, Insightful)
Java vs C vs C# (Score:5, Informative)
C# whips the tar off of Java (and most non-optimized C code) in most benchmarks. Why? Because it's running on Windows only for these benchmarks. Anyone remember IIS running faster than Apache because of MS taking advantadge of undocumented platform APIs?
Do you think C# on Linux/BSD/*nix is going to be near as fast as C# on Windows? Think again. It may eventually catch up, but not before it gets a reputation for being dog slow. (See Java as an example).
C is really fast. If you know how to optimize it, nothing can beat it (except assember or some special Fortran routines, if it works for you project). If you ~don't~ know how to optimize C really well, Java (anywhere) and C# (on Win32) can be as fast or faster. Usually is much faster, these days.
Java runs, with very little effort, on every major OS and platform out there. (And yes, I do this for a living). I work at SAS () and we ship the same codebase on Win32, HP-UX, HPi, Linux, Solaris, AIX, etc. The advances in the Just In Time compilers has made a huge difference in performance. (There are some differences in the major J2EE environments, but even that is addressable and minor compared to an entire product port).
Yes, it's still true that a programming guru can write some smoking C code, but Joe Sixpack Programmer usually can't beat Java's performance. And yes, I'm talking big number crunching. At a prior job (at a biotech), we crunched Big Numbers (two month runs on a grid of machines) and Java did a very respectable job. We spent our time improving algorythms (from a bio point of view, not a C/ASM point of view).
The C#/Mono crowd is spending a lot of mindshare in making sure that MS's latest language will run anywhere, and that's great. I am glad they are doing it and applaud the effort.
But Java is far and away the fastest true cross platform language out there right now. It's got the best cross platform enterprise environments available. If you are looking the most speed ~and~ portability, the King isn't dead yet.
:)
And another apocryphal quote is born... (Score:3, Interesting)
This article implies a great deal, but the reality is that Miguel never said C was dead. He said that to him C was dead, meaning that he intended to focus his programming time on C#. Pretty reasonable statement given that he's in charge of a project that's porting it to linux.
Surprisingly to the language zealots among us, Miguel is allowed to write code in whatever language pleases him.
The point? (Score:4, Insightful)
Having seen side by side comparisons of J#, C# & VB running on
Language Piggy-Backing (Score:3, Interesting)
So, in response, we have C compiling to bytecode. But, Longhorn will require bytecode assemblies to be signed; I suppose that could be built into the compiler as well (else wouldn't we lose portability?)
I was thinking along these lines a while back, and thought to myself, "What's to stop somebody from writing an interpreter for any language (I was thinking scripting at the time) that will run as a
What's the impact of doing this, you ask? Well, if the interpreter itself is the signed certificate-backed secure executable, then any little scriptlet or homebrew app could be run without being digitally signed!
To me that allows a fairly obvious circumvention of Palladium, and "trustworthy computing" is out the door.
What about LLVM? (Score:3, Interesting)
Pitiful number of APIs? (Score:3, Informative)
Completely ignoring the fact that no APIs could "come with" C# because C# is just a one of many languages that compiles to
Punch Cards (Score:5, Insightful)
FORTRAN and COBOL are still in wide use, even if they aren't as popular as they once were.
Re:Adaption, but.. (Score:3, Insightful)
As for Fortran and COBOL, Fortan is still an entry requirement to the California college system, and COBOL is still everywhere - deeply embedded into the payroll and employment operations of many businesses. And there are still vestiges of punch cards too - Scantrons and the like. So things don't die as easily as you might think. Much as we sometimes wish them away, they hang on.
Re:Adaption, but.. (Score:5, Insightful)
There will _ALWAYS_ be parts of an Operating System, hardware-oriented realtime or embedded app that _needs_ to be close to the metal. C/ASM is predictable, consistent, flexible and fine-grained in the things you can do with it. You certainly don't want a time critical interrupt handler routine that is supposed to be done in 5ms to suddenly decide that it needs to do some garbage collection or page in some hashing function to access an array of some sort.
Plus, C is great because it isn't assembly.
Even then, sometimes you just gotta write some ASM.
Sure, someone might make a "better" C that has similar goals (structured around ASM-style thinking rather than human-style thinking), but if they did it surely would be some incarnation of C. Compare traditional K&R C with the current features of GNU C (hooray for structure member tags!) or even the ANSI C99 specification.
Even though there has been no great change in the approach to programming itself (compare to LISP, haskell or Perl), C has nonetheless had continuous improvments along the way, from language and data structure standards to libraries, compilers, debugging tools, code profiling, and so on.
I find it hard to believe that we're going to have OS-level DMA transaction code written in Java or C#.
I once read in a visual basic for dummies manual (or was it Delphi?): "Trying to write an Operating System in Basic is like trying to fly to the moon in a hot air balloon".
At some point, you've _GOT_ to talk to the hardware.
- Paul
Re:So... (Score:4, Informative)
C is neither bad nor dead (not that it doesn't have its problems). Whoever wrote this article and the previous one about it on slashdot is a moron.
Re:So... (Score:5, Informative)
Re:So... (Score:5, Insightful)
You know the old adage, "Use the right tool for the right job?" Well, use C when you need it. C is probably the most misused language I've ever seen. But of course, this is Slashdot, the land where opinions are forged and are never to change.
Re:So... (Score:3, Insightful)
It has been said many times before, but it's worth reiterating: [nearly] all of those wonderful runtime environments, and interpreters are written in C. Sometimes, language designers try to implement a self-hosting interpreter (like, say, scheme in scheme,
...), but even here, it still has to be bootstrapped somehow. Unless you want to do this in (unportable) asm, you still need C.
To be sure, check Google News. (Score:5, Funny)
However, you should check News.Google.com [google.com] frequently in case the world ended and no one told you.
Re:So... (Score:5, Insightful)
Re:So... (Score:3, Insightful)
Re:Let it die! (Score:5, Interesting)
Remember, a language does not cause overflows - careless and stupid programmers do.
C is built for low-level interface, and its best suited for that purpose. Its lean and mean, and thats how its meant to be.
If you want complex exception handling and all that, you are probably using the wrong language for the task.
Blame the people who used C for the wrong task, not the language.
Re:Let it die! (Score:3, Insightful)
But why have a language that enables the possibility for careless and stupid programmers like myself to do overflows?
"Sir, perhaps its the fact that we put the self destruct button next to the light button on our new combat vehicle that causes a large number of them to explode?"
"Button proximity does not cause explosions! Careless operators cause explosions!!"
When I subscribed to Bugtraq, it seemed most of the vulnerabili
Re:It's Dead Jim (Score:5, Insightful)
Well, DUH. In the end its just ones and zeroes no matter what language you use. OO does not change the way computers operate much, it is a way to help programmers think about the problem domain in a way that hopefully is a bit easier for most of us. Jeez.
If you don't like it because it cramps your "bursting with geek studliness" style, that's fine. But if you don't even understand what high level languages are for, I doubt you know what you are doing. | https://developers.slashdot.org/story/04/03/15/0047202/c-alive-and-well-thanks-to-portablenet?sdsrc=prevbtmprev | CC-MAIN-2016-36 | refinedweb | 7,199 | 72.16 |
Sending SMS Messages with Visual Basic
WEBINAR:
On-Demand
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017
Introduction
We all know what an SMS is (hopefully!), but sadly, SMS is said to be a dying medium of communication. I honestly do not actually think it is, because most countries are still battling with proper internet communication, and the fact that internet prices are quite expensive, especially in South Africa. Anyway, enough rambling… Today, I will show you how to send and receive an SMS with your Windows Phone
Let's get straight down to business.
Our Project
Figure 1: Our Design
You may name your objects anything you like; but, keep in mind that my object names may be different than yours. If you want to follow my example to the letter, here is the resulting XAML code for this design:
<Page x: <Grid> <Button x: <TextBox x: <TextBox x: <Button x: </Grid> </Page>
Code
First, let me start with sending an SMS. Add the following code to add the appropriate namespaces and their functionalities to your project:
Imports System Imports Windows.Devices.Sms
This simply imports SMS communication capabilities to your project. Speaking about capabilities, you could also add this capability to your project. To add any Capability to a project, follow these steps:
- Double-click Package.appxmanifest in the Solution Explorer, as shown in Figure 2.
Figure 2: Solution Explorer
- This will produce the screen as shown in Figure 3.
Figure 3: Settings
- Select the Capabilities tab and choose it from the items in the list.
- You also could click on Project, Properties and click the Package Manifest… button, as shown in Figure 4.
Figure 4: Project Properties
If this is your first time playing with Windows Phone apps, have a thorough look through each of the tabs and play around a little. Here are a few articles that can assist you to get started with Windows Phone apps:
Add a modular variable. This is a variable object that will be used through all the objects on the page:
Private sdDevice As SmsDevice
Add the following code behind the button labeled Send:
Private Async Sub btnSend_Click(sender As Object, _ e As RoutedEventArgs) Handles btnSend.Click If sdDevice Is Nothing Then Try sdDevice = Await SmsDevice.GetDefaultAsync() Catch ex As Exception Return End Try End If Try Dim stmMessage As New SmsTextMessage() stmMessage.To = txtSendTo.Text stmMessage.Body = txtBody.Text() Await sdDevice.SendMessageAsync(stmMessage) Catch err As Exception sdDevice = Nothing End Try End Sub
You can say "Thank You, Windows.Devices.SMS Namespace." Why? Well, I honestly did not think it will be so easy. Okay, it is not easy code, but it is not too overly complicated either! What happens in this sub is set out in the following list:
- The Sub itself has been changed to Async, because it will deal with an Asynchronous process. If you have not heard about Async yet, I suggest you read the following article: Async Programming with Visual Basic and Windows 8 / 8.1
- It then tries to get hold of a valid SMS capable device. If it cannot find a valid device, it will do nothing; else, it will continue to the next Try & Catch block. If you have never encountered a Try & Catch block before, I recommend this (somewhat old) article: Handling Exceptions in Visual Basic
- Inside the last Try & Catch block, it simply set up the SMS message to be sent. I provided the number to where the SMS should be sent, as well as the body of the SMS. Then, I send the message.
- Easy as Pie!
Receiving SMSs
Add the following modular variable:
Private blnListening As Boolean
This flag indicates that the device is listening for incoming messages. Add the next code segment behind the btnRecieve button's Click event:
Private Async Sub btnReceive_Click(ByVal sender As Object, _ ByVal e As RoutedEventArgs) Handles btnRecieve.Click If sdDevice Is Nothing Then Try sdDevice = Await SmsDevice.GetDefaultAsync() Catch ex As Exception Return End Try End If If Not blnListening Then Try AddHandler sdDevice.SmsMessageReceived, _ AddressOf sdDevice_SmsMessageReceived blnListening = True Catch ex As Exception sdDevice = Nothing End Try End If End Sub
Also, not too complicated. There is one spanner in the works, however. Notice the AddHandler line? Well, this line creates a handler named sdDevice.SmsMessageRecieved that is the actual method that will show the SMS details—note, not the content, just the details such as where this message is from. I may talk about reading SMSs later. Add the sdDevice.SmsMessageRecieved event now:
Private Async Sub sdDevice_SmsMessageReceived(ByVal sender As _ SmsDevice, ByVal args As SmsMessageReceivedEventArgs) Await Dispatcher.RunAsync(Windows.UI.Core. _ CoreDispatcherPriority.Normal, Sub() ' Get message from the event args. Try Dim stMessage As SmsTextMessage = args.TextMessage ReceivedFromText.Text = stMessage.From ReceivedMessageText.Text = stMessage.Body Catch ex As Exception End Try End Sub) End Sub
Not rocket science. If you have not yet read my article about Async Programming that I spoke about, I suggest you do so now.
Reading an SMS
Add another button your page and name it btnRead. Give it a content value of Read. This button will be used to read the physical SMS that has been received. Add its code now:
Private Async Sub btnRead_Click(ByVal sender As Object, _ ByVal e As RoutedEventArgs) Handles btnRead.Click If sdDevice Is Nothing Then Try sdDevice = Await SmsDevice.GetDefaultAsync() Catch ex As Exception Return End Try End If txtSendTo.Text = "" txtBody.Text = "" Try Dim id As UInteger If id >= 1 AndAlso (id <= sdDevice.MessageStore.MaxMessages) Then Dim strMessage As ISmsMessage = _ Await device.MessageStore.GetMessageAsync(id) Dim strTextMessage As ISmsTextMessage = _ TryCast(strMessage, ISmsTextMessage) If strTextMessage Is Nothing Then If TypeOf strMessage Is SmsBinaryMessage Then strTextMessage = _ SmsTextMessage.FromBinaryMessage(TryCast(strMessage, _ SmsBinaryMessage)) End If End If If strTextMessage IsNot Nothing Then txtSendTo.Text = strTextMessage.From txtBody.Text = strTextMessage.Body End If Else End If Catch ex As Exception sdDevice = Nothing End Try End Sub
You should know the drill by now! First, it determines whether or not we have a valid SMS device. If it is dealing with a valid SMS device, it will continue to the next steps; else, it will not do anything. Because space is very limited, I decided not to put too many controls onto the page. So, excuse the fact that it will keep on using txtSendTo and txtBody, although for a different purpose.
The text gets cleared, and then it establishes the total number of messages received. If there are more than 0 received, it determines what type of message it is. If it is a Text message, it converts the binary message to a text message and simply displays it.
Conclusion
I hope you have enjoyed this article. Until next time, cheers!
About the Author
Hannes du Preez is a Microsoft MVP for Visual Basic for the seventh year in a row.
MSG91Posted by Teenabiswas on 08/11/2016 03:23am
thanks for sharing blog now I am sending SMS using phpReply | https://www.codeguru.com/columns/vb/sending-sms-messages-with-visual-basic.html | CC-MAIN-2018-05 | refinedweb | 1,177 | 55.03 |
Moving build them using the 2008 or 2008 R2 version of BIDS, and they can be used in either environment successfully, as long as the package doesn’t have an ADO.NET Destination. If it does, a package developed in the 2008 R2 version of BIDS will give errors when you open on a machine with the 2008 version of SSIS installed. This is because the 2008 version of the ADO.NET Destination doesn’t know what to do with the new property added to the R2 version.
This wouldn’t be a big deal, if you could have side-by-side installs of BIDS 2008 and BIDS 2008 R2, but the install for R2 replaces the 2008 version of BIDS. So, if you need to move packages developed in 2008 R2 to 2008 (a common scenario for me), you have to do a little extra work. There are a few values that need to be removed or changed by directly editing the package XML.
As always, it’s a good idea to make a backup of your package before editing the XML directly.
Open the package in your favorite text or XML editor, and look for the section that contains <components>. Underneath that, you need to locate the <component> tag that relates to your ADO NET Destination (the sample below is easy, since the name is “ADO NET Destination”, but that’s not the typical case (you do give your components meaningful names, right?).
="1" pipelineVersion="0" contactInfo="Writes to a database using ADO.NET provider.;Microsoft Corporation; Microsoft SqlServer v10; © 2007 Microsoft Corporation; All Rights Reserved;;1"> <properties> <property id="23" name="TableOrViewName" dataType="System.String" state="default" isArray="false" description="The Destination database table name." typeConverter="" UITypeEditor="Microsoft.DataTransformationServices.Controls.ModalMultilineStringEditor, Microsoft.DataTransformationServices.Controls, Version= 10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" containsID="false" expressionType="Notify">"sample"</property> <property id="24" name="BatchSize" dataType="System.Int32" state="default" isArray="false" description="Specify the number of rows per batch. The default is 0 which uses the same size as SSIS internal buffer. " typeConverter="" UITypeEditor="" containsID="false" expressionType="Notify">0</property> > </properties>
Once you’ve located the right <component> tag, you need to make two changes:
One, change the version=”1” attribute in the <component> tag to version=”0”.
="0" pipelineVersion="0" contactInfo="Writes to a database using ADO.NET provider.;Microsoft Corporation; Microsoft SqlServer v10; © 2007 Microsoft Corporation; All Rights Reserved;;1">
Second, remove the entire <property name=”UseBulkInsertWhenPossible> element. You can comment it out, as shown below, or just delete it.
>
If you have a lot of packages to move back and forth, you probably don’t want to hand edit this each time. I wrote a little application that will process a folder of .dtsx files, and strip the 2008 R2 information out. This is done using an XSLT transform (available in the source code). The application and source are available to download from my SkyDrive.
hi
hi your blog is very nice.
Hi John.
I’ve not extensivly tested, but I think that the “version” attribute is not required for either version of SSIS (R2 or SP1) and “UseBulkInsertWhenPossible” property is not required for R2.
Based on that, and just because I can and for the fun of it, I rewrote your tool as a .NET 4.0 console application using XLINQ instead of XSLT.
Here it is:
namespace Ssis2008R2_To_Ssis2008
{
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
static class Program
{
static void Main(string[] args)
{
string path;
if ((args == null) || (args.Length == 0))
{
path = Environment.CurrentDirectory;
}
else if (args.Length == 1)
{
path = args[0];
}
else
{
Console.WriteLine(“Usage: [path]“);
return;
}
Console.WriteLine(“Converting packages in {0}”, path);
Directory.EnumerateFiles(path, “*.dtsx”, SearchOption.TopDirectoryOnly)
.AsParallel()
//.WithDegreeOfParallelism(1)
.ForAll(ConvertPackage);
}
static void ConvertPackage(string path)
{
var info = new FileInfo(path);
if (info.Attributes.HasFlag(FileAttributes.ReadOnly))
{
return;
}
var dtsx = XDocument.Load(path, LoadOptions.None);
var converted = false;
var components = from c in dtsx.Descendants(“component”)
where c.Descendants(“property”).SingleOrDefault(p => p.Attribute(“name”).Value == “UserComponentTypeName” && p.Value.StartsWith(“Microsoft.SqlServer.Dts.Pipeline.ADONETDestination”)) != null
select c;
foreach (var c in components)
{
var version = c.Attribute(“version”);
if (version != null)
{
version.Remove();
converted = true;
}
var useBulkInsertWhenPossible = c.Descendants(“property”).SingleOrDefault(p => p.Attribute(“name”).Value == “UseBulkInsertWhenPossible”);
if (useBulkInsertWhenPossible != null)
{
useBulkInsertWhenPossible.Remove();
converted = true;
}
}
if (converted)
{
dtsx.Save(path, SaveOptions.None);
Console.WriteLine(“{0} converted”, path);
}
}
}
}
Sooo helpful. Thank you, thank you, thank you!!
Thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you, thank you!
Hi,
I have followed the instuction to migrate SSIS packages developed in BIDS 2008 r2 to BIDS 2008, and then deployed to a 2008 box. But, it still says me ADO NET Destination version mismatch(component not upgradeable, component missing, not registered etc..).
Let me know if I am doing something wrong.
Thanks
I’m not sure exactly what’s not working for you, but if you compare the 2008 R2 package XML to one created in 2008, you should be able to see any differences.
Did you ever get this to work? I’m having the same negative results as you did when I deployed my package.
WOW! Thank you SO much! I’ve been hung up on this for a couple of days and stumbled upon your post. This FIXED my issue!!! Thanks!!!!!!!!!
Actually, when searching for the component, you can search for the componentClassID which specifies the type of component. This should be: {2E42D45B-F83C-400F-8D77-61DDE6A7DF29}.
This helps if you have named your components something other than ADO NET Destination.
Well, we’re running SQL Server 10.0.4000, SS 2008 SP2.
I’ve run both programs, and I get the same error result.
Error: 2012-03-16 14:57:29.59
Code: 0xC0047062
Source: Transfer Canola Data to Holding Transfer Canola Data to Holding (ADODest Holding [1550])
Description: Microsoft.SqlServer.Dts.Pipeline.ComponentVersionMismatch
Exception: The version of component “ADODest Holding” (1550) Error
Here is the component. The version=”1″ has been removed, and the UseBulk… property has been removed. I’m not sure where the discrepancy is located.
“dbo”.”tblHolding”
0
30
Microsoft.SqlServer.Dts.Pipeline.ADONETDestination, Microsoft.SqlServer.ADONETDest, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91
This was built on BIDS 2008 R2.
Thank you so much for this. It stopped me banging my head against a wall. Worked perfectly first time.
Worked perfectly for me. Thanks a lot
Thank you very much for providing the transformation utility. It sure beats editing 20k line package files!
Thanks for this very helpful information.
Its a big shame that MS don’t put a hotfix for this so that a 2008 SSIS can be executed.
This is clearly just a case of MS trying to force needless expensive server upgrades. How hard can it be for MS to check the version of the package and server and simply degrade the additional functionality of the package.
Not hard I think.
Thanks for your efforts in this and for letting the world know
Dave
[...]-... [...]
Amazing thanks a ton
Thanks! Life saver!
[...] is the full article that outlines this problem:-... If you like this post, share [...]
We have a SSIS package that was written against SQL Server 2008 R2 and it has ADO.NET Destination tasks which is failing with the same messages as seen above. I modified the .dtsx file to change the version numbers for those components to version = 0 and removed the UseBulkInsertWhenPossible property but after deploying the package it does not fail but it also does not write any values to the tables that are defined in those ADO.NET Destination tasks. | http://agilebi.com/jwelch/2010/05/13/moving-ssis-packages-with-ado-net-destinations-between-2008-r2-and-2008/?replytocom=64654 | CC-MAIN-2018-17 | refinedweb | 1,284 | 59.3 |
The School Of Practical Philosophy: Love - Week Two
As the second week of my course on Love at the School of Practical Philosophy has come to a close, I have been thinking a lot about Self. Pretty much everything that we do here at school is geared towards gaining a better understanding of Self and about the wisdom that we have available to us. As such, I've started to think of the term, "selfless," as being somewhat ironic. We often refer to selfless acts as being virtuous. However, if we act without regard to our self, it appears that we are acting in direct conflict with the search for wisdom and for self understanding.
In philosophy, we posit that the beauty that we see in the world around us is a reflection of the beauty and the wisdom that we have inside of us. And, in fact, the more in touch we become with ourselves, the more beautiful the world appears to be. To keep in alignment with such an outlook, it seems only appropriate to conclude that the love we express outwardly is nothing more than a reflection of the love we express inwardly, at ourselves.
Given this context, the concept of "unconditional love" makes sense for the first time. If you concentrated only on the expression of love outwardly, unconditional love becomes frustrating and illogical. Our brains will jump through hoops trying to justify how one can love Evil; and when failing to do so, will chalk it up to a failure of character. However, if you realize that outward love is a reflection of inward love, then the only love that need-be "unconditional" is the love of one's self.
With this new understanding, you can start to see that the greatest potential for outward love must necessarily be founded, not in "selfless" love, but in "selfful" love. Of course, this is nothing new. Everyone is familiar with the cliche, "You can't love others until you love yourself." The problem with a cliche, however, is that it is so common-place that it is often ignored or not taken to heart. Much of this class seems to be about rediscovering things I already knew. But that's no surprise - I think the challenge of life is to be constantly rediscovering your identity, your values, and your principles.
The challenge of life is to unlock the wisdom that you already have within... selfful sounds better and much more positive.
@Peter,
Thanks! It's nice to hear that this connects with someone. The terms "selfishness" is such a loaded trigger word. That's why I like "selfful", although it is a made-up word :)
@Ben,
All words are made up, no words just exist. This your blog and therefore you male the rules!
@Peter,
Word up. I just use what ever I can find in order to bring about consciousness and deeper thinking... and sometimes you gotta make some stuff up in order to do that ;)
@Ben, I love making words up. But I do think that there is a distinction between what you describe as being "selfful" and downright "selfishness". I realize that there is in fact some level of self introspection in selfishness, regardless of whether you are being more selfful, as you described it, or just purely downright "selfish". When being selfful, as you described it, you are still having somewhat of a thought to others, as a part of looking into yourself is so that you can be a better "self" for others, and as it relates to how you interact with others. People who are acting just downright "selfish" are sometimes not looking at or even caring at all how others are affected by their actions. There is a huge difference in looking inward in order to improve yourself so that you can have better interactions with other people, and being so self-centered that you don't even take other people into consideration at all.
Also, even when people are being as "selfless" as they can possibly be...even when they are doing something almost soley for the other person, it's not like they are getting absolutely nothing out of it. They are getting the pleasure of seeing the other person pleased. They are getting the pleasure of knowing they did something good for the other person, that they made them happy. Without that, I doubt many people would do totally and completely "selfless" acts with absolutely no reward or regard to getting anything at all in return (even if it was that pleasure of knowing you did something really good for the other person).
As it relates to love, the downright selfishness where people care not at all or very little about the other person does not make for a good relationship at all. I have been in these types of relationships before, and they are not good at all. And sometimes, these people can pretend like they are wanting your happiness or doing something good for you, but even the things they do that are supposedly for you really have ulterior motives which utlimately are supposed to bring about the greatest good to them, not you. You are merely a pawn in their pursuit of happiness and advancement.
Sorry this ended up being so long. It originally was not. :-/
@Anna,
I don't want to get into a semantic argument. One could say that both "selfishness" and "selflessness" can be founded on a disregard for one's self (one in the long term and one in the short term). Despite the fact that this post was launched from a word, I'd rather not worry too much about what words mean.
@Ben, I hear ya. I was merely using the words to describe the actions without having to describe them explicitly every time I was trying to make a point about them. That would've made the comment even longer than it was. :-O I was really trying to just differentiate between someone being interverted in terms of looking inwardly and trying to improve themselves for the purpose of later having better interactions with other people versus someone who was completely self-centered to the point to where they did not even think of other people at all.
@Ben,
I think you have truly flipped selfless love on it's head to prove it's possibility or attainability...:) Love it!
I recently read a quote: Weak thoughts and feelings often feel strong but remember, real strength is never anxious, cruel, or punishing. ~ Guy Finley For me this explains how a selfless or true love should feel like. Since when we sometimes mistake our desire or wants as love and if we take a moment to reflect on those feelings we may notice that there might have been a bit of self died somewhere in there trying to attain the object of desire. The true love should be kind, pleasing and peaceful and harmonious.
@Ben,
Nice post. This if from the man in cloth, but this aligns perfectly with the saying 'Love others as well as you love yourself.', don't you think?
@Smita,
I absolutely love the quote that you posted. As usual, you added something to the conversation that could go much more indepth, but I won't add anything to it, because it would probably just water it down and make my comment way longer than it needs to be. I also read the one link you posted one time on right and wrong on one of the posts, and enjoyed the reading there as well. I always like looking at all aspects and sides of an issue.
I may be the only one, or there may be others like me, but in order for me to be in a relationship, it is almost necessary somewhat for me to give up or lose a little bit of self. But sometimes, this makes me a much better self. One of the reasons it is so hard for me to be in a relationship without letting go somewhat of self, and making some concessions, is because I love the ideal of traditional and conservative relationships.
I know that some people think that women who are traditional and conservative are dumb, and that we just don't want to work, but that is completely not the case. I love my job. I love working. I love the fact that I go to work every day and write ColdFusion and get paid for it. I love the fact that I get to go to work and mess with databases, and sometimes write little php...but the bottom line is that I get to do problem solving, and get paid to do it. I will always be a problem solver, and I will probably always do some level of programming. Probably ColdFusion, but depending on opportunity, it may be php. Regardless, I would do it whether I got paid to or not. I love the fact that I get paid to do it. I also love the fact that I am able to pay my own bills, take care of myself, buy my own food, and that I am independent of a man or anybody for life.
And giving up working doesn't really have to do with the concept of giving up self if I am in a relationship, even though I would give up working if I were married and my partner and I decided that it was what was best for the relationship, for us as a couple, and to some extent, for us as individuals. What I mean when I say I would have to give up some of myself to be in a relationship is that there are very few truly traditional/conservative guys out there. And so if I am in a relationship, especially with someone who isn't traditional and/or conservative as I am, I almost have to give up parts of that side of myself in order for the relationship to have a chance.
I can imagine there are other ways that some other people have to give up parts of themselves for relationships as well.
@Anna,
Actually I wanted to elaborate more last night, but my thoughts were all scattered and bouncing off all over the place…:) So by "self dies", I meant soul. Since I believe in each of us if we are truly connected or even if not-so connected with ourselves; our conscience and soul feels and hurts when we pretend or being manipulated. So my point was when you are truly in love you should not feel tormented… it should feel good not just outwardly but deep within.
When we say that we gave up something to get to something either a relationship or work or anything for that matter, it somehow always has a tinge of regret associated. So if you don't have regrets then those catalysts really helped you, so you really didn't lose yourself and rather gained or added to your self.
When it comes to love, I wouldn't disregard the feelings which sometimes either misplaced or mislead. Those are unreciprocated or unrequited love but very much true for the "self" that felt it and gave it all. But if one looks back it was never true for the soul since the soul was not in harmony with self. So the most ideal love should be harmonious and uplifting.
Now coming to traditional/conservative vs. liberal/progressive, these words are so limited and misused or confused while perceiving people. It's hard to categorize people into two broad groups. If I had to then I would label people as rational vs. irrational, stupid vs. intelligent, crazy vs. sane. I would also describe myself as "areligious" like @Ben mentioned in one of his comments. Areligious doesn't mean not religious or irreligious. It just means we don't give that much importance or concern to religion. So when one puts himself/herself against religion also becomes another inherent religion of opposite kind in my opinion.
I would end up contradicting myself every step of the way when describing love…:) The best way I can describe love is something in the lines of Socrates…If you ask me I know nothing. If you don't then I may know something. (Don't think that's the exact quote… but the gist I got out of one of his quotes).
@Smita, that's a good idea waiting until you were in a good state of mind and able to gather your thoughts. I should do that more often. If you had written a scrambled response, you probably would've sounded like a lot of my posts sound. All over the place. :^D
The way you describe being areligious almost makes it sound like I am, since it is highly personal to me, and something I do mostly as an inward thing. But I'd rather not go into the religion thing again other than saying that.
I've had feelings of unrequited love and unreciprocated, and looking back, sometimes I almost hold those up to being the most pure and true love, and definitely over other times when I may have thought I was in love but really wasn't. The key is that I wasn't mislead, nor did I mislead. They never knew I "loved" them, and I wanted it that way. They never led me on, so it wasn't like I was deceived or anything. Sometimes, there's just somebody and you just can't help but love them, whether they love you or not, and whether they know you love them or not. I can't explain it other than that.
Often, when it comes to love, I am at a loss for words and/or expression. It's kind of somewhat unchartered territory for me. I have rarely loved in my life, and especially the special rare kind of love which is both true and pure AND not unrequited or unreciprocated. My mother says I am a hard person to love. Maybe that is true and why it has been largely out of grasp for me.
About the giving up thing...giving something up for someone. I agree about it adding to you. I remember with my first love, I gave up a lot of things to become something else. I was in law school, and my mother would argue that he was at least 85% - 90% of the reason I gave it up, but that isn't true at all. There were tons of reasons that I gave it up, one of them being him, but he was probably one of the lesser important reasons. One of the bigger reasons was financial. That was related to him, but it wasn't that he directly was the most important reason I gave up law school.
When I got out of law school, I decided I wanted to go into a career where you could make enough to support yourself and at least another person. So I was looking at hot jobs where you could get enough education to get into the field, but not necessarily spend years and years at it, and then make a fairly substantial income...especially if you had to support another person. I did this, because he didn't have a career that could support himself hardly, much less me. I was willing to work so that he wouldn't have to.
So, anyway, that is what landed me in Computer Science. Computer Science was that kind of field back then. I knew many programmers who had little to no education and were working in the field with enough income to support themselves and their families. So I got into Computer Science then, and that is why I am a Developer now. Even though we broke up, I developed a love of it independently of him, so it became a part of me. So I am not regretful of all of that way that he "changed" me...I am thankful.
I like your Socrates quote. It kind of reminds me of the Supreme Court quote on pornography, although I'm not sure why. They used to hold sessions where they would watch porn in an attempt to define it. When they became frustrated with trying to define it, they came up with something like, "When you see it, you will know it". The empirical epistomological approach to something that just simply "is". You can't actually define it with words, or it may be very difficult to define with words, but it just simply "is".
@Smita,
I like your quote; and, it reminds me of something else we talk about in class - that Love is linked to Stillness. I think when we get agitated, things can feel very strong, and this is when we make decisions that don't necessarily align with our values. However, when we are still and centered, that is the point where we can dig deep into our wisdom and express love.
@Nico,
I like it!
@All,
My friend Iveth once shared a quote with me from Jalal ad-Din Rumi:,
That's a great quote of Rumi. Hadn't heard this one before. Like your current interpretation of it. I'm going to steal it ...:)
Thanks!
The unrequited love and feelings I mentioned before is very different from relationships and what I would like to have in a relationship if I had one. Oftentimes, when I choose to love someone and have feelings that I determine will be unrequited, it's a situation where a relationship and/or shared feelings would not really be feasible. For example, the current person I have a crush on lives thousands of miles away, with a whole nation between us. He's on one coast and I am on the other (well, I am not literally on the coast, but you know what I mean). I choose not to let him know my feelings partly for him -- I don't want to creep him out, and partly for the fact that it is infeasible, and also, why risk rejection and put up with rejection over something that is completely infeasible anyway? In this type of situation, I am totally cool with it being all about him. I'm not looking to get anything out of that. To be honest, I barely know the guy. I just know that I really like him a whole lot, and find him a valuable asset to the earth as a person. I enjoy the limited interactions we have, and that's pretty much it. And I wouldn't mind, really, if it stayed that way. Now, if he were to call me up and beg me to move out there with him, and it were feasible to do so, I might actually seriously consider it. But I am fine with the way things are right now.
With a relationship, however, I really appreciate the give and take of it. Call me selfish, but I like to get something out of the whole thing. With the guy I have mentioned before (not in this reply), I felt he and I both had this unselfish love for each other independently. I would say I did love him, more or less unselfishly, but I was only really able to do that because he loved me so completely unselfishly. I wasn't looking to get anything out of that relationship more than the unselfish love he was giving me. When I say I want to get something out of it, that's what I mean...love. I want to get love out of it, at least. Anything else is extra. :-)
I just really can't see being in an actual relationship with someone, and loving them, and trying to make myself a better person for them, and them not really loving me in return. I guess I just see love as cyclical, to a degree. It's like an exchange. An exchange of heat between people, for example. It's cold out. You have these two people. One of them generates heat and sends it to the other to keep the other person warm. The other person could return the heat back, and it could become a matter of passing the heat back and forth, and both people keeping warm. Or, in the case of love where one person is selfless and the other doesn't care about the first, then the first would have to keep generating the heat and sending it to their love's way. But there's always the chance of running out. That person could run out of heat...or steam, so to speak. They could become broken, uncapable of generating any more heat. I would say with love, most people need a return.
Philosophy is beautiful, I envy those who were on the course! wins.
@mvaughn,
I have absolutely been exposed to the golden rule, and I do agree with the idea and think it is ideal. Many times in life, I have contemplated this, though. The golden rule, as it is, states "Do unto others as you would have them do until you." I don't mean to be argumentative, and I think that under normal circumstances, it definitely is the way to go. But, I have thought many times...some people are very different from others.
I'll give you an example. In my life, I would much, much rather someone assume that a date was on, even if we hadn't touched base, if we had made plans. I would much rather someone "show up" for a date that we had 'tentatively' planned rather than just assume the date was off just because we hadn't touched based about it. But once, I had a date with a guy, which we were going to touch base about, but we had made a date, and both of us during the week were just too busy. But I thought it was still on. So I showed up, much to my detriment, because by the golden rule, I would have much rather the guy show up than stand me up. But it made the guy very uncomfortable, because he had expected us to touch base during the week, and thought the date was off. But how was I supposed to know this? This had never been communicated to me. I was penalized severely for this. I was called a 'stalker', and other things, and I was treated really badly, because I was attempting to not stand the guy up and go by the golden rule as opposed to just considering the date off and be on my merry way and let the date get rescheduled at some other point. And trust me, if I had gone on my merry way, it's not like I would have had nothing to do...I had plenty to do. I was a very busy person. But this person meant enough to me that I was willing to carve some time out in my schedule for him, and so I thought it was best to keep the date, even though we had both been too busy doing the week to make contact.
Another case of me being so very different from a lot of other people out there, and something I have had to learn to adjust along the way -- I grew up in a very small town, and we were all extremely friendly, knew everybody by name, etc. Well, for me, growing up, it was 100% accepted, and in fact expected, that people you knew would just randomly show up at your house at any time during the day, during regular waking hours. Of course it was considered rude before 9 a.m. (unless arranged), or after 10 p.m. (again, unless arranged), but any time during the day between those times, it was expected and accepted. I had to learn really quickly after leaving my hometown that this is not the way 'the world outside' works. lol. Apparently, in other places of the world, this is considered completely unacceptible...and you are expected to make definite plans before showing up at other people's house any time.
I have spoken with other women who have experienced similar things. Some women I have spoken to felt like if they were seeing a guy, it was 100% acceptible to show up at any time (because that is how they grew up), and so they would show up on him unexpected and he would be with another woman. Eeks. :-/
"The challenge of life is to unlock the wisdom that you already have within you."
On first read, I took a defensive stance against that. Having grown up in the church (protestant), that says to me, "You're your own God," and was always warned against that stadpoint.
On second read, I read that as saying, "You know what's right [for you], so just do it, the right thing." Still, I have some 'concern' for that because some people are just stupid and/or have no conscience.
What's wise to them isn't necessarily wise on-the-whole.
Regarding "love others," I recently was offered a job. I actually was planning on accepting it. Everything about it looked good: pay, the work, the boss... But I turned it down because even though the short term was right/good, I was concerned about the long term. So I 'loved myself' enough to decline, politely.
Along a similar-but-different vein, I dealt with this while being in the church. At some point, you have to "save yourself before you save another." Kinda like on an airplane when the masks fall and they tell you to put on your own oxygen mask first. If we were truly 100% selfless, we'd probably not be alive. We wouldn't work, because we'd be helping someone else. We wouldn't eat, because that means I'm taking food from someone else and that's selfish. We wouldn't breathe, because that's depriving someone else of oxygen. Extreme example, but you get what I'm saying.
Thus, you must get your /needs/ met first.
Now the follow-on argument to that is, "If I need $2 to survive, but I earn $3, then should I give away my extra dollar? Or, should I take my $1 and invest it so that I'll then have >$1 thus being able to serve/help/love more people?"
If person A gives away his $1, but person B invests his $1, if a year later, person B has $36 to give away, is he better than person A who only had $12 to give away?
Oh, and you should be studying Tae Kwon Leap.
@Randall,
I was trying not to post a comment, but you know I can't resist this. Grrrrr...darn you, Randall. lol. Just kidding. Kind of. Anyway, that last little bit that you posted was like the parable of the talents, wasn't it?
The other part of your comment reminded me of my training as a lifeguard, my cpr training, and other first-aid type training. The absolute, first rule to remember when you are a rescuer of any sort is to survey the scene and make sure that it is safe before you even enter to help out. If we were truly 100% self-less, we wouldn't care if the scene was safe, and we would absolutely enter an unsafe scene to help out.
That being said, I don't think there are many parents who would hesitate to jump in front of a train going full speed, walk over fire, or risk their own life in any way in order to save their young if their young was in danger. I guess that's part of the difference between the love you have for other people and the love that you have for your son or daughter.
On the job, selfishness is almost always required. I am fortunate that at my job, it isn't required much, but I have worked at places where they would throw you under the bus in a new york minute in order to save their own skin and their own job. The current place I work is very team-oriented, thank goodness, but I have worked at places that were very competitive, and where they pitted employees against each other. In those environments, you have to be selfish to survive.
The job I work now, I love it, but the bottom line really is that if I lost my job, I have close to 100% confidence that I could find another job that would pay sufficient amounts for me to survive. Therefore, although I do love my job and want to keep it, I know it wouldn't be a huge problem if I lost it. I would miss it, and would be sad, but it wouldn't be the end of the world.
I have co-workers, on the other hand, who are really dependent upon this job. Their way of life depends on it, and it would be devastating to them if they lost it. Therefore, I would take the blame 100% for something if I had to, if it kept one of them from losing their job. Because I know that for me, it wouldn't be that difficult to bounce back...I know I could do it. For them, it would be much harder. That's why I would sacrifice myself and me being at this job in a minute if I knew it would save them from being let go.
Often, in relationships, you have to be selfish in order to survive, and sometimes in order for the relationship to survive, especially if the other person is really selfish (unfortunately).
About the thing with the wisdom. I read somewhere that some people are of the thinking that we are born with this wisdom, and as we live in life and pick up things along the way, that wisdom gets buried, and it is a lifelong journey to recover that wisdom that was buried. Also, in regards to the comment "The challenge of life is to unlock the wisdom that you already have within you"...I don't think that necessarily means that this wisdom was something that was never given to you, at some point, it is just wisdom that you might have been given but forgotten along the way. For me, it's reminiscent of the many times I sat in a sermon, and the preacher was talking, and he was saying things that I for sure knew or had heard before, but hadn't thought about in a long time. Sometimes you can get caught up in life, and things you have heard and taken to heart gets kind of sweeped under the carpet, and then, when you are reminded of those things again, for example, during a sermon, it brings them back to life for you again, you are reminded of it again, and you can re-commit to it once more, and try to make an effort to live it as you go on with your life from that point on., this was so refreshing. I came across your blog on a google search for reviews of "The School" as I will be attending an introductory course in Fall. Greatly looking forward to it, after having read some of your posts. Thank you for the inspiration!
L | http://www.bennadel.com/blog/2262-the-school-of-practical-philosophy-love-week-two.htm?_rewrite | CC-MAIN-2015-14 | refinedweb | 5,296 | 77.98 |
In an -ideas thread, Guido suggested ():
> If we want some way to turn something that just defines __getitem__ and __len__ into a proper sequence, it should just be made to inherit from Sequence, which supplies the default __iter__ and __reversed__. (Registration is *not* good enough here.) If we really want a way to turn something that just supports __getitem__ into an Iterable maybe we can provide an additional ABC for that purpose; let's call it a HalfSequence until we've come up with a better name. (We can't use Iterable for this because Iterable should not reference __getitem__.)
Later in the thread, Nick Coghlan suggested ():
> Perhaps collections.abc.Indexable would work? Invariant:
> for idx, val in enumerate(container):
> assert container[idx] is val
> That is, while enumerate() accepts any iterable, Indexable containers
have the additional property that the contained values can be looked
up by their enumeration index. Mappings (even ordered ones) don't
qualify, since they offer a key:value lookup, but enumerating them
produces an index:key relationship.
So, in particular:
* Indexable is a subclass of Iterable.
* Sequence is a subclass of Indexable, Sized, and Container instead of Iterable, Sized, and Container. (Or, if #25987 also goes through, of Reversible, Indexable, Sized, and Container.)
* The abstract method __getitem__ and the concrete __iter__ implementation get moved up from Sequence to Indexable.
* Indexable does _not_ have a subclass hook (to avoid making every Mapping, generic type, etc. accidentally Indexable).
This means that you can write this (borrowing an example from Steven D'Aprano in):
class Squares(collections.abc.Indexable):
def __getitem__(self, index):
return index**2
Because this no longer depends on the old-style sequence protocol, testing it with ABCs will work as expected.
For related issues, see #25987, #25864, #25958, and | https://bugs.python.org/msg257311 | CC-MAIN-2021-31 | refinedweb | 295 | 53.81 |
getload() returns 3 elements: representing load averages over the last 1, 5 and 15 minutes. On failure empty list is returned. uptime() returns the system uptime in seconds. Returns 0 on failure. EXPORT None by default. AUTHOR Peter BARABAS, <z0d [@]...BARABAS/Sys-Load-0.2 (1 review) - 01 Sep 2002 10:01:55 GMT - Search in distribution
This module retrieves the 1 minute, 5 minute, and 15 minute load average of a machine. SYNOPSIS use Sys::CpuLoad; print '1 min, 5 min, 15 min load average: ', join(',', Sys::CpuLoad::load()), "\n"; AUTHOR Clinton Wong Contact info: (2 reviews) - 19 Mar 2002 01:57:14 GMT - Search in distribution
Module for accessing System load averages. EXPORT By default, the only exports are the constants LOADAVG_1MIN, LOADAVG_5MIN, and LOADAVG_15MIN. The loadavg() sub can be explicitly exported if desired. AUTHOR Jeremy Madea <jeremy@cpan.org> COPYRIGHT A...JEREMY/Sys-LoadAvg-0.03 - 30 May 2012 14:29:43 GMT - Search in distribution
Sys::Statistics::Linux::LoadAVG gathers the load average from the virtual /proc filesystem (procfs). For more information read the documentation of the front-end module Sys::Statistics::Linux. LOAD AVERAGE STATISTICS Generated by /proc/loadavg. avg_1...BLOONIX/Sys-Statistics-Linux-0.66 (5 reviews) - 09 Mar 2012 03:11:37 GMT - Search in distribution
With the all pragma you can load multiple modules that share the same root namespace. This vastly reduces the amount of times you need to spend use'ing modules. BUGS / FEATURES * This will remove the ability to use exported / optionally exported func...DEXTER/all-0.5101 - 05 Dec 2008 21:31:53...RJBS/perl-5.20.0 (5 reviews) - 27 May 2014 01:35
This is a command line interface for module Sys::Facter(3). It collects information (facts) about host operating system and prints them to STDOUT. By default, all facts available are printed in form that mimics Puppet's Facter output. You may also sp...DOZZIE/Sys-Facter-1.01 - 14 Apr 2014 10:58:52 | https://metacpan.org/search?q=Sys-Load | CC-MAIN-2014-23 | refinedweb | 331 | 51.44 |
Containers share some results from my use of FireLens, and provide recommendations for configuring it. This post is a deep dive on FireLens, Fluent Bit, and Fluentd. If you’re not familiar with Fluentd or Fluent Bit, you may want to familiarize yourself with them and the FireLens documentation before reading on.
What this post covers
- Why we built FireLens
- How FireLens works
- My experience using FireLens – Reliability and Recommendations
At AWS, our new features are driven by conversations with our customers. You can participate in this process by creating and commenting on issues in our public containers roadmap. The feedback we received on application logging was distilled into the following requirements:
- Support a wide-array of AWS Services as log destinations. From CloudWatch, to Amazon Elasticsearch Service and Amazon S3 with Amazon Athena, AWS provides multiple services, which can store and search your application logs.
- Require no additional configuration beyond the Task Definition. No one wants to worry about installing, configuring, and troubleshooting logging agents. No one wants to sift through documentation to find their use case. An ideal solution would simply have a set of examples for common use cases, which can be used as-is!
- Use Open Source for extensibility. If your use case is not supported, simply contribute changes or plugins to Fluentd or Fluent Bit. There’s no need to involve us 🙂
- Decorate logs with ECS Metadata. Log messages should be able to identify the AWS resources that created them.
- Observability on the performance of the log solution. You can enable logging for the Fluentd or Fluent Bit container, inspect resource usage, and obtain log delivery metrics. This is in contrast to Docker Log Drivers, which are “hidden” inside of the Docker Daemon.
- Facilitate partner integration. Since the announcement of the FireLens Public Preview, we’ve seen many of our partners add support for Fluentd and Fluent Bit. We’re pleased that FireLens is driving new contributions in open source!
From those use cases, it was clear we needed to build a solution based on Fluentd and Fluent Bit. Fluent Bit is our recommendation- because its resource utilization is considerably less than Fluentd. We support Fluentd because it’s an established tool with hundreds of plugins. Long term, we hope that FireLens energizes the open source community to add many of the features and all of the destinations that Fluentd supports in Fluent Bit. We will play a role in this by continuing to contribute plugins and improvements to Fluent Bit.
Why not simply recommend Fluentd and Fluent Bit? Why FireLens?
Fluentd and Fluent Bit are powerful, but large feature sets are always accompanied by complexity. When we designed FireLens, we envisioned two major segments of users:
- Those who want a simple way to send logs anywhere, powered by Fluentd and Fluent Bit.
- Those who want the full power of Fluentd and Fluent Bit, with AWS managing the undifferentiated labor that’s needed to pipe a Task’s logs to these log routers.
Our answer for the first group is best demonstrated by the GitHub repository of examples that we have created. Most of these examples only require configuration in the Task Definition, and they can be used with minor modification by anyone. They are straightforward to use, and require no knowledge of Fluentd and Fluent Bit.
Our solution for the second group is shown in the options field of the FireLensConfiguration object in the task definition:
To serve any advanced use case, you can pull an entire Fluentd or Fluent Bit config file from S3. This will be included with the configuration that ECS generates for you- more on that in the next section.
Storing the config file in S3 makes updates easier. I’ve personally found this very useful when testing out configurations. Before FireLens I always baked my config file into my Fluentd or Fluent Bit image- if I needed to change my configuration, I had to re-build my image and re-push it to Amazon ECR. With FireLens, I simply edit the file and re-upload to S3; when my tasks launch they automatically pull the new configuration.
Will you support other log routing projects?
We hope FireLens energizes the open source community to contribute more plugins and improve Fluentd & Fluent Bit. Standardization on those projects will help focus community efforts; fragmentation of features between many projects is not ideal. That being said, the interface for FireLens is minimal- other projects could be supported. If another open source logging project becomes dominant and is heavily requested by our customers, then we will support it.
How FireLens works
Is it a Docker log driver?
No. The
awsfirelens log driver is syntactic sugar for the Task Definition; it allows you to specify Fluentd or Fluent Bit output plugin configuration.
FireLens internals
The diagram above shows how FireLens works. Container standard out logs are sent to the FireLens container over a Unix socket via the Fluentd Docker Log Driver. The driver supports both tcp and Unix sockets; we chose Unix socket because it is the faster and more performant option. In addition, the FireLens container listens on a tcp socket for Fluent forward protocol messages– this allows you to tag and send logs from your application code using the Fluent Logger Libraries.
Generating Fluent Configuration
When the ECS Agent launches a Task that uses FireLens, it constructs a Fluent configuration file with the following parts:
- The log sources. These are the Unix and tcp sockets mentioned above.
- Transformer to add ECS Metadata. Unless you opt out, we use the record transformer plugin to add metadata to every log object.
- Optional User provided configuration. If you specify your own configuration file, we use the include directive to import it in the generated configuration file.
- Log sinks derived from the Task Definition. The configuration options you specify with the
awsfirelenspseudo-driver are converted to Fluentd or Fluent Bit output plugin configurations.
The configuration file is generated using our Golang Fluent Config Generation Project. You can view this generated configuration file after you launch an ECS Task with FireLens that uses the EC2 launch type. The configuration files are stored on the host, at the path specified by the value of the environment variable
ECS_HOST_DATA_DIR. By default, this variable is set to
/var/lib/ecs.
You can find the generated configuration file for your task at the following path on your EC2 instance:
You can see sample FireLens Fluentd and Fluent Bit configurations and their Task Definitions here.
The generated config file is mounted into your log routing container at the following paths:
- Fluentd:
/fluentd/etc/fluent.conf
- Fluent Bit:
/fluent-bit/etc/fluent-bit.conf
These are the default config file paths used by the official Fluentd and Fluent Bit images. Any Fluentd or Fluent Bit container image can be used with FireLens as long as it uses those default paths.
Implications of Config Ordering- One reason to use Fluent Bit
Fluent Bit internal log processing pipeline
The diagram above shows the internal log processing pipeline for Fluent Bit. This ordering is always enforced, regardless of the order of sections in the configuration file. This is very convenient for FireLens users. It means that you can add log sources, filters, and outputs to your optional extra config file.
Recall the config file ordering from earlier:
- The log sources.
- Transformer to add ECS Metadata.
- Optional User provided configuration.
- Log sinks derived from the Task Definition.
If the user provided Fluent Bit config file includes a log source, ECS Metadata will be added to the logs it ingests even though the source comes after the ECS Metadata transformer. It also means that you can easily send logs to multiple destinations. You can even split these multiple outputs between the Task Definition and you optional config; one can come from the Task Definition log configuration section, and others can be present in your config. I’ve created an example that demonstrates this here.
Neither of the above are possible with Fluentd. Log messages flow through a Fluentd config file in the order that sections appear, and they are sent to the first output that matches their tag.
Log Tagging in the generated config file
Fluentd and Fluent Bit route log events via tags- each log message has a tag, and each configuration section includes a pattern, which determines which tags it will be applied to. As you can see in the examples, the record modifier that adds ECS Metadata matches * for Fluent Bit and ** for Fluentd. This means that all logs have ECS Metadata added (with the caveat noted for Fluentd in the previous section that not all events “pass through” this section). See the Fluentd documentation for an explanation on why ** is needed.
The log outputs generated from the Task Definition match
<container name>-firelens* and
<container name>-firelens**. So, if you’re using Fluent Bit and your container name is app, the match pattern is
app-firelens*.
Container standard out logs are tagged with
<container name>-firelens-<task ID>. So if your container name is
app and your Task ID is
dcef9dee-d960-4af8-a206-46c31a7f1e67, the tag is
app-firelens-dcef9dee-d960-4af8-a206-46c31a7f1e67.
The CloudWatch plugins for Fluentd and Fluent Bit both allow you to auto-create a log stream named by the log tag. Thus, your log stream can be named based on the container and task which its logs originated from.
Let’s use this information to accomplish something cool. Recall from the FireLens documentation that ECS injects the environment variables
FLUENT_HOST and
FLUENT_PORT (when you use the bridge or awsvpc network mode), which allow you to connect to the TCP port, which your log router is listening at.
Use the FireLens CloudWatch example task definition; with the following log configuration:
You can then use a Fluent Logger Library in your application code; example code for the Python logger library is shown below:
from fluent import sender # connect to FireLens log router # container name is 'app' logger = sender.FluentSender('app-firelens', host=os.environ['FLUENT_HOST'], port=int(os.environ['FLUENT_PORT'])) # send a debug message with tag app-firelens.debug logger.emit('debug', {'log': 'debug info'}) # send an error message with tag app-firelens.error logger.emit('error', {'log': 'Error: Something went wrong'})
In the log group
firelens-blog, you get separate log streams for the debug and error messages because each are tagged differently.
My experience using FireLens: reliability and recommendations
During the development of FireLens and the AWS Fluent Bit plugins, I wanted to test that they could reliably delivery my logs to destinations and would be tolerant against scenarios that could cause log loss. I also was interested in understanding the resource usage of Fluent Bit with the AWS plugins under various loads. To this end, I performed some experiments.
Please note that these results do not represent a guarantee. Your results may differ. I merely want to share my experience as a FireLens and Fluent Bit user.
Reliability
Reliability is key for any logging solution. There are many situations that can lead to log loss: misconfiguration of permissions or network, a lapse in availability of the destination service, etc. With FireLens, the most common cause of log loss will be task termination. When your task dies, the FireLens side-car container stops, and any unsent logs are lost forever. This can be mitigated by configuring Fluentd or Fluent Bit with a persistent file buffer, however, that option is not available on Fargate (no persistent storage) and necessitates a cumbersome process of collecting logs from the unsent file buffers after task termination.
Ideally, all logs should be sent by the time the logging side-car is terminated. To test this, I created a fake application that logs predictable events, which can later be counted at the log destination. This logger emits logs at a configurable rate per second for 1 minute. It then immediately exits.
Before we analyze the results of my tests, we must understand what happens when a Task shuts down.
Unless overridden with our Container Dependency feature, ECS ensures that the FireLens container starts first and stops last. (More precisely, it will start before any containers that use the
awsfirelens log driver, and will stop after any containers that use the
awsfirelens log driver).
So in my log loss test, the app container exited first. Since it is essential, this will trigger the Task to terminate. The ECS Agent then sends a SIGTERM to the Fluent Bit/FireLens container, notifying it that it should clean up and prepare to shut down. Then, 30 seconds later it will send a SIGKILL, forcibly stopping the container. (This 30 second timeout is called a “grace period” and is configurable in ECS on EC2).
However, while performing these tests, I discovered that Fluent Bit by default only waits 5 seconds after receiving a SIGTERM before shutting itself down. This means that it is not using the full 30 seconds that it is allowed. I also discovered that by default, Fluent Bit tries to flush logs to the output plugins every 5 seconds. For each flush, the AWS plugins can and will make multiple API calls. However, we can improve throughput by decreasing this interval.
Both of these settings can be changed with the Service section of the Fluent Bit configuration file. The Grace setting configures the SIGTERM timeout, and the Flush setting configures the flush interval.
I performed tests with both the default Fluent Bit settings, and with these “optimized” settings. You can see all of the code for my performances tests here. The tests were performed under the following conditions:
- The tasks ran on a c5.9xlarge Amazon EC2 instance.
- Every Task used the Amazon VPC network mode, so that each got its own Elastic Network Interface.
- The application container outputted logs for 1 minute and then exited.
- I used the task level CPU and Memory settings; each task was given 1 GB of memory and 0.5 vCPU.
- Tests were performed with Kinesis Data Firehose and CloudWatch Logs as destinations. For Kinesis Data Firehose I increased the throughput limit on my delivery stream to 30,000 records per second (the default is 1000 in most regions). It should be noted that most FireLens users will need to request limit increases in order to use Kinesis Data Firehose for their logs.
- For each log emission rate, I ran 5 test cases.
FireLens Log Loss Test with Fluent Bit Default Settings
MIN is the worst performing test case out of the 5 total test runs.
FireLens Log Loss Test with Fluent Bit “Optimized” Settings
The optimized settings clearly increase performance. The difference in results is most noticeable for the MIN value- the optimized settings provide more consistent results.
The CloudWatch Fluent Bit plugin very slightly outperforms the Firehose plugin in both testing scenarios. This is probably because the CloudWatch PutLogEvents API accepts 10,000 events per request, while the Firehose PutRecordBatch API only accepts 500. I suspect that each request adds a small amount of overhead; thus larger API batch sizes result in slightly higher throughput.
However, all in all, the results are very good even with the default settings. Many applications will not output logs at the rate needed to see a benefit from the optimized settings. However, for those applications that do output logs at a high rate, using these settings is encouraged.
As of version 1.3.2 of the AWS for Fluent Bit image, I have baked the “optimized” configuration file in the image at the path
/fluent-bit/configs/minimize-log-loss.conf. You can use it with FireLens by adding the following section to the container definition for your Fluent Bit container:
While the results of those tests were satisfactory, I was curious about the memory usage of the Fluent Bit container. In order to successfully send all those logs, was its memory usage spiking significantly? So I performed the tests with default settings again, but this time set a hard memory limit of 100 MB on the Fluent Bit container. This means that if it exceeds 100 MB of memory usage, it would get OOM-Killed, and logs would be lost.
FireLens Log Loss Test with Fluent Bit Default Settings – 100 MB Hard Memory Limit
The results indicate that up to 7,000 log lines per second, Fluent Bit can send logs to AWS destinations while consuming less than 100 MB of memory. Interestingly, the Firehose plugin once again performs slightly worse than the CloudWatch plugin. The results strongly suggest that the Firehose plugin is more readily OOM-Killed than the CloudWatch plugin. This is probably once again due to its smaller API batch size; the in-memory buffer is filled more quickly because logs are being sent slower.
Future Improvements
Based on these results, I’ve opened two issues for improvements:
- Batch multiple log lines into a single record in Fluent Bit Firehose Data Streams plugin – amazon-kinesis-firehose-for-fluent-bit#12
- Set Grace to 30 when FireLens users do not specify a custom config – containers-roadmap#579
Resource Usage
Fluent Bit CloudWatch
Fluent Bit Data Firehose
Tests were run on a c5.9xlarge Amazon EC2 instance.
These results from my resource utilization tests were already published in Centralized Container Logging. I suggest using them to estimate the Task Size, which you will need on Fargate when you use FireLens. You can also use these values to set the CPU and memoryReservation fields in your FireLens container definition. I recommend against setting a hard memory limit with the memory field however; Fluent Bit and Fluentd’s memory usage can occasionally spike, and this will cause your container to get OOM Killed. Since the FireLens container must be essential- this will kill your task. As shown in the previous section on log loss, Fluent Bit can process logs at a high rate without using more than 100 MB of memory. However, it is still safer to not use a hard memory limit.
Finally, I ran a FireLens Task that uses Fluent Bit to send logs to Kinesis Data Firehose. I let this Task run for two weeks, to ensure that its memory usage remained stable over time. The results verify that there are no long term memory leaks or other issues; it is stable over time. This is to be expected- Fluent Bit is an established tool with a size-able user base.
FireLens Fluent Bit Memory Usage over 2 weeks
Conclusion
In this post, you learned why we built FireLens, and how it works. Knowing how it works, you learned tips on how to write custom configuration files for Fluentd and Fluent Bit. Finally, you learned the results of my resource usage and log loss tests, from which you learned tips on provisioning resources for your log router, and optimize for reliability.
We would like your feedback as we continue to optimize the logging experience for AWS Containers customers. What should we add to FireLens or to our Fluent Bit integration? Please open issues or comment on GitHub at our aws/container-roadmap and aws/aws-for-fluent-bit repositories. We take feedback received there seriously; the number of +1s and comments on issues help us determine which features are most important to our customers.
Finally, AWS re:Invent 2019 is around the corner. If you are attending, consider signing up for one of the following sessions on FireLens and Fluent Bit. They will be led by myself and Eduardo Silva, creator of Fluent Bit. | https://aws.amazon.com/blogs/containers/under-the-hood-firelens-for-amazon-ecs-tasks/ | CC-MAIN-2019-51 | refinedweb | 3,254 | 53.71 |
I'm using the following code to iterate through the RGB values to light an LED. What I noticed is that unless any of the given R, G or B values reach 50 the LED does not light up, as soon as it hits 50 it turns on and when it falls below 50 it goes off again. This happens for any of the R, G or B lights on any LED in the array.
I would have expected the LED to gradually get brighter from 0 to 49, the same way it does from 50 to 255.
Code: Select all
from sense_hat import SenseHat import time sense = SenseHat() sense.clear() pixcol = 0 while True: while pixcol < 255: print('Count: ', pixcol) sense.set_pixel(0,1,0,pixcol,0) pixcol += 1 time.sleep(.1) while pixcol > 0: print('Count: ', pixcol) sense.set_pixel(0,1,0,pixcol,0) pixcol -= 1 time.sleep(.1)
Is this expected behaviour, a limitation or do I have a faulty Sense HAT? | https://www.raspberrypi.org/forums/viewtopic.php?p=1066169 | CC-MAIN-2019-51 | refinedweb | 165 | 82.14 |
File Replication
Thanks...We actually use Groove for some doc sharing and other collaborative stuff.
However, I am looking for real-time replication for DR purposes. thx
Joe
DFS in R2
You can you use Distributed File System (DFS) in Windows Server 2003. It provides an orderly namespace as well as redundant file resources. However, the replication engine behind this functionality called File replication Service (FRS) is fraught with problems since it's inception in Win2K. From hotfix to hotfix, it has become more stable in Win2K3.
Currently we use the DFS service in Win2K3 to replicate our namespace data in conjunction with Tacit Appliance that replicates our SYSVOL.
Tacit is a smart enough to replicate only the changes made to the file as suppose to the whole file so instead of replicating a whole 25MB file across your servers, you are only replicating 16KB of changed data.
Looking into R2 DFSR which will eliminate Tacit and purely have a MS replication service.
File Replication
Hi, just use the DFS (Distributed File System) feature of Windows server 2003. That might help your problem..
Advin
jovenmail@yahoo.com
need details of DFS or FRS in Win2K3
I am trying to set-up file replication for web farm purposes.
I am familiar with DFS in WinSrvr 2K3, but the first step in Wizard asks for "Host" server and I want redundant servers making files available. So DFS "Host" implementation looks like it only makes "Root" and "Links" available via namespace FROM "Host" server.
I want to place file on one server and have file replicated to several other servers for back-up purposes, and if one server goes down, other servers can be used.
Windows 2003 Server - File Replication extended outage to our corporate location.
I understand that Windows OS has an internal replication function, however have never used or setup.
Does anyone have experience with the new file replication features of Win 2k3 server??
Is there any major performance impact to primary server?
We are looking for a process other than the nightly copy routines used in the past.
Any help would be greatly appreciated.
Regards,
Joe
Joe Labadessa
Source1 Group
jlabadessa@source1group.com
This conversation is currently closed to new comments. | https://www.techrepublic.com/forums/discussions/windows-2003-server-file-replication/ | CC-MAIN-2018-51 | refinedweb | 371 | 64.61 |
Ticket #77 (closed defect: fixed)
[PATCH] Importing SQLObject classes into model.py doesn't work
Description
I'm trying to import into model.py several modules, all located in the project package. I'm trying both class imports and package imports:
import user
as well as
from user import User
When I run tg-admin create sql, I'm getting:
... No classes found! No modules specified No packages specified Looked in eqqs: a2
The Getting Starting guide talks about being able to import into model.py, but I'm having a heck of a time actually doing it.
Here's an update. I think the Getting Started guide might be wrong on the ability to import other sql object classes as a way to distribute the model classes to other modules.
From the SQLObject docs:
"""When finding SQLObject classes, we look in the modules for classes that belong to the module -- so if you import a class from another module it won't be "matched". You have to indicate its original module."""
So, I added the modules to the egg info in sqlobjects.txt:
db_modules=foo.bar,baz.bam
and tq-admin sql create was able to find them.
Change History
comment:1 Changed 14 years ago by kevin
- Milestone set to 0.9
- Summary changed from Importing SQLObject classes into import.py doesn't work to Importing SQLObject classes into model.py doesn't work
comment:2 Changed 14 years ago by michele
The message Kevin was refering to is this:
comment:3 Changed 14 years ago by ianb@…
I can't remember exactly why I made it like that. Something about wanting to make it predictable, but maybe that's not really accomplished well by this. I'll think about changing the semantics.
comment:4 Changed 13 years ago by elvelind@…
For now you can the soClasses variable in your model.py (or model/init.py) and specify the classes you want to use in a list.
comment:5 Changed 13 years ago by Luca <luca@…>
Maybe adding a flag to sqlobject-admin to select if you want to search recursively in the model or not could be a good choice: still easy to use and can be used any way you need it.
comment:8 Changed 13 years ago by manxsupo@…
My vote would be to fix Getting Started Document with diff below:
Index: gettingstarted.html =================================================================== --- gettingstarted.html (revision 573) +++ gettingstarted.html (working copy) @@ -525,7 +525,12 @@ <p>You can also provide options via "query parameters" on the connection URI. A couple of useful options are debug and debugOutput. If you add ?debug=1 to your URI, each query will be output as it is run. If you add &debugOutput=1, you'll also see the result of the query displayed.</p> - <p>You define your data model in the model.py module in your project's package. If you have more model code than will comfortably fit in one module, you can always break it up into multiple modules and import into the model module.> + <p>You define your data model in the model.py module in your project's package. If you have more model code than will comfortably fit in one module, you can always break it up into multiple modules using one of the following two approaches: + <ol> + <li>Define a variable in your model.py or model/__init__.py module called 'soClasses' as a list of classes to include in the project's model.</li> + <li>Modify your projectName.egg-info/sqlobject.txt such that the db_module property is set to a comma delimited string of modules to find SQLObject persistable classes.</li> + </ol> > <textarea name="code" class="py"> from sqlobject import *
comment:9 Changed 13 years ago by jab@…
- Status changed from new to assigned
- Summary changed from Importing SQLObject classes into model.py doesn't work to [PATCH] Importing SQLObject classes into model.py doesn't work
The following is a SQLObject patch that adds an option to sqlobject.txt called "db_package". This tells sqlobject-admin to load all SQLObject classes found under the specified package. This was easy to do because the code for loading classes from packages was already there. I simply tweaked the code to support subpackages as well (i.e., package.subpackage).
In my project, I've tested this by having all model-related modules in project.lib.model and setting "db_package=project.lib.model". tg-admin successfully finds the SQLObject classes. Setting "db_package=project" works as well, though it is less efficient. There can be multiple packages separated with commas, as with db_module.
The patch allows both db_package and db_module to be specified, though allowing only one would be easy enough.
--- sqlobject/manager/command.py 2006-01-10 17:14:34.000000000 -0800 +++ sqlobject/manager/command.py 2006-01-23 18:34:19.000000000 -0800 @@ -372,6 +372,7 @@ all = [] package = moduleloader.load_module(package_name) package_dir = os.path.dirname(package.__file__) + package_subdir = package_name.replace('.', os.path.sep) + os.path.sep def find_classes_in_file(arg, dir_name, filenames): if dir_name.startswith('.svn'): @@ -379,9 +380,9 @@ filenames = filter(lambda fname: fname.endswith('.py') and fname != '__init__.py', filenames) for fname in filenames: - module_name = os.path.join(dir_name, fname) - module_name = module_name[module_name.find(package_name):] - module_name = module_name.replace(os.path.sep,'.')[:-3] + module_dir = os.path.join(dir_name, fname) + module_subdir = module_dir[module_dir.rfind(os.path.sep + package_subdir):] + module_name = module_subdir.replace(os.path.sep,'.')[1:-3] try: module = moduleloader.load_module(module_name) except ImportError, err: @@ -401,6 +402,13 @@ def classes_from_egg(self, egg_spec): modules = [] dist, conf = self.config_from_egg(egg_spec, warn_no_sqlobject=True) + for pkg in conf.get('db_package', '').split(','): + pkg = pkg.strip() + if not pkg: + continue + if self.options.verbose: + print 'Looking in package %s' % pkg + modules.extend(self.classes_from_package(pkg)) for mod in conf.get('db_module', '').split(','): mod = mod.strip() if not mod:
comment:10 Changed 13 years ago by michele
Great, you should ping Ian Bicking for taking a look at this.
comment:11 Changed 13 years ago by jab@…
- Cc ianb@… added
Ian, please check my patch.
comment:12 Changed 13 years ago by jorge.vargas
- Status changed from assigned to closed
- Resolution set to fixed
closing this is already in SO
I think Ian Bicking had a good reason why sqlobject-admin create ignores imported classes, but I can't find that message now :(
*Something* does need to happen here. Either the doc needs to be fixed or the code needs to be fixed. | http://trac.turbogears.org/ticket/77 | CC-MAIN-2019-22 | refinedweb | 1,074 | 60.21 |
runcharter
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Waffle
I didn’t write a blog post in March, because I was busy doing other stuff, but it turns out no one noticed, or maybe they did, and simply didn’t care. Well, I care, because it brought my streak of 20 successive monthly blog posts to an end. Which means I need to start a new one. And, if I was going to plot my number of successive blog posts, I might use a run chart. Which is an absolutely hideous way of shoe-horning in the topic of this month’s attempt:
Substance
After several abortive attempts spanning longer than I care to admit (or remember), I finally got round to building a package for making lots of run-charts all at once : runcharter. This is pretty niche, but, at the last count, using the fingers of one hand, I needed almost all of them to count the interested parties across the globe.
What unites us is that we all work in healthcare, we are involved in quality improvement or performance monitoring, and runcharts and SPC charts are a big part of what we do on a daily basis. Runcharts are easy to build, but are an absolute faff to update when median lines need to be updated. Most people start out building them in a spreadsheet, and adding in additional columns, which is fine for about the first 5 charts, but when you have hundreds, or thousands to analyse, it’s simply not viable.
I have done this sort of analysis in SQL, and used various BI tools to attempt it also – which I blogged about two years ago. I have a couple of fledgling attempts that were never good enough for release, plus many aborted efforts, so its a relief more than anything else, to cross this off my mental ‘to do’ list.
What does my package do? It takes a dataframe with 3 columns – a grouping variable, a date, and a y variable representing whatever value it is you want to plot, and it will then analyse the data to find any runs of n successive points on the desired side of the median line.
If it finds a run, it will calculate a new median, and look for any remaining runs. And it keeps doing this until there are no more runs, or there is no more data, at which point it will generate a lovely faceted plot for you, with a runchart for each individual group (my current record is a 68 panel faceted plot, which, I’m not going to lie, brought tears of joy to my eyes).
Typically, in quality improvement, you are only looking for a run on one particular side of the median line. For example, if you want to reduce patients falling in hospital, then alongside the actual hard work of implementing changes in practice, you would plot the number of recorded falls, and hope to see a sustained reduction below the median line. And then hopefully, with further improvement work, you might see another reduction.
In my place of work we have seen 3 sustained reductions in reported falls, representing more than a 25% reduction overall from our baseline period. In addition to plotting the overall totals, I also need to be able to analyse individual ward areas – and this package helps me do that.
I have bowed to popular demand (66% of the people who took an initial interest in the package requested this) and built in the ability to look for runs on both sides of the median, in addition to being able to select either above or below the line. It’s not something I would do personally, but I can see why some people want it, so it’s there now.
There are a lot of improvements needing made to the code, and I won’t be rushing to show it off any time soon, but it works. One thing I really hadn’t appreciated when building packages was the namespace / environment issues that crop up when you define a function that can’t be found within the scope of another function. I think its fair to say I’ve hacked my way round that, and this is definitely something that I would love to learn more about. The curse of being the only R user in the organisation, or indeed, possibly the only one around in (checks notes) the nearest 100 miles or so.
I also need to get to grips with testthat, which I have failed to do so far. One other change is to make the plot colours editable, as I know how annoying it can be if you find a package useful but hate the plots.
Bait and switch
If you work in healthcare/ quality improvement, and you need to make run charts on a regular basis, then you might find it useful. Other packages also exist, such as the excellent qicharts2. That package uses different rules for analysis, and also produces many other types of chart. I also want to highlight runchart, which is another package from an R using analyst based in Scotland which is far superior to mine, so be sure. | https://www.r-bloggers.com/2019/04/runcharter/ | CC-MAIN-2021-17 | refinedweb | 888 | 62.31 |
WndTabs Loaded Into DevStudio
Environment: VC5, VC6, eMbedded VC++, WinCE Platform Builder, Comctl32.dll 4.71+
What is it?Ever wished that you could quickly switch among your open workspace windows without using the "Windows" menu or Alt-Tab'bing till you drop? Well, I did.
The add-in has long ago evolved beyond a simple window switcher. Some key features found in the current version are:
- Highly configurable:
- Control what goes on the tab: number, icon, path components, resource information.
- Control the tab strip position (bottom/top).
- Control the number of tab rows. (NEW: Automatic row counts)
- Control what goes on the tab context menus.
- Tab context menus packed with useful features:
- Window management functions
- Close window/all windows
- Close all windows except current window
- Close all related files (file group)
- Minimize all windows
- Automatically (and selectively) close windows opened during debugging. NEW!
- File management functions
- Save file/all files
- Access the file's shell context menu.
- Open a file's alternate (.h<->.cpp etc.) file - manually or automatically (NEW)
- Toggle a file's read-only attribute for quick hack of source controlled files.
- Open a file as a text document. For instance, get quick access to your resource file's source.
- Open a file's containing folder. NEW!
- Clipboard copy functions
- And others...
- Full source code.
- Programmatically extend WndTabs using the WndTabs SDK. NEW!
- Access tabs via keyboard shortcuts.
- Setup wizard to set up toolbars and keyboard shortcuts.
- Full online help.
- Automatic setup program
- Supports most VC variants, including VC5, VC6, eMbedded Visual C++ and CE Platform Builder. NEW!
- Extension module (shareware) that adds the following advanced capabilities to WndTabs:
- Tab Grouping - allows grouping of multiple windows on the same tab.
- Tab Coloring - custom colors for tabs.
- Fully customizable menus. NEW!
- Fully customizable keyboard shortcuts. NEW!
Refer to the online help for installation and usage details, and a full list of features.
What's New
Version 3.0 has been almost a year in the making, and is the most ambitious version of WndTabs to date. This version is uses the great BCG library to implement a fully customizable UI. This isn't as simple as it sounds: To make everything work as it should, WndTabs is no longer a simple addin. It is now a full MFC application living inside another MFC application (Visual C++). As you might imagine, this requires a lot of stitching code. And although the casual user wouldn't notice (and probably wouldn't care), if you want to know how it all works, have a look at the source code.
As I said, version 3.0 is a major update to WndTabs and users of previous versions are encouraged to check out the WndTabs site for a full list of new features and bug fixes.
A feature tour is also available online.
The WndTabs Source CodeWndTabs is provided with full source code. The code demonstrates the following techniques:
- Writing DevStudio add-ins that handle events and export commands.
- Interfacing with other add-ins using the AddInComm library.
- "Stealing" events from other windows by using subclassing.
- Installing and using system message hooks (SetWindowsHookEx). NEW!
- Enumerating the shell namespace / full support for file context menus including the elusive "Send To..." menu.
- Use of common controls (tabs, images, etc.)
- Use of the MFC template based collections (CTypedPtrArray, CTypedPtrList, etc.).
- Reusable components for HTML Help integration in MFC applications!
- Use MFC to access Internet files.
- Detect version updates over the net unobtrusively for both direct and dialup Internet users.
- Small tricks of the trade:
- Dialogs that change at runtime.
- Storing your configuration in the registry.
- And more...
NoteMake sure to check out the WndTabs web site which is more likely to have updates and betas:
DownloadsDownload the WndTabs 3.0 Installer [binaries only] - (1,069 kb)
Download the WndTabs 3.0 Source Code Installer - (3,650 kb)
There are no comments yet. Be the first to comment! | https://www.codeguru.com/cpp/v-s/devstudio_macros/add-ins/article.php/c3179/Window-Tabs-Developer-Studio-AddIn.htm | CC-MAIN-2018-51 | refinedweb | 651 | 68.47 |
Learn how to use the FTX Rest API in Python to trade cryptocurrencies and develop crypto applications in this comprehensive guide.
If you’re new to FTX.US, use the following link to save 5% on all of your trade fees.
You can download the code at Analyzing Alpha GitHub Repo.
What is FTX?
FTX is a cutting-edge cryptocurrency exchange platform. With FTX, you can trade various assets like futures and options on top cryptocurrencies at competitive prices with significant leverage.
Sam Bankman-Fried and Gary Wang founded FTX in May of 2019. Since then, it has become one of the most popular exchanges for traders from all backgrounds who want access to provide liquidity and profitable opportunities when trading these highly volatile markets.
FTX.com is unavailable in the U.S. and others due to location restrictions, which is why the team came up with a solution.
FTX vs. FTX.US
FTX.US is the US-regulated cryptocurrency exchange brought to you by the FTX.com team. It’s built from the ground up to be a market-leading U.S. cryptocurrency exchange.
Should You Use FTX?
FTX and FTX.US are two of the best cryptocurrency exchanges for both discretionary and algorithmic traders due to the depth of the order book and the availability of assets to trade.
This isn’t a surprise considering Sam came from Jane Street Capital, which earned the top spot when we surveyed proprietary trading firms and is also backed by legends such as Paul Tudor Jones.
Why You Shouldn’t Use FTX
From an algorithmic trading perspective, the only downside to using FTX or FTX.US is that it doesn’t provide a trading test server.
With this out of the way, let’s get to the code.
FTX REST API Python Tutorial
This tutorial aims to teach you how to use the FTX Rest API. FTX provides many different API endpoints, including:
- Markets
- Futures
- Account
- Wallet
- Orders
- Fills
I’m going to show you how to interact with the Market API. You’ll be able to work with the other components of the FTX API without breaking a sweat in roughly 30 minutes.
Let’s get started.
Set up your Python Environment
The first thing you’ll want to do is create a python virtual environment and activate it.
$ mkdir project_dir $ cd project_dir $ python3 -m venv venv $ source ./venv/bin/activate
We’ll then use pip to install all of the necessary packages. I will demo using the API within Jupyter Notebook, so I’ll install that, too.
pip install -U pip pip install notebook pandas requests ciso8601
We’ll also want to download the Python FTX API client. You can do that by downloading the raw file from the FTX GitHub Repo or using curl.
curl is a handy *nix command-line utility that allows you to transfer data over various protocols. It stands for “Client URL”.
curl -o client.py
Let’s create a python file named local_settings.py to store our API key. Creating a dictionary to store local settings is helpful, and you can save the contents into git with git-crypt.
ftx = { 'apy_key':'', 'api_secret':'' }
With the environment set up, let’s get a free API key. I will be using FTX.US, but you can follow the same steps if you’re not a U.S. resident at the FTX.com exchange.
Get FTX.US API Key
You will first need to register for an account.
You’ll then want to go to settings found within the dropdown menu when clicking your login name and selecting API.
You’ll then want to create an API key. If you’re not going to place trades, select a read-only key; otherwise, you’ll need a key with trading permissions. If you’re inclined, you can also have both.
Get Required Imports
import datetime import requests import pandas as pd from client import FtxClient from local_settings import ftx as settings
Using the FTX Market API
Using the Markets API is easy. The Markets API allows us to get all of the market data. We’ll be greeted with the following information when we make a request.
Get All Market Data
Let’s start by getting all available markets. We need to use the requests library to request the appropriate API endpoint.
# GET /markets api_url = '' api = '/markets' url = api_url+api url ''
Now we’ll use requests to get the market response data.
markets = requests.get(url).json() data = markets['result'] data
{'name': 'AAVE/USD', 'enabled': True, 'postOnly': False, 'priceIncrement': 0.01, 'sizeIncrement': 0.01, 'minProvideSize': 0.01, 'last': 146.85, 'bid': 147.07, 'ask': 147.21, 'price': 147.07, 'type': 'spot', ...
Since JSON format isn’t that easy to read, let’s convert it into a pandas dataframe.
df = pd.DataFrame(data) df = df.set_index('name') # using iloc to make it readable df.iloc[:,:4].head()
enabledpostOnlypriceIncrementsizeIncrement name AAVE/USDTrue False 0.010000 0.010 AAVE/USDTTrue False 0.010000 0.010 AUD/USDTrue False 0.000100 1.000 BAT/USDTrue False 0.000025 1.000 BCH/BTCTrue False 0.000001 0.001
Pretty easy, right? This will become second nature soon enough.
Get an Individual Market Data
You can use the following to get a single market.
# GET /markets/{market_name} market_name = 'ETH/USD' path = f'/markets/{market_name}' url = api_url + path url ''
Now let’s make the request and output the response as a dataframe.
res = requests.get(url).json() df = pd.DataFrame(res)['result'] df
ask 2478.3 baseCurrency ETH bid 2478.0 change1h 0.010768 change24h 0.044292 changeBod 0.017785 enabled True highLeverageFeeExempt True largeOrderThreshold 5000.0 last 2477.1 minProvideSize 0.001 name ETH/USD postOnly False price 2478.0 priceIncrement 0.1 quoteCurrency USD quoteVolume24h 88033400.0916 restricted False sizeIncrement 0.001 type spot underlying None volumeUsd24h 88033400.0916 Name: result, dtype: object
Get Historical Data
You can also get historical data for any of the markets. Let’s get the data as daily bars starting from 2022.
# GET /markets/{market_name}/candles?resolution={resolution}&start_time={start_time}&end_time={end_time} # Days is 60 seconds * 60 minutes * 24 resolution = 60*60*24 resolution
86400
start = datetime.datetime(2022,1,1).timestamp() start
1641013200.0
We’ll now construct the URL string and request as we’ve done above.
path = f'/markets/{market_name}/candles?resolution={resolution}&start={start}' url = api_url + path url
''
And we’ll put the data into the dataframe and clean up the index.
res = requests.get(url).json() df = pd.DataFrame(res['result']) df['date'] = pd.to_datetime(df['startTime']) df = df.set_index('date') df = df.drop(columns=['startTime', 'time']) df
open high low close volume date 2020-03-23 00:00:00+00:00130.355 136.935 129.625 136.775 0.0 2020-03-24 00:00:00+00:00136.770 144.210 132.855 138.790 0.0 2020-03-25 00:00:00+00:00138.785 142.980 132.750 136.115 0.0 2020-03-26 00:00:00+00:00136.105 140.125 133.615 138.890 0.0 2020-03-27 00:00:00+00:00138.890 141.955 129.320 131.425 0.0
Get Order Book Data
We can also get the order book at varying depths.
Let’s take a look at the order book for ETH/USD.
# GET /markets/{market_name}/orderbook?depth={depth} depth = 20 path = f'/markets/{market_name}/orderbook?depth={depth}' url = api_url + path url
''
res = requests.get(url).json() bids = pd.DataFrame(res['result']['bids']) asks = pd.DataFrame(res['result']['asks']) bids.columns = ['Bid Price', 'Bid Amount'] asks.columns = ['Ask Price','Ask Amount'] bids.head()
Bid PriceBid Amount02475.819.02512475.30.22422475.24.40032475.01.80042474.925.617
Let’s merge the two dataframes on their range indices.
And we can get the summary statistics using describe. Notice the depth as the count variable.
df.describe()
Bid PriceBid AmountAsk PriceAsk Amount count20.000000 20.000000 20.000000 20.000000 mean2469.810000 32.653350 2483.470000 91.586000 std5.285322 81.233445 4.152374 123.888884 min2460.500000 0.142000 2477.600000 0.018000 25%2464.675000 1.105000 2480.100000 1.944000 50%2471.650000 2.419000 2483.600000 4.700000 75%2474.600000 9.818750 2486.300000 217.624250 max2475.800000 291.635000 2490.600000 322.424000
Now let’s merge the two dataframes and rename the columns.
Get Trades
Getting the recent trades for any market is also easy.
# GET /markets/{market_name}/trades path = f'/markets/{market_name}/trades' url = api_url + path url
''
res = requests.get(url).json() df = pd.DataFrame(res['result']) df.head()
id price size side liquidation time 0231386382481.70.044 buy False 2022-01-28T20:34:04.660049+00:00 1231386322480.818.422 buy False 2022-01-28T20:34:00.089735+00:00 2231386252481.80.026 buy False 2022-01-28T20:33:59.123590+00:00 3231386242481.80.018 buy False 2022-01-28T20:33:59.123590+00:00 4231385252481.74.400 sell False 2022-01-28T20:33:22.179278+00:00
Working with FTX Futures
Now that you’ve learned how to use the Markets API, using the Futures API is just as easy. I’ll get you started. One thing to note is that futures are not available through the ftx.us API.
First, check out the futures API documentation. You’ll notice we need to make a get request to /futures. Let’s create the request URL and use requests to get the data.
url = '' res = requests.get(url).json() res
'success': True, 'result': [{'name': '1INCH-PERP', 'underlying': '1INCH', 'description': '1INCH Token Perpetual Futures', 'type': 'perpetual', 'expiry': None, 'perpetual': True, 'expired': False, ...
df = pd.DataFrame(res['result']) df.head()
df = pd.DataFrame(res['result']) # Using iloc to make it readable df.iloc[:,:4].head()
name underlying description type 01INCH-PERP1INCH1INCH Token Perpetual Futures perpetual 11INCH-03251INCH1INCH Token March 2022 Futures future 2AAPL-0325AAPLApple March 2022 Futures future 3AAVE-PERPAAVEAave Perpetual Futures perpetual 4AAVE-0325AAVEAave March 2022 Futures future
The Bottom Line
FTX and its U.S. counterpart FTX.US are two of the best exchanges in the crypto space. If you’re interested in algo trading or simply looking for a great data source, FTX has an easy-to-use REST API to get you what you need. | https://analyzingalpha.com/ftx-rest-api-python | CC-MAIN-2022-33 | refinedweb | 1,714 | 69.89 |
Webpack simplifies web development by solving a fundamental problem: bundling. It takes in various assets, such as JavaScript, CSS, and HTML, and transforms them into a format that's convenient to consume through a browser. Doing this well takes a significant amount of pain away from web development.
It's not the most accessible tool to learn due to its configuration-driven approach, but it's incredibly powerful. The purpose of this guide is to help you get started with webpack and go beyond the basics.
Web browsers consume HTML, CSS, JavaScript, and multimedia files. As a project grows, tracking all of these files and adapting them to different targets (e.g. browsers) becomes too complicated to manage without help. Webpack addresses these problems. Managing complexity is one of the fundamental issues of web development, and solving this problem well helps significantly.
Webpack isn't the only available bundler, and a collection of different tools have emerged. Task runners, such as Grunt and Gulp, are good examples of higher-level tools. Often the problem is that you need to write the workflows by hand. Pushing that issue to a bundler, such as webpack, is a step forward.
Framework specific abstractions, such as create-react-app or @angular/cli, use webpack underneath. That said, there's still value in understanding the tool if you have to customize the setup.
Webpack takes another route. It allows you to treat your project as a dependency graph. You could have an index.js in your project that pulls in the dependencies the project needs through the standard
require or
import statements. You can refer to your style files and other assets the same way if you want.
Webpack does all the preprocessing for you and gives you the bundles you specify through its configuration and code. This declarative approach is versatile, but it's challenging to learn.
Webpack becomes an indispensable tool after you begin to understand how it works. This book exists to get through that initial learning curve and even go further.
This book has been written to complement the official documentation of webpack, and it can be considered a companion to it. The book helps you to get through the initial learning curve and go further.
You will learn to develop a composable webpack configuration for both development and production purposes. Advanced techniques covered by the book allow you to get the most out of webpack.
The book starts by explaining what webpack is. After that, you will find multiple chapters that discuss webpack from a different viewpoint. As you go through these chapters, you will develop your webpack configuration while at the same time learning essential techniques.
The book consists of the following parts:
Finally, there is a short conclusion chapter that recaps the main points of the book. It contains checklists of techniques from this book that allow you to go through your projects methodically.
The appendices at the end of the book cover secondary topics and sometimes dig deeper into the main ones. You can approach them in any order you want, depending on your interest.
The Troubleshooting appendix at the end covers what to do when webpack gives you an error. It includes a process, so you know what to do and how to debug the problem. When in doubt, study the appendix. If you are unsure of a term and its meaning, see the Glossary at the end of the book.
The book has been written mainly beginner and intermediate developers in mind. For experts that already know webpack well, there's value in the form of techniques. The book summaries included in each chapter and at the Conclusion chapter, make it fast to skim and pick up the ideas.
Especially at the beginning and intermediate levels it can make sense to follow the book tutorial and develop your own webpack configuration from scratch and then check the chapters that feel most relevant to you. The only expectation is that you have a basic knowledge of JavaScript, Node, and npm.
Even if you use webpack through an abstraction such as Create React App, it can be valuable to understand the tool in case you have to extend your setup one day. Many of the techniques discussed go beyond webpack itself and are useful to know in daily development if and when you have to optimize your web application or site for example.
The book uses several conventions to keep the content accessible. I've listed examples below:
This is a tip. Often you can find auxiliary information and further references in tips.
This is a warning that's highlighting unexpected behavior or a common problem point that you should know.
Especially in the early part of the book, the code is written in a tutorial form. For this reason, the following syntax is used:
// You might see insertionsconst webpack = require("webpack");// You might see deletions as wellconst { MiniHtmlWebpackPlugin } = require("mini-html-webpack-plugin");// Or combinations of bothconst { MiniHtmlWebpackPlugin } = require("mini-html-webpack-plugin");const webpack = require("webpack");// If content has been omitted, then ellipsis is used ...
Sometimes the code assumes addition without the highlighting for insertion and many examples of the book work without by themselves and I've crosslinked to prerequisites where possible.
You'll also see
code within sentences and occasionally important terms have been highlighted. You can find the definition of these terms at the Glossary.
Trailing commas are used in the book examples on purpose as it gives cleaner diffs for the code examples.
The book examples have been formatted using Prettier with
"printWidth": 68to make the examples fit the book pages.
The book uses a versioning scheme, and 2.6.2.
If you run into trouble or have questions related to the content, there are several options:
If you post questions to Stack Overflow, tag them using survivejs. You can use the hashtag #survivejs on Twitter for the same result.
I am available for commercial consulting. In my past work, I have helped companies to optimize their usage of webpack. The work has an impact on both developer experience and the end-users in the form of a more performant and optimized build.
You can find more related material from the following sources:
Big thanks to Christian Alfoni for helping me craft the first version of this book as this inspired the entire SurviveJS effort. The text you see now is a complete rewrite.
This book wouldn't be half as good as it is without patient editing and feedback by my editors Jesús Rodríguez, Artem Sapegin, and Pedr Browne. Thank you.
This book wouldn't have been possible without the original “SurviveJS - Webpack and React” effort. Anyone who contributed to it deserves my thanks. You can check that book for more accurate attributions.
Thanks to Mike “Pomax” Kamermans, Cesar Andreu, Dan Palmer, Viktor Jančík, Tom Byrer, Christian Hettlage, David A. Lee, Alexandar Castaneda, Marcel Olszewski, Steve Schwartz, Chris Sanders, Charles Ju, Aditya Bhardwaj, Rasheed Bustamam, José Menor, Ben Gale, Jake Goulding, Andrew Ferk, gabo, Giang Nguyen, @Coaxial, @khronic, Henrik Raitasola, Gavin Orland, David Riccitelli, Stephen Wright, Majky Bašista, Gunnari Auvinen, Jón Levy, Alexander Zaytsev, Richard Muller, Ava Mallory (Fiverr), Sun Zheng' an, Nancy (Fiverr), Aluan Haddad, Steve Mao, Craig McKenna, Tobias Koppers, Stefan Frede, Vladimir Grenaderov, Scott Thompson, Rafael De Leon, Gil Forcada Codinachs, Jason Aller, @pikeshawn, Stephan Klinger, Daniel Carral, Nick Yianilos, Stephen Bolton, Felipe Reis, Rodolfo Rodriguez, Vicky Koblinski, Pyotr Ermishkin, Ken Gregory, Dmitry Kaminski, John Darryl Pelingo, Brian Cui, @st-sloth, Nathan Klatt, Muhamadamin Ibragimov, Kema Akpala, Roberto Fuentes, Eric Johnson, Luca Poldelmengo, Giovanni Iembo, Dmitry Anderson , Douglas Cerna, Chris Blossom, Bill Fienberg, Andrey Bushman, Andrew Staroscik, Cezar Neaga, Eric Hill, Jay Somedon, Luca Fagioli, @cdoublev, Boas Mollig, Shahin Sheidaei, and many others who have contributed direct feedback for this book!
This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack. | https://survivejs.com/webpack/introduction/ | CC-MAIN-2020-40 | refinedweb | 1,340 | 53.81 |
First solution in Clear category for Feed Pigeons by vlad.bezden
''' food for all the
birds, the pigeons who arrived first ate first. Pigeons are hungry animals and
eat without knowing when to stop.
If I have N portions of bird feed, how many pigeons will be fed with at least
one portion of wheat?
Input: A quantity of portions wheat as a positive integer.
Output: The number of fed pigeons as an integer.
Precondition: 0 < N < 105.
'''
def checkio(number: int) -> int:
pigeons = 1
counter = 1
while number > pigeons:
number -= pigeons
counter += 1
if number < pigeons + counter:
break
pigeons += counter
return number if number > pigeons else pigeons
if __name__ == '__main__':
assert checkio(1) == 1, '1st example'
assert checkio(2) == 1, '2nd example'
assert checkio(3) == 2, '3rd example'
assert checkio(5) == 3, '4th example'
assert checkio(10) == 6, '5th example'
assert checkio(40) == 15, '6th example'
Feb. 4, 2018
Forum
Price
Global Activity
ClassRoom Manager
Leaderboard
Coding games
Python programming for beginners | https://py.checkio.org/mission/feed-pigeons/publications/vlad.bezden/python-3/first/share/65746cb79fea0423bacba561cd1c197f/ | CC-MAIN-2021-31 | refinedweb | 163 | 54.02 |
This C++ program prints maximum of two values using max algorithm. The function takes two objects as the parameters by const reference and the third parameter is optional which is a predicate. The predicate can be used for objects which can not be compared like primitive datatypes and hence can be compared on the basis of some key.
Here is the source code of the C++ program which prints maximum of two values using max algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to print maximum of two values using max() algorithm
*/
#include <iostream>
#include <algorithm>
int main()
{
int a, b;
std::cout << "Enter a = ";
std::cin >> a;
std::cout << "\nEnter b = ";
std::cin >> b;
std::cout << "\nMaximum of a and b is "
<< std::max(a, b) << std::endl;
}
$ a.out Enter a = 10 Enter b = 20 Maximum of a and b is 20 $ a.out Enter a =-40 Enter b = 20 Minimum of a and b is 20
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you wish to look at all C++ Programming examples, go to C++ Programs. | http://www.sanfoundry.com/cpp-program-print-maximum-value-using-max-algorithm/ | CC-MAIN-2017-47 | refinedweb | 195 | 61.16 |
Hi there,
I'm following along with your videos on how to use the ApiDataProvider and have hit a snag. I clearly see the data in MyData - 2015/01/01-2016/01/01 for EURUSD and Forex/FXCM minute data. Just like in the video.
public class BasicTemplateAlgorithm : QCAlgorithm
{
private Symbol _eurusd = QuantConnect.Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM);
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2015, 1, 7); //Set Start Date
SetEndDate(2016, 1, 1); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here:
// Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
// Futures Resolution: Tick, Second, Minute
// Options Resolution: Minute Only.
AddEquity("EURUSD", Resolution.Minute);
// There are other assets with similar methods. See "Selecting Options" etc for more details.
// AddFuture, AddForex, AddCfd, AddOption
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings(_eurusd, 1);
Debug("Purchased Stock");
}
}
}
My ApiDataProvider is correctly trying to fetch the data, but it keeps coming up with the error - Unable to remotely retrieve data for path ../../../Data/equity\usa\minute\eurusd\20151231_trade.zip. Please make sure you have the necessary data in your online QuantConnect data library.
The only thing I can see that looks wrong to me is _trade and not _quote. The MyData library seems to show the zip file named as _quote. I can't find where to edit this in the code. I found one area for fileDestination in the QuantConnect.ToolBox.QuantQuoteConverter,
var fileDestination = string.Format("{0}/equity/{1}/{2}/{3}_trade.zip", destinationDirectory, resolution, symbol, date.ToString("yyyyMMdd"));
but editing that didn't have the desired effect (so I reverted it).
Any ideas what I can do? | https://www.quantconnect.com/forum/discussion/3893/unable-to-remotely-retrieve-data/ | CC-MAIN-2020-05 | refinedweb | 331 | 50.43 |
Summary
In this article, Susanne Hupfer introduces you to distributed data structures -- the common set of building blocks that are used in practically every space-based program. She shows you how to build and use a versatile channel distributed data structure, and illustrates its use in a distributed MP3-encoding application.
The design of any space-based application typically revolves around one or more distributed data structures. These are data structures that exist in a space where multiple processes can access and work on them at the same time -- something that is often difficult to achieve in distributed computing models.
As Figure 1 below shows, message passing and remote method invocation systems usually sequester data structures behind a centralized manager process; therefore, any process that wants to manipulate the structures will have to wait its turn and ask the manager to perform the operation on its behalf. In other words, multiple processes can't truly access a data structure simultaneously in these conventional systems.
Distributed data structures take a very different approach that decouples the data from any one process. Distributed data structures are represented as collections of objects that, as I said earlier, can be accessed and modified by multiple processes concurrently. As Figure 2 suggests, processes can work on different pieces of the structure at the same time without getting in each other's way.
The design of any distributed data structure requires both a representation of the data structure and a protocol that processes follow to ensure that they can manipulate the structure safely and fairly. Now I'll explain how you can use entries to represent distributed data structures, and how you can use space operations to implement distributed protocols.
Let.
Unlike.
When people first see the JavaSpaces API, they often ask, "How can I get a list of all the entries in a space?" It's a legitimate concern, since programmers often want to iterate over a set of objects. The simple answer is that the API itself provides no way to iterate over all the entries in the space. You can think of a space itself as just a big bag of entries -- an unordered collection of objects. The good news is that you can impose your own structure on a space by building various ordered distributed data structures within it. Once you've done this, entries can be enumerated by performing simple operations on those data structures.
In the remainder of this article, I'll explore how to create and work with one very useful type of ordered distributed data structure -- a channel. You can think of a channel as an information pipe that takes in a series of objects at one end and delivers them at the other end in the same order. At the input end, there may be one or more processes piping in messages or requests. At the output end, there may be one or more processes reading or removing these objects.
Channels turn out to be very versatile data structures, and can be used to achieve a variety of communication patterns in JavaSpaces programs (refer to Chapter 5 of JavaSpaces Principles, Patterns, and Practice for more details). In the rest of this article, I'll walk step-by-step through the details of implementing one kind of channel distributed data structure, and show you how it is central to a real-world program -- a distributed MP3 encoding application. Before diving down into the details, I'll give an overview of the application we'll be building.
Most folks have heard of MP3, a wildly popular sound compression format. Sounds encoded in MP3 format almost match CDs in quality, but MP3 files are much smaller than the equivalent files on a CD. If you've ever played around with digital audio files, you may have performed encoding -- the process of taking uncompressed digital audio data (for example, wav files on your PC) and compressing them according to a specific compression scheme such as MP3. MP3 encoding can be a computationally intensive process, especially if the original wav file is large or you have a large collection of wav files to encode.
You might imagine submitting your wav files to a high-powered, net-connected MP3 encoding service that would perform the wav-to-MP3 encoding for you and return the MP3 data. If many users simultaneously send encoding requests to a single MP3 encoder, the requests would need to queue up until they could be serviced. However, since the encoding tasks are completely independent of each other, they lend themselves well to being serviced in parallel by a farm of MP3 encoders. By using a space, you can easily build a distributed MP3-encoding application; Figure 3 shows the architecture of the system.
At first, you might think that your distributed application should just use bags, as the compute server did. In other words, the application could revolve around a bag of MP3 requests (deposited by
MP3Requester processes and picked up by
MP3Worker processes) and a bag of MP3 results (deposited by
MP3Workers and picked up by
MP3Requesters). This scheme has one major drawback: there is no guarantee of fairness. In other words, there's no assurance that some newer encoding requests won't be serviced before older requests. In fact, some requests might languish forever and never get picked up, while others are serviced. Ideally, you'd like for encoding requests to be handled on a first-come, first-served basis, with a guarantee of eventually being serviced (provided that at least one MP3 worker remains up and running to perform encoding). It turns out that a channel distributed data structure is exactly what you need to accomplish those goals.
As you can see from Figure 3,
MP3Requester processes add MP3 encoding requests to the tail end of an MP3 Request channel, and
MP3Worker processes take the requests off the head end of the channel, in order. An
MP3Worker calls a piece of third-party software to perform the actual wav to MP3 encoding; when that software generates the MP3 data, the worker writes the data to a result bag in the space (you can assume for this example that the order in which results are picked up is not important). In the meantime, the
MP3Requester processes constantly monitor the space to pick up and display results that have been tagged for them.
Now that you have the aerial view of the application, I'll dive down into the details.
To implement the MP3 Request channel, you use an ordered collection of
MP3Request entries -- one for each request in the channel. Each
MP3Request entry holds its position in the channel. For instance, the third request to be added to the channel has a position of three (assuming that the request sequence starts at one).
Requests are added to the tail end of the channel, and taken away from the head end. You can use a tail entry to keep track of the end of the channel: it holds the position number of the last request in the channel, and it gets incremented before you append a new request to the channel. You'll also need a head entry to keep track of the front of the channel: it holds the position number of the first request in the channel, and every time a request is removed from the front, the head's position number is incremented to point to the next request.
Now I'll show how each
MP3Request in the channel will look.
The
MP3Request entry is defined as follows:
public class MP3Request implements Entry {
public String channelName; // recipient of the request
public Integer position; // position # of request in channel
public String inputName; // file path
public byte[] data; // content of the file
public String from; // who sent the request
public MP3Request() { // the no-arg constructor
}
public MP3Request(String channelName) {
this.channelName = channelName;
}
public MP3Request(String channelName, Integer position) {
this.channelName = channelName;
this.position = position;
}
public MP3Request(String channelName, Integer position,
String inputName, byte[] data, String from)
{
this.channelName = channelName;
this.position = position;
this.inputName = inputName;
this.data = data;
this.from = from;
}
}
Each
MP3Request entry contains five fields:
channelName,
position,
inputName,
data, and
from. The
channelName identifies the name of the channel to which the request belongs (which in this example will always be "MP3 Request"). The
position field specifies the integer position of the request in the channel. The
inputName holds the absolute path name to a wav file to encode (for example,
C:\Windows\Desktop\groovy-music.wav). The
data field is used to hold the raw byte content of that file. Finally, the
from field specifies the user who submitted the request.
You'll need both head and tail entries to keep track of the front and back ends of the channel, respectively. You can base both on the
Index entry defined here:
public class Index implements Entry {
public String type; // head or tail
public String channel;
public Integer position;
public Index() {
}
public Index(String type, String channel) {
this.type = type;
this.channel = channel;
}
public Index(String type, String channel, Integer position) {
this.type = type;
this.channel = channel;
this.position = position;
}
public Integer getPosition() {
return position;
}
public void increment() {
position = new Integer(position.intValue() + 1);
}
}
The
Index entry has three fields: a
type field to identify the type of index (whether the entry points to the head or tail of the channel), a
channel field that holds the name of the channel, and a
position field that contains the position number (of the head or tail element). You'll notice that this entry has three constructors and two convenience methods:
getPosition, which returns the position of the head or tail, and
increment, which increments the position by one.
You'll track the start and end of the channel using
Index entries as follows. Say your channel holds five
MP3Request entries, at positions one through five. In that case, the head index entry will hold position number one, and the tail index entry will hold position number five. When a new request is added to the tail end of the channel, the tail position is incremented by one. When a request is removed, it is taken away from the head end of the channel, which results in the head position being incremented by one. If requests are removed at a faster clip than new ones are added, eventually there will be just one request in the channel, with both the head and tail pointing to it. If that one remaining request is removed and the head is incremented, the head's position number will be greater than the tail's -- and that will indicate an empty channel. As long as the tail position is greater than or equal to the head position, you know there are requests in the channel.
Now I'll show how you create your (initially empty) channel. An administrator runs a
ChannelCreator application, which is defined like this:
public class ChannelCreator {
private JavaSpace space;
public static void main(String[] args) {
ChannelCreator creator = new ChannelCreator();
creator.createChannel(args[0]);
}
private void createChannel(String channelName) {
space = SpaceAccessor.getSpace();
Index head =
new Index("head", channelName, new Integer(1));
Index tail =
new Index("tail", channelName, new Integer(0));
System.out.println("Creating new channel " + channelName);
try {
space.write(head, null, Lease.FOREVER);
space.write(tail, null, Lease.FOREVER);
} catch (Exception e) {
System.out.println("Error creating the channel.");
e.printStackTrace();
return;
}
System.out.println("Channel " + channelName + " created.");
}
}
Notice that
ChannelCreator takes as an argument the name of the channel to be created, which in this case is "MP3 Request." When this application is run, the
main method takes the channel name and passes it to the
createChannel method. The job of
createChannel is straightforward: it sets up two
Index entries to mark the head and tail of the channel, and it writes them to the space. Since a new channel starts out empty,
createChannel sets up the tail entry with an index of zero and the head entry with an index of one (recall that when the tail position is less than the head position, you know you have an empty channel).
Once a channel exists, you are free to add requests to it. In order to add MP3 encoding requests to your MP3 Request channel, you run an
MP3Requester applet, whose interface is shown in Figure 4. To request MP3 encodings, you must fill in the topmost text field with a unique name that identifies yourself (you can use your email address, for example); this name will be used to identify your requests and results. You must also fill in the text field that asks for an absolute filename (say,
C:\Windows\Desktop\wavs\drpepper.wav) that you'd like to have encoded. Then you're ready to click on the Encode It! button, which causes the
MP3Requester to append the request to the MP3 Request channel.
Here's the code skeleton for the
MP3Requester applet:
public class MP3Requester extends Applet
implements ActionListener, Runnable
{
private JavaSpace space;
private Thread resultTaker;
private String from; // unique name for person requesting MP3s
. . . variables for user interface components
public void init() {
space = SpaceAccessor.getSpace();
// spawn thread to handle collecting & displaying results
if (resultTaker == null) {
resultTaker = new Thread(this);
resultTaker.start();
}
. . . user interface setup
}
// "Encode It!" button pressed
public void actionPerformed(ActionEvent event) {
from = userTextField.getText();
String inputName = fileTextField.getText();
. . .
// we'll package the file's raw data in the entry
byte[] rawData = null;
rawData = Utils.getRawData(inputName); // open file & read bytes
// append an MP3 request to the channel
if (rawData != null) {
append("MP3 Request", inputName, rawData, from);
}
}
. . . append method goes here
// thread that loops, taking & displaying MP3 results
public void run() {
. . .
}
}
Whenever the Encode It! button is pressed, the
actionPerformed method gets called to add the MP3 encoding request to the MP3 Request channel. This method first extracts the unique username and the filename that you typed into the applet's text fields. The method opens the wav file and obtains its raw byte data. Then the
append method (which I'll explain shortly) is called to add the request to the channel, passing it the name of the channel ("MP3 Request"), the filename to encode, the raw data from the file, and the name of the user making the request.
Another thing to note about this applet is that it spawns a result taker thread. The
run method of this thread loops continuously, removing MP3 results from the space and displaying the resulting MP3 filenames in the applet's GUI. (This functionality needs to run in its own thread, since the main thread of the applet needs to be available and responsive to GUI events such as button clicks.)
Let's take a closer look at the
append method that adds requests to the tail end of a channel. That method obtains the position number of the tail, increments it, and stamps the new request with that number.
First, you'll define a
getRequestNumber method that obtains a position number for the new request:
private Integer getRequestNumber(String channel) {
try {
Index template = new Index("tail", channel);
Index tail = (Index) space.take(template, null, Long.MAX_VALUE);
tail.increment();
space.write(tail, null, Lease.FOREVER);
return tail.getPosition();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
In this method, you first create an
Index template, specifying that you're looking for a tail index in a certain channel (but leaving the position number unspecified, to serve as a wildcard). Then you call
take to remove the tail entry for that channel, waiting as long as necessary. Once you've retrieved the tail entry for the channel, you increment the tail and write it back into the space. You return the new position number of the tail to the caller, to be used as the position number of the new request. Since the tail entry for a channel starts out at position zero, the first time you call this method for a channel, position one will be returned to use for the first request.
Now you'll make use of
getRequestNumber to implement the
append method:
private void append(String channel, String inputName,
byte[] rawData, String from) {
Integer num = getRequestNumber(channel);
MP3Request request =
new MP3Request(channel, num, inputName, rawData, from);
try {
space.write(request, null, Lease.FOREVER);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
The
append method takes the name of the channel ("MP3 Request"), the filename to encode, the raw data from the file, and the name of the user making the request. Here you first call
getRequestNumber, passing it the channel name, to increment the tail and obtain a position number for the new request. Then you create a new
MP3Request entry (with the given channel name, position number, filename, raw data, and user's name) and write it into the space.
Now that you've seen the details of the MP3 Requester and examined how it appends new MP3 encoding requests to your MP3 Request channel, we'll investigate what happens to those requests in the channel.
An administrator will start up one or more MP3 workers. Each worker repeatedly removes an MP3 encoding request from the channel's head, calling a third-party program to perform the wav-to-MP3 encoding, and then constructs and writes an
MP3Result entry into the space (which all MP3 Requesters are monitoring). Here's the basic outline of the
MP3Worker code:
public class MP3Worker {
private JavaSpace space;
private String channel;
public static void main(String[] args) {
MP3Worker worker = new MP3Worker();
worker.startWork();
}
public void startWork() {
space = SpaceAccessor.getSpace();
channel = "MP3 Request";
while(true) {
processNextRequest();
}
}
. . . other method definitions
}
As you can see from the
main and
startWork methods, the worker enters a loop, in which it continually calls the
processNextRequest method, which is defined as follows:
private void processNextRequest() {
Index tail = readIndex("tail", channel);
Index head = removeIndex("head", channel);
if (tail.position.intValue() < head.position.intValue()) {
// there are no requests
writeIndex(head);
return;
}
// get the next request & increment the head:
MP3Request request = removeRequest(channel, head.position);
head.increment();
writeIndex(head);
if (request == null) {
System.out.println("Communication error.");
return;
}
// retrieved an MP3 request, so call third-party freeware
// program to perform the conversion from WAV to MP3
String inputName = request.inputName;
byte[] inputData = request.data;
byte[] outputData = null;
String tmpInputFile = "./tmp" + request.position + ".wav";
String tmpOutputFile = "./tmp" + request.position + ".mp3";
Process subProcess = null;
Utils.putRawData(inputData, tmpInputFile);
try {
String[] cmdArray = { "\"C:\\Program Files\\BladeEnc\\BladeEnc\"",
"-quit", "-quiet", "-progress=0", tmpInputFile, tmpOutputFile};
subProcess = Runtime.getRuntime().exec(cmdArray);
subProcess.waitFor();
} catch (Exception e) {
. . .
return;
}
. . .
// put MP3 result into the space
outputData = Utils.getRawData(tmpOutputFile);
MP3Result result = new MP3Result(inputName, outputData, from);
try {
space.write(result, null, Lease.FOREVER);
. . .
} catch (Exception e) {
. . .
return;
}
}
The
processNextRequest method first reads the tail index for the MP3 Request channel, but leaves it in the space. Then it removes the head index and compares the two positions. If the tail's position is less than the head's position, that means the channel is currently empty and there are no encoding requests to process. If that is the case, this method simply returns the unmodified head index to the space and returns.
However, if there are requests in the channel,
processNextRequest calls
removeRequest to remove the request entry at the head, increments the head index, and then writes the updated head index back into the space. Then the method is ready to obtain the wav data from the request entry and perform the actual conversion. Let's look at how that happens.
The method extracts the input filename and wav input data from the request entry. It also constructs two temporary local files -- one to hold the wav input data and one to hold the MP3 output data -- and writes the wav input data into the temporary input file. Next the method makes a call to an external, third-party freeware program that takes the wav input file, encodes it into the MP3 format, and writes the resulting MP3 data to the temporary output file.
At that point, our method constructs an
MP3Result (which I'll look at shortly) using the generated MP3 data, and writes it to the space.
For the sake of completeness, here are the definitions of a few helper methods used in the code. Their implementations should be fairly straightforward:
// remove a request entry from the channel
private MP3Request removeRequest(String channel,
Integer position)
{
MP3Request template = new MP3Request (channel, position);
MP3Request request = null;
try {
request = (MP3Request)
space.take(template, null, Long.MAX_VALUE);
return request;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// remove an index ("head" or "tail") from the channel
private Index removeIndex(String type, String channel) {
Index template = new Index(type, channel);
Index index = null;
try {
return (Index)space.take(template, null, Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// read an index ("head" or "tail") from the channel
private Index readIndex(String type, String channel) {
Index template = new Index(type, channel);
Index index = null;
try {
return (Index)space.read(template, null, Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// write a head or tail index to the channel
private void writeIndex(Index index) {
try {
space.write(index, null, Lease.FOREVER);
} catch (Exception e) {
e.printStackTrace();
}
}
As the workers obtain MP3 data, they wrap the results in
MP3Result entries and write those into the space for MP3 Requesters to find. Here's how an
MP3Result entry is defined:
public class MP3Result implements Entry {
public String inputName; // name of file that was encoded
public byte[] data; // raw MP3 data
public String from; // who sent the request
public MP3Result() { // the no-arg constructor
}
public MP3Result(String from) {
this.from = from;
}
public MP3Result(String inputName, byte[] data, String from) {
this.inputName = inputName;
this.data = data;
this.from = from;
}
}
The result entry is straightforward: it holds the filename that was encoded, the bytes representing the MP3 encoding, and a
String representing the name of the person who requested the MP3.
As I mentioned earlier, each MP3 Requester has a thread that loops continuously, removing MP3 results from the space and displaying them. To complete your understanding of the whole picture, here's the code that accomplishes this:
// thread in the MP3Requester that loops,
// taking & displaying links to MP3 results
public void run() {
MP3Result template = new MP3Result(from);
MP3Result result = null;
String outputName = ""; // name of MP3 output file
while(true) {
try {
result = (MP3Result)
space.take(template, null, Long.MAX_VALUE);
int pos = result.inputName.indexOf(".wav");
outputName = result.inputName.substring(0, pos) + ".mp3";
Utils.putRawData(result.data, outputName);
displayResult(outputName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This method first constructs an
MP3Result template, supplying only the username that was entered into the requester's GUI. Then the method enters a loop, looking for any
MP3Result entries that are tagged with the requester's name. Whenever an entry is found, it is removed from the space, and the raw MP3 data is written to an output file that corresponds to the input file the user specified. For instance, if the user specified
C:\Windows\Desktop\wavs\drpepper.wav as the file to encode, the resulting MP3 data is written to
C:\Windows\Desktop\wavs\drpepper.mp3. Then
displayResult is called to display the name of the file in the GUI (see the results area of Figure 4); if the user double clicks on the MP3 filename, an MP3 player (currently hardcoded in the application as
C:\Program Files\winamp\winamp) will be launched to play the MP3 file.
With this article, we've created a real-world distributed application that revolves around two distributed data structures -- an ordered MP3 Request channel holding
MP3Request entries, and an unordered bag holding
MP3Result entries. The channel distributed data structure is versatile; with small changes to the protocols, it can form the basis of a variety of communication patterns. For instance, if workers don't remove the entries in the channel but simply read them, the channel can form the basis of an archived chat stream in the space. To explore channels further, refer to JavaSpaces Principles, Patterns, and Practice.
You might think of the pattern in this example as a variation on the master/worker pattern Eric Freeman and I used in earlier columns. Recall that, in the master/worker pattern, a single master process deposits tasks into a task bag in the space, and worker processes pick up arbitrary tasks, compute them, and write the results into a result bag. Now, in our MP3 encoder architecture, there are potentially many requester processes that append requests to an ordered channel of requests, and potentially many workers that pick up the requests in order and process them. Just as in the master/worker pattern, the workers write the results into a result bag in the space. The requester processes pick up just the results earmarked for them. You could apply the pattern developed here to a wide variety of domains: writers simply add tasks (or requests for services) to the channel, and worker processes remove and process the tasks (computing them or providing some other service). The channel distributed data structure allows requests to be processed in a fair, first-come, first-served manner.
It's also worth noting, once again, that space-based communication decouples the senders and receivers of information and promotes a loosely coupled communication style in which senders and receivers don't interact directly, but rather communicate through distributed data structures in a space. In this distributed MP3 encoding example, the requesters don't care which worker or backend server ultimately processes their request; they only care that they get a result back. Conversely, the workers don't care who wants MP3 data; they just know how to take the request and deliver a result back to the space. Loosely coupled applications tend to be more flexible and scalable than tightly coupled ones. Indeed, in this case you can deploy as many workers on as many machines as you would like, without revising or recompiling any code.
Distributed data structures are the building blocks of space-based distributed programs. There is no limit to the variety and complexity of distributed data structures you can build using entries: distributed linked lists, hierarchical tree structures, graphs, and so on. Now that you've seen a few distributed data structures and their power, you should be ready to start inventing new and useful structures for your own applications.
"Make Room for JavaSpaces, Part IV" by Susan Hupfer was originally published by JavaWorld (), copyright IDG,
October 2000. Reprinted with permission. | https://www.artima.com/jini/jiniology/js6P.html | CC-MAIN-2018-13 | refinedweb | 4,414 | 52.49 |
<p>I know there is godep, but I am curious why go doesn't natively support versions via git url stub. Something along these lines</p> <pre><code>import ( "os" "github.com/uname/myrepo1" "github.com/uname/myrepo2@dev" "github.com/uname/myrepo2@c8ufj1" ) </code></pre> <p>That seems to fit go idioms fairly well. Is there a place that the language accepts feature requests? I wouldn't mind implementing this given a good direction to go in.</p> <hr/>**评论:**<br/><br/>tv64738: <pre><p>This horse has been beaten to death on the mailing list.</p> <p>What would happen if I import <code>database/sql@1</code> and you import <code>database/sql@2</code>?</p></pre>flydonkey: <pre><p>Throw a compiler error?</p></pre>agentargo: <pre><p>That seems totally reasonable to me</p></pre>danredux: <pre><p>I feel like I'm missing something, but why would it be an issue if people imported, hell, BOTH of those in the same package?</p> <p>Sure, you'd have to rename one on import.. but that's all.</p></pre>calebdoxsey: <pre><p>Libraries often have state or initialization with side effects. For example if you imported two MySQL libraries the latter would probably overwrite the former.</p> <p>You also wouldn't be able to transfer data between the two different versions because the types would be different. For example suppose you were using a redis library and passed around a redis connection everywhere in your own code. If you had two versions of redis included which redis connection would you define for you functions? (And how would you convert one type of redis connection to another?)</p></pre>danredux: <pre><p>I can't think of a situation where importing two versions of the same package would cause problems with overwriting initalization/state, excepting I suppose if some third package has some option that is changed between sql versions, and the value that sql@2 sets is incompatible with the value that sql@1 sets.</p> <p>However the solution to this is quite simply- reset the "import" cache when importing a new version. IE, sql@1 and sql@1 get two entirely separate compilations of each package they import.</p> <p>However, there's almost no state in packages at the top-level and this might not even be a problem. The packages could simply be aware that, to support versioning, they may not rely on third-party package state.</p> <p>Edit: In fact, this is already an issue! Two parts of your program (or two packages) can both import and configure a third-party package's state. Nothing changes from versioning this way.</p></pre>Yojihito: <pre><p>Why not just use <a href="mailto:sql@1.doSomething" rel="nofollow">sql@1.doSomething</a>() and <a href="mailto:sql@2.doAnotherThing" rel="nofollow">sql@2.doAnotherThing</a>()?</p></pre>danredux: <pre><p>Because you want to simplify the common case, always.</p> <p>Importing a version should, by default, go to a simple namespace.</p> <p>If you wanted to import both versions, you could import them with a name like "sqlV1" and "sqlV2".</p></pre>agentargo: <pre><p>I'd love to read those chains if you have links to them.</p> <p>The case where you have two branchs and each import a different version. I'd argue it's even more clear at merge time if you have to explicitly resolve the conflict to make sure you match the correct API.</p> <p>The other case being you literally have two import in the same file with two different versions. That seems like it should be a compiler error unless you explicitly rename the imports</p> <p>So this is a compiler error</p> <pre><code>import ( "database/sql@1" "database/sql@2" ) </code></pre> <p>and this being OK</p> <pre><code>import ( sql_1 "database/sql@1" sql_2 "database/sql@2" ) </code></pre> <p>Again maybe I'm missing something here that is covered in the mailing list, but that behavior seems totally reasonable to me.</p> <p>Other languages handle the versioning outside of the code and pip requirements would throw an error if you tried to import a lib twice. Having the git path linked creates a bit of a misnomer to me if you can only reference head. I'd say that the import should be just the name and the external version management tool should define the location.</p> <p>EDIT:</p> <p>Found this thread <a href="" rel="nofollow"></a></p></pre>gdey: <pre><p>It's because the import paths are opaque to the go compiler. There are projects that provide you with versioning. <a href="" rel="nofollow">gopkg.in</a> is a service that allows you to have stable versioned packages. </p> <p>For example the YAML package is released this way. gopkg.in/yaml.v1 — get's you version one of the yaml package. And because of the way imports work, the package name is <em>yaml</em>.</p></pre>agentargo: <pre><p>Isn't the definition of an opaque pointer to hide implementation details? So if the name is opaque, the library loader could choose to interpret the path with the @ symbol to point to branch/tag/commit. I could be misinterpreting that though.</p> <p>This seems like such a hack to create a URL with an implicit version that points to the correct commit.</p></pre> | https://studygolang.com/resources/1949 | CC-MAIN-2018-39 | refinedweb | 921 | 56.35 |
*I'm not exactly sure if this is the right place for this*
Hello, I'm new here. I'm teaching myself c++ and I decided to make a simple text RPG. I'm coding a "battle engine" first and I created two instances of the class cTheo to test it. It compiles with no problems, but when I run it, this is what I get:
This is the code. If it helps, I'm using VStudio 6.0 on WinXP Pro on a 533 Celeron.This is the code. If it helps, I'm using VStudio 6.0 on WinXP Pro on a 533 Celeron.Code:Linking... Cpp1.obj : error LNK2005: "void __cdecl Choice(class cTheo)" (?Choice@@YAXVcTheo@@@Z) already defined in Battle.obj Cpp1.obj : error LNK2005: "void __cdecl Action(class cTheo,class cTheo)" (?Action@@YAXVcTheo@@0@Z) already defined in Battle.obj Cpp1.obj : error LNK2005: "char choice" (?choice@@3DA) already defined in Battle.obj Cpp1.obj : error LNK2005: "class cTheo theo" (?theo@@3VcTheo@@A) already defined in Battle.obj Cpp1.obj : error LNK2005: "class cTheo allah" (?allah@@3VcTheo@@A) already defined in Battle.obj Debug/Cpp1.exe : fatal error LNK1169: one or more multiply defined symbols found Error executing link.exe.
Any help would be greatly appreciated.Any help would be greatly appreciated.Code:<main> #include "Battle.cpp" int main() { bool partyIsAlive = true; Battle(partyIsAlive); if (partyIsAlive == true) cout << victory; else cout << defeat; return 0; } <Battle.cpp> #include <iostream> #include <cstdlib> #include <string> #include <ctime> using namespace std; class cTheo { public: int hitPoints, strength; string name; cTheo::cTheo(int h, int s, string n) { cTheo::hitPoints = h; cTheo::strength = s; cTheo::name = n; } }; //Function Prototypes void Choice(cTheo); void Action(cTheo, cTheo); //Globals and Constants const string victory = "Party has Survived!\n"; const string defeat = "Party has been Defeated!\n"; char choice; //Syntax cTheo -name- (hitPoints, strength, name) cTheo theo(19, 10, "Theo"); cTheo allah(20, 15, "Allah"); bool Battle(bool& survived) { survived = true; //I would like to implement some mechanism that takes speed into account while (theo.hitPoints > 0 && allah.hitPoints > 0) { //Theo goes first Choice(theo); Action(theo, allah); //Followed by Allah Choice(allah); Action(allah, theo); //If I lose in my epic and blasphemous battle... if (theo.hitPoints = 0) survived = false; } return (survived); } //X is the attacker void Choice(cTheo x) { cout << x.name << "'s turn" << endl; do{ cout << "Attack (A) Defend (D) "; cin >> choice; }while((choice != 'A') && (choice != 'D') && (choice != 'a') && (choice != 'd')); //I need to fix this do-while statement. } //X is the attacker, Y is the receiver void Action(cTheo x, cTheo y) { srand(time(NULL)); int i = rand(); //Switch used b/c I want to a more options eventually switch (choice) { case ('A'): case ('a'): cout << x.name << " is attacking. \n"; y.hitPoints -= i + 3; break; case ('D'): case ('d'): cout << x.name << " is defending. \n"; cout << "On a later date, this will actually do something!\n"; break; } }
P.S. Please don't be offended by my use of Allah. It's not malicious -- I would just as quickly use Jesus/Bob/Jebus/Buddha/etc. | http://cboard.cprogramming.com/game-programming/54488-help-vcplusplus-6-0-my-code-error.html | CC-MAIN-2014-42 | refinedweb | 516 | 68.87 |
Red Hat Bugzilla – Full Text Bug Listing
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.2)
Gecko/20040803 Galeon/1.3.17
Description of problem:
When I compile this program:
-------------------------------
#include <stdio.h>
#include <libpq-fe.h>
int main(int argc,char **argv){
int i;
PGconn *conn;
PGresult *res;
for(i=0;i<1000000;i++){
conn=PQconnectdb("dbname=spintest");
res=PQexec(conn,"select * from spintest");
printf("%d\r",i);
PQclear(res);
PQfinish(conn);
}
printf("\n");
return 0;
}
-------------------------------
And run it, I'm seeing constant increase in the memory usage of the
program, around 4 kB every second on my 2 GHz P4-based Celeron
machine. I am either doing something incredibly stupid in the above
code (I would not be surprised ;-), or there is a memory leak in the
library.
Version-Release number of selected component (if applicable):
postgresql-7.4.2-1
How reproducible:
Always
Steps to Reproduce:
1. Compile the above program on FC2.
2. Run it.
3. Observe memory usage in top.
Actual Results: Memory usage increases.
Expected Results: Memory usage should be steady.
Additional info:
Just to put things in perspective, by about 600,000 iterations, the
memory leak is almost 9 MB!
I couldn't reproduce this in a first attempt. Do you have any connection-related settings
that libpq is making use of beyond what is shown in your test program? For instance,
PGfoo environment variables, or a .pgpass file?
I have no .pg* files at all. There are no PG* environment variables.
As far as I'm aware, there is nothing special about this user account
in terms of PostgreSQL.
The only thing in pg_hba.conf that is not commented out is this:
---------------------------------
local all all ident sameuser
---------------------------------
The contents of postgresql.conf is this:
---------------------------------
max_connections = 100
shared_buffers = 1000 # min 16, at least max_connections*2,
8KB each
lc_messages = 'en_AU.UTF-8' # locale for system error
message strings
lc_monetary = 'en_AU.UTF-8' # locale for monetary formatting
lc_numeric = 'en_AU.UTF-8' # ou locale for number formatting
lc_time = 'en_AU.UTF-8' # locale for time formatting
---------------------------------
Pretty much the defaults. Is there anything else you need?
BTW, I'm going to try this on another FC2 machine, just to see if I
can replicate it there.
Created attachment 103471 [details]
Table creation script
This is the script used to create the table used in the test. Before that, the
database also needs to be created, of course, and user (which has to exist) has
to be granted select privilege on the table.
I'm seeing the same thing on my other FC2 system. Same version of
PostgreSQL RPM, as shipped with FC2.
On this machine, there is no .pg* files. Here, the environment
variables are set like this:
PGLIB=/usr/lib/pgsql
PGDATA=/var/lib/pgsql
I'm guessing this is from /etc/profile.d/postgresql.sh, which is
something that's been hanging around from previous version of
PostgreSQL (this particular box has been upgraded all the way from Red
Hat Linux 5.0 :-).
On both systems, the program has been compiled like this:
gcc -o test test.c -lpq
Sorry, I forgot to mention that before.
I've just spent a couple hours trying to duplicate this, with no success at all.
I think possibly there is some version difference between your machines and the one I was
testing on. What version of glibc are you using, for instance?
Another line of attack is to try to find out what makes the leak go away. For instance, if
you use something besides IDENT authentication, does the leak go away?
Both machines are simply FC2 installations, fully updated. I don't
normally upgrade RPMS on those machines from development branches of
Fedora. The only difference may be RPMS that don't exist in Fedora by
default.
I'll install a brand new system, pure vanilla FC2, and then try again.
BTW, on the first machine I mentioned, I also have problems with
krb5-libs functions, called from pqlib code. They intermittently
segfault, but I was unable to pinpoint the exact cause (and therefore
never reported that as a bug). I have seen some recent security
advisories with double-free in krb5, which does look very similar to
what I have been experiencing (all my segfaults were in krb5 calling
free()). However, to replicate those tests, a complicated set of
software needs to be set up (httpd, libapreq2, mod_spin etc.), making
in unpractical for you guys to test.
That's how I came up with this small example - trying to replicate
those segfaults with a straightforward test. Turns out, it ended up in
memory leaks. Go figure... BTW, I have experienced memory leaks of
similar nature in my mod_spin applications, which do not appear unless
I keep opening and closing PostgreSQL connections.
I'll keep you posted.
I found this sentence in the release notes for 7.4.3:
Fix temporary memory leak when using non-hashed aggregates (Tom)
That's on this page:
Could that have anything to do with what I'm seeing?
No.
Just testing on the third machine (which doesn't even run a PostgreSQL
server, only has libs and devel, so all request are failing for sure)
and I'm seeing the same thing. Still have to do the vanilla install to
verify...
Hm, just to confirm I read that right: you have a loop in which PQconnectdb is failing to
begin with (never mind the PQexec), and it's still leaking memory?
I'm still clueless why I can't reproduce this :-(. I suspected from the start that the leak is
associated with the connection and not with the query (please confirm whether it still leaks
if you take out the PQexec and PQclear lines) but I sure do not know why ...
Yep, exactly. I have removed PQexec() and PQclear() calls altogether
and recompiled. Still leaks. I'll attach the output of two pmap runs,
just so you can see where exactly the memory goes. Not sure if that
helps though.
I did run strace and the only thing I can see in relation to memory
allocation is repeated calls to mmap2() by krb5-libs. There is a
matching munmap() and it does appear to be successful, so I'm not sure
if it's related at all. I'll attach a snippet of that too.
Created attachment 103662 [details]
strace output of around 10,000 iterations
Created attachment 103663 [details]
first pmap output
Created attachment 103664 [details]
second pmap output (see diff in comment)
Here is a diff of the first and second pmap output, which shows where the
memory is going:
--------------------------------
--- test-pmap-1.txt 2004-09-10 11:12:12.603360095 +1000
+++ test-pmap-2.txt 2004-09-10 11:12:30.256620406 +1000
@@ -46,9 +46,9 @@
06300000 12K rw--- /libssl.so.0.9.7a
08048000 4K r-x-- /test
08049000 4K rw--- /test
-08d55000 644K rw--- [ anon ]
+08d55000 1028K rw--- [ anon ]
f6feb000 16K rw--- [ anon ]
-f6fff000 4K rw--- [ anon ]
+f6ffe000 8K rw--- [ anon ]
fee95000 1452K rw--- [ stack ]
ffffd000 4K ----- [ anon ]
- total 5820K
+ total 6208K
--------------------------------
Created attachment 103665 [details]
All RPM packages installed on this system
This particular system is an HP Vectra VL 420 DT, Pentium 4, 1.7 GHz with 384
MB or RAM and 20 GB disk. In terms of glibc, I guess it would be running i686
version of it.
Output of "ldd ./test" looks like this:
--------------------------------
libpq.so.3 => /usr/lib/libpq.so.3 (0x00618000)
libc.so.6 => /lib/tls/libc.so.6 (0x0011a000)
libssl.so.4 => /lib/libssl.so.4 (0x062cf000)
libcrypto.so.4 => /lib/libcrypto.so.4 (0x061a1000)
libkrb5.so.3 => /usr/lib/libkrb5.so.3 (0x00c70000)
libcom_err.so.2 => /lib/libcom_err.so.2 (0x02e8e000)
libcrypt.so.1 => /lib/libcrypt.so.1 (0x00b5c000)
libresolv.so.2 => /lib/libresolv.so.2 (0x02dde000)
libnsl.so.1 => /lib/libnsl.so.1 (0x00b8b000)
libpthread.so.0 => /lib/tls/libpthread.so.0 (0x02dca000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x00101000)
libgssapi_krb5.so.2 => /usr/lib/libgssapi_krb5.so.2 (0x062b8000)
libk5crypto.so.3 => /usr/lib/libk5crypto.so.3 (0x06294000)
libdl.so.2 => /lib/libdl.so.2 (0x02e71000)
libz.so.1 => /usr/lib/libz.so.1 (0x02df2000)
--------------------------------
I didn't mention this and it may be important, pmap and strace outputs
are from *different* runs. If you want me to do it on the same one,
let me know. And, sorry for so many posts today... :-(
Ah-hah. I've been able to reproduce this problem on one FC2 machine
in the Toronto office, but the one I first tried does not have it!
They are running different kernels:
no bug: 2.6.8-1.521
bug: 2.6.8-1.521smp
but I suppose the problem is actually in userspace. The only package
that libpq depends on that is different between the two is krb5:
no bug seen with 1.3.3-7, bug seen with 1.3.4-6. So your gut
suspicion of krb5 seems confirmed.
Some further digging shows that each time through the loop, libpq
tries to get the username from Kerberos. On both of my test systems,
krb5_cc_get_principal() fails with "No credentials cache found". It
appears that something gets leaked in that code path in 1.3.4-6, but
not in 1.3.3-7.
I'm going to reassign this to the krb5 package owner and see what
he/she has to say. It's possible that the true bug is still in libpq,
but if so it now takes the form of misuse of the kerberos library, so
I need a hand anyway ...
Awesome! Thanks for all your help.
Just for the record, this is how I get pinched by segfaults when
running a lot of requests to Apache that runs my software inside it
(mod_spin + spin_app):
---------------------------------
(gdb) set args -X
(gdb) r
Starting program: /usr/local/apache2/bin/httpd -X
[Thread debugging using libthread_db enabled]
[New Thread -151078176 (LWP 4395)]
Detaching after fork from child process 4404.
[New Thread -151295056 (LWP 4405)]
[New Thread -161784912 (LWP 4406)]
[New Thread -172274768 (LWP 4407)]
[New Thread -182764624 (LWP 4408)]
[New Thread -193254480 (LWP 4409)]
[Thread -151295056 (zombie) exited]
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread -161784912 (LWP 4406)]
0x00000000 in ?? ()
(gdb) bt
#0 0x00000000 in ?? ()
#1 0x043a40a9 in krb5_cc_close (context=0x935f3c8, cache=0x935f3c8)
at ccfns.c:61
#2 0x0084c871 in pg_krb5_init (
PQerrormsg=0xf65b5380 "pg_krb5_init: krb5_cc_get_principal: No
credentials c
ache found\n") at fe-auth.c:329
#3 0x0084c92f in pg_krb5_authname (PQerrormsg=0x935f3c8 "\001")
at fe-auth.c:348
#4 0x0084d20b in fe_getauthname (
PQerrormsg=0xf65b5380 "pg_krb5_init: krb5_cc_get_principal: No
credentials c
ache found\n") at fe-auth.c:731
#5 0x0084f8dd in conninfo_parse (conninfo=0x935f3c8 "\001",
errorMessage=0xf3c00780) at fe-connect.c:2720
#6 0x0084d2fc in connectOptions1 (conn=0xf3c00480, conninfo=0x935f3c8
"\001")
at fe-connect.c:328
#7 0x0084d295 in PQconnectStart (conninfo=0x935f3c8 "\001")
at fe-connect.c:287
#8 0x0084d242 in PQconnectdb (conninfo=0x935f3c8 "\001") at
fe-connect.c:245
#9 0x00115257 in rxv_spin_db_connect (pool=0x93a7eb0, cpool=0x0,
conninfo=0xeb5a15 "dbname=spintest", type=1 '\001') at db.c:255
#10 0x00eb4f96 in rxv_spin_service (ctx=0x93a94a8) at app.c:61
#11 0x00ccf9a1 in handler (r=0x93a7ee8) at mod_spin.c:390
#12 0x0807f40a in ap_run_handler (r=0x93a7ee8) at config.c:151
#13 0x0807f91e in ap_invoke_handler (r=0x93a7ee8) at config.c:358
#14 0x0806d1a7 in ap_process_request (r=0x93a7ee8) at http_request.c:246
#15 0x080692b5 in ap_process_http_connection (c=0x931add0) at
http_core.c:250
#16 0x08088472 in ap_run_process_connection (c=0x931add0) at
connection.c:42
#17 0x0807c5f1 in process_socket (p=0x931aca8, sock=0x931ace0,
my_child_num=71132672, my_thread_num=154530760,
bucket_alloc=0x9322cc8)
at worker.c:520
#18 0x0807cc3a in worker_thread (thd=0x92d5fa0, dummy=0x935f3c8)
at worker.c:834
#19 0x00d22068 in dummy_worker (opaque=0x935f3c8) at thread.c:88
#20 0x02f6d98c in start_thread () from /lib/tls/libpthread.so.0
#21 0x0237416a in clone () from /lib/tls/libc.so.6
(gdb)
---------------------------------
This is Apache 2.0.50 with worker MPM, but it is just a single thread
doing everything (due to -X). When I go up the call stack a bit, to
verify what is being passed into PQconnectdb() function by my software
(to eliminate any stupidites on my behalf), this is what I see:
---------------------------------
(gdb) up
#1 0x043a40a9 in krb5_cc_close (context=0x935f3c8, cache=0x935f3c8)
at ccfns.c:61
61 return cache->ops->close(context, cache);
(gdb) up
#2 0x0084c871 in pg_krb5_init (
PQerrormsg=0xf65b5380 "pg_krb5_init: krb5_cc_get_principal: No
credentials
cache found\n") at fe-auth.c:329
329 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
(gdb) up
#3 0x0084c92f in pg_krb5_authname (PQerrormsg=0x935f3c8 "\001")
at fe-auth.c:348
348 if (pg_krb5_init(PQerrormsg) != STATUS_OK)
(gdb) up
#4 0x0084d20b in fe_getauthname (
PQerrormsg=0xf65b5380 "pg_krb5_init: krb5_cc_get_principal: No
credentials
cache found\n") at fe-auth.c:731
731 name = pg_krb5_authname(PQerrormsg);
(gdb) up
#5 0x0084f8dd in conninfo_parse (conninfo=0x935f3c8 "\001",
errorMessage=0xf3c00780) at fe-connect.c:2720
2720 option->val = fe_getauthname(errortmp);
(gdb) up
#6 0x0084d2fc in connectOptions1 (conn=0xf3c00480, conninfo=0x935f3c8
"\001")
at fe-connect.c:328
328 connOptions = conninfo_parse(conninfo,
&conn->errorMessage);
(gdb) up
#7 0x0084d295 in PQconnectStart (conninfo=0x935f3c8 "\001")
at fe-connect.c:287
287 if (!connectOptions1(conn, conninfo))
(gdb) up
#8 0x0084d242 in PQconnectdb (conninfo=0x935f3c8 "\001") at
fe-connect.c:245
245 PGconn *conn = PQconnectStart(conninfo);
(gdb) up
#9 0x00115257 in rxv_spin_db_connect (pool=0x93a7eb0, cpool=0x0,
conninfo=0xeb5a15 "dbname=spintest", type=1 '\001') at db.c:255
255 if(!(conn->pgconn=PQconnectdb(conninfo)))
(gdb) p conninfo
$1 = 0xeb5a15 "dbname=spintest"
---------------------------------
I have no idea how the conninfo (which in my code is a constant
string) gets screwed after that... BTW, this is just *one* way those
segfaults happen. Sometimes, it is when free() is called from various
krb5 library functions on an invalid pointer.
Not sure if this is helpful, but here it is nevertheless.
I'm hoping krb5-1.3.5 will eventually become part of FC3, at which
point I can retest with it...
Still present in recently updates krb5-libs-1.3.6-2.
According to Kerberos developer Tom Yu, these memory leaks have been
fixed in 1.4, which is currently at beta 3.
I did a little bit more snooping around and it turns out:
- worker MPM: segfaults
- prefork MPM: no segfaults
This is related to thread safety issues in relation to the way
PostgreSQL uses krb5 libraries. This is what Tom said:
-----------------------------
I took a closer look at
postgresql-7.4.5/src/interfaces/libpq/fe-auth.c and discovered that a
lot of krb5 state is kept as file-scope static variables. The problem
is therefore mostly postgresql's fault, since it looks like libpq
itself isn't thread-safe.
-----------------------------
In relation to memory leaks, this is allegedly fixed in 1.4 beta.
BTW, do I close this bug with with UPSTREAM? I'm not sure what the
policy of including krb5-libs is and if 1.4 is going to go into the
FC3 updates... Maybe I should close it with NEXTRELEASE? | https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=131769 | CC-MAIN-2017-04 | refinedweb | 2,492 | 67.35 |
Simplify the construction of HTML inside ASP.NET server controls using ControlInjector
Introduction:ASP.NET
server controls are great. They allow for building reusable components,
and are easy to distribute because they are entirely contained in an
assembly (no .ascx files needed). One of the drawbacks of server
controls is the lack of a designer/HTML editor for creating your
layout. The HTML is generated in the code and generally looks messy. It
can also be a headache to tweak/debug because your controls are being
added in a mess of LiteralControls for the HTML.
Approach:After
creating a server control with some very complex HTML, I realized that
the method of mixing HTML literal content with my private controls is
not ideal. What if there was a way to accomplish something similar to
String.Format()? We could parse a string and look for blocks like {xxx}
and inject our control there... all HTML content before and after those
blocks would be added to the Control collection as LiteralContent.Doing
this will allow us to separate layout from content, and we can easily
use a designer to construct and view the HTML, then copy it into a
string to place in the code.The ImplementationThe HTML can
be stored as a single string, and with C#, we can use string literals
@"string" to allow for multi-line strings without any concatenation
code. It will be relatively simple to cut-n-paste from another
designer. We will need to parse the HTML string and have placeholders
for each control we want to inject. I chose to use "{controlID}" as the
placeholder text. Some might argue that a use of {0} {1} would fit the
String.Format pattern a little better, but I chose to be more verbose
here because clarity of code is what I am going for here.Our
private controls will need to be contained inside of a hashtable. We
can use the control ID as the key, so it will be easy to work with.
Update
-- I decided to follow some advice and keep the Hashtable internal to
the class. The ControlInjector will no longer hold static methods, so
you will need to instantiate it before use. I like this design a lot
better.We will parse the HTML string, find the indices of the {
and }, add the text to the left as a literal control, replace the {xxx}
text with the actual control, and continue. The end result will be one
single control that the client code can add to the control tree.The CodeThe ControlInjector class contains three useful methods:
Update --
After using this utility for a while, I realized quickly that I was
still not getting any kind of designer support, and for large, complex
controls, it was still a bit unreadable. I wrote a method to allow for
getting the HTML string from an embedded resource. This way I can
create an HTML page inside my class library, set it as an embedded
resource and retain HTML designer support. Still, the designer support
is limited - you cannot design the individual controls, only the
layout. Another drawback is that I cannot edit the inner HTML of one of
the controls, I must use separate HTML files for this.The best
part about this is that the HTML file is included in your DLL, so you
do not introduce any file dependencies at all, which is ideal.
Nothing really
exciting here, the code uses reflection to get the current assembly
object, then checks to see if the resource exists. The only requirement
is that the caller assembly contains the embedded resource and they
supply the fully qualified name of the resource.
The Advantage:What does this code give you? Well, here's a snippet from a server control with mixed HTML and controls:
To demonstrate the
resource example, go to Visual Studio and add an HTML page to your
webcontrols project. Design the above HTML using the Visual Studio HTML
editor. Make sure and right-click the file in Solution Explorer and
choose Embedded Resource. If you don't do this, the file will not be
found at runtime. Once you have done this, the above method can be
reduced to the following:
This will get the HTML from the resource located in the MyWebControls namespace, entitled MyControl.html.Without the injector, we would have something like this:
... you get the idea...
multiply this mess by 100 lines of HTML mixed with controls and it's
not very easy to see what's going on.What's next?This
method has very minimal error checking, and that would be the first
place I would expand, but it is out of the scope of this article. (I
wanted to keep it clean and easy to understand.)The next thing
I would like to add would be the ability to nest content inside of the
controls, something like {control1}nested html{/control1}, but that
introduces a large level of complexity to the parser, so I haven't
decided if the benefit will be worth it.ConclusionHopefully
this will be of some use, and I am sure that there are other methods of
accomplishing the same task. I welcome any comments or criticisms.Updates*
June 30, 2005 - I removed the static methods in favor of an
instantiated use of the control. This allowed me to contain the
hashtable as an internal reference only, making the calling code a lot
simpler. I also added a method to read from an embedded resource to get
the HTML string. These two additions make the class 100% more readable
in my server controls. I hope it helps you as well! About Subdigital:Ben Scheirman is a professional web developer providing enterprise level ASP.NET solutions.He
started programming in QBASIC in 1993, learning from examples
downloaded online. He migrated to Pascal in 1996, C/C++ ruled his spare
time during the late 90's, and for the past 2 years he has been
developing using C# & VB.NET.He enjoys programming in his spare time, especially toying around with Managed DirectX.Read his blog here | http://www.gridviewguy.com/Articles/61_Using_Control_Injector_Control.aspx | crawl-001 | refinedweb | 1,022 | 62.78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.