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
|
|---|---|---|---|---|---|
How do you get Jetty not to work on request?
I'm studying Java, Jetty, Servlet. I want to study Spring later. Is that what the question is, how do you get the server to do my code permanently or with some frequency without a client's request?
For example, I have sensors that need to gather information in advance, and later, at the client ' s request, just get it out quickly. There are also executive devices that need to be forced to work without the participation of a person (open the tap, insert the ventilation).
Server's very notion is that he's dumb to wait for him to get kicked and can't do it any other way. I understand that you can get the planner to do every five seconds a request for a server, but it's a crutch, I'd like to hear the right academic solution, as they do (e.g. in enterprises)?
I don't want to move the Jetty core of the system to some other place or to double the logic by doing the outside violin.
I still don't know what application server is, maybe I need it. I mean, maybe appserver is different from the usual web server and the silver container that he can do the code himself for some internal dial and trigger?
A quick look at Spring's book has noticed that there are some tasks and a planner, maybe that's what I need?
I'm planning on using SBD and client for Androids, and maybe there's no point in keeping the logic of my program in the ears, but moving it to the extra program or to the CSB, and Jetty leaving it for the WEB-page? How is it right to do the perfect architecture?
I'll notice that it's all on ancient Raspberry Pi and I'm thinking about using it as a controller or as a server. Electricity can be saved as well as easily out of the situation by replacing the malfunctioning device and re-establishing the system from a backup copy. Besides, it's a messy system.
The replacement of Java technology is requested not to offer, the choice is made (long learning the popularity of programming languages, etc.). The plans are great, but I'm a newcomer, and I'm very smart not to be explained unless there's another way.
We need to look at the ServletContextListener and asynchronic. ServletContextListener redefinition contextInitialized and launch the necessary asynchronous disk:
public class BackgroundJobManager implements ServletContextListener {
private ScheduledExecutorService scheduler; @Override public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new SomeDailyJob(), 0, 1, TimeUnit.DAYS); // или что-то вроде этого... } @Override public void contextDestroyed(ServletContextEvent event) { // убить таск при останове сервера: scheduler.shutdownNow(); }
Of course, contextListener needs to be registered on the web.xml.
A more complete example can be found here:
|
https://software-testing.com/topic/888188/how-do-you-get-jetty-not-to-work-on-request
|
CC-MAIN-2022-21
|
refinedweb
| 485
| 62.27
|
Quixote 0.4.6 CHANGES * a last-minute patch to http_request.py just before release 0.4.5 broke extracting form data from GET requests -- fixed that 0.4.5 (11 Apr 2002): * The meaning of the DISPLAY_EXCEPTIONS configuration variable has changed. It's no longer a Boolean, and instead can take three different values: None (or any false value) [default] an "Internal Server Error" page that exposes no information about the traceback 'plain' a plain text page showing the traceback and the request variables 'html' a more elaborate HTML display showing the local variables and a few lines of context for each level of the traceback. (This setting requires the cgitb module that comes with Python 2.2.) (Idea and first version of the patch by David Ascher) * Fixed SessionManager.expire_session() method so it actually works (spotted by Robin Wohler). * Fixed docs so they don't refer to the obsolete URL_PREFIX configuration variable (spotted by Robin Wohler). * Various other documentation tweaks and improvements. * Fixed sample Apache rewrite rules in demo.txt and web-server.txt (spotted by Joel Shprentz). * Generate new form tokens when rendering a form rather then when intializing it. This prevents an extra token from being created when processing a valid form (suggested by Robin Wohler). * Ensure filenames are included in SyntaxError tracebacks from PTL modules. * Changed format of session cookies: they're now just random 64-bit numbers in hex. * Use HTTP 1.1 cache control headers ("Date" and "Expires") instead of the older "Pragma: no-cache". * In the form/widget library: make some effort to generate HTML that is XHTML-compliant. * New method: HTTPRequest.get_accepted_types() returns the MIME content types a client will accept as a dictionary mapping MIME type to the quality factor. (Example: {'text/html':1.0, 'text/plain':0.5, ...}) * Changed escape hatch for XML-RPC handlers; standard input will only be consumed when the HTTP method is POST and the Content-Type is either application/x-www-form-urlencoded or multipart/form-data. * Added quixote.util module to contain various miscellaneous utility functions. Right now, it contains a single function for processing requests as XML-RPC invocations. 0.4.4 (29 Jan 2002): * Simplify munging of SCRIPT_NAME variable, fixing a bug. Depending on how Quixote was called, the path could have been appended to SCRIPT_NAME without a separating slash. (Found by Quinn Dunkan.) * On Windows, set mode of sys.stdout to binary. This is important because responses may contain binary data. Also, EOL translation can throw off content length calculations. (Found by David Ascher) * Added a demonstration of the form framework. (Neil) * Added an escape hatch for XML-RPC handlers; http_request.process_inputs() will no longer consume all of standard input when the Content-Type is text/xml. * Removed a debug print from form.widget. 0.4.3 (17 Dec 2001): * Removed the URL_PREFIX configuration variable; it's not actually needed anywhere, and caused some user confusion. * Added FORM_TOKENS configuration variable to enable/disable unique form identifiers. (These are useful as a measure against cross-site request forgery [CSRF] attacks, but disabled by default because some form of persistent session management is required, which is not currently included with Quixote.) * Added demonstration and documentation for the widget classes (the first part of the Quixote Form Library). * Added HTTPResponse.set_content_type() method. * Fixed some minor bugs in the widget library. * Fixed to work with Python 2.2. * Greatly reduced the set of symbols imported by "from quixote import *" -- it's useful for interactive sessions. 0.4.2 (14 Nov 2001): * Made the quixote.sendmail module a bit more flexible and robust. * Fix so it doesn't blow up under Windows if debug logging is disabled (ie. write to NUL, not /dev/null). * Clarified some documenation inconsistencies, and added description of logging to doc/programming.txt. * Fixed some places that we forgot to update when the PTL-related modules were renamed. * Fixed ptl_compile.py so PTL tracebacks include the full path of source file(s). * Fixed bug where a missing _q_index() triggered a confusing ImportError; now it triggers a TraversalError, as expected. * Various fixes and improvements to the Config class. * Miscellaneous fixes to session.py. * Miscellaneous fixes to widget classes. * Reorganized internal PTL methods of the Form class. * Removed the "test" directory from the distribution, since it's not used for anything -- ie., there's no formal test suite yet ;-( 0.4.1 (10 Oct 2001): * Made access logging a little more portable (don't depend on Apache's REQUEST_URI environment variable). * Work around the broken value of PATH_INFO returned by IIS. * Work around IIS weird handling of SERVER_SECURE_PORT (for non-SSL requests, it is set to "0"). * Reassign sys.stderr so all application output to stderr goes to the Quixote error log. 0.4 (4 Oct 2001): * TraversalError now takes a public and a private message, instead of just a single message string. The private message is shown if SECURE_ERRORS is false; otherwise, the public message is shown. See the class docstring for TraversalError for more details. * Add the Quixote Form Library, a basic form and widget framework for HTML. * Allow classes and functions inside PTL modules. * Return a string object from templates rather than a TemplateIO instance. * Improve the security of session cookies. * Don't save empty sessions. * Detect expired sessions. * Add the quixote.sendmail module, useful for applications that need to send outgoing mail (as many web apps do). * Code reorganization -- various modules moved or renamed: quixote.util.fcgi -> quixote.fcgi quixote.compile_template -> quixote.ptl_compile quixote.imphooks -> quixote.ptl_import quixote.dumpptlc -> quixote.ptcl_dump * More code reorganization: the quixote.zope package is gone, as are the BaseRequest and BaseResponse modules. Only HTTPRequest and HTTPResponse survive, in the quixote.http_request and quixote.http_response modules. All remaining Zope-isms have been removed, so the code now looks much like the rest of Quixote. Many internal interfaces changed. * Added the quixote.mod_python module, contributed by Erno Kuusela <erno@iki.fi>. Allows Quixote applications to be driven by the Apache module mod_python, so no CGI or or FastCGI driver script is required. 0.3 (11 Jun 2001): *. * Added an ACCESS_LOG configuration setting, which allows setting up a file logging every call made to Quixote. * The error log now contains the time of each error, and a dump of the user's session object. * Added handy functions for getting request, session, user, etc.: quixote.get_publisher(), quixote.get_request(), quixote.get_session(), quixote.get_user(). *. * Some fixes and minor optimizations to the FCGI code. * Added HTTPRequest.get_encoding() method to find the encodings a client accepts. 0.2 (16 Jan 2001): * Only pass HTTPRequest object to published functions. The HTTPResponse object is available as an attribute of the request. * Removed more unused Zope code from HTTPRequest. Add redirect() method to HTTPRequest. * Simplify HTTPResponse. __init__() no longer requires the server name. redirect() requires a full URL. * Fix a bug in the PTL compiler. PTL modules can now have doc strings. * Added a config parser. Individual Quixote applications can now have their own configuration settings (overriding the Quixote defaults). See the config.py module for details. * Re-wrote the exception handling code for exceptions raised inside of published functions. * Non-empty PATH_INFO is no longer supported. __getname__ or query strings are a cleaner solution. * Add FIX_TRAILING_SLASH option and make code changes to carefully preserve trailing slashes (ie. an empty component on the end of paths). * Session management has been over-hauled. DummySessionManager can be used for applications that don't require sessions. * Set Content-length header correctly in HTTPResponse object * Added a demo application. 0.1: * Officially given a license (the Python 1.6 license, so it's free software). * Added SECURE_ERRORS variable to prevent exception tracebacks from being returned to the Web browser * Added a __getname__() function to traversal, which is called if the current name isn't in the current namespace's export list. This allows interpolation of arbitrary user object IDs into the URL, which is why it has to circumvent the __exports__ check: the object IDs won't be known until runtime, so it would be silly to add them to __exports__. Very useful and powerful feature, but it has security implications, so be careful! * compile_template.py should now work for both Python 1.5.2 or 2.0. * Better reporting of syntax errors in PTL * Always assume regular CGI on Windows 0.02 (12 Aug 2000): * Neil Schemenauer has completely rewritten the PTL compiler and changed the syntax to match Python's. The compiler now relies on Jeremy Hylton's compiler code from the Python 2.0 CVS tree. * Added functions to quixote.sessions: get_session(), has_session(), get_app_state() * Simplified reload-checking logic * Added .browser_version() method to HTTPRequest * Various bugfixes * session classes slightly tweaked, so you can subclass them * Added .session attribute to request object * Added quixote.errors module to hold exceptions 0.01: * Initial release.
|
http://lwn.net/2002/0418/a/quixchanges.php3
|
crawl-003
|
refinedweb
| 1,465
| 60.61
|
my teacher only teach to read char with system.in.read(),is there any way to read a char with scanner?? and is a String of "a" same as a char of 'a' .
Printable View
my teacher only teach to read char with system.in.read(),is there any way to read a char with scanner?? and is a String of "a" same as a char of 'a' .
Hello lotus,
You can read a char with the Scanner class like this:
Code :
import java.util.Scanner; public class lotus { /** * JavaProgrammingForums.com */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.next(); char[] myChar; myChar = input.toCharArray(); System.out.println(myChar); } }
The Scanner class doesn't have .nextChar(); unlike .nextDouble(); .nextInt(); etc.
Basically you use the Scanner class to read in the user input as String and then you need to convert the String to char.
A char is a single character, a String is ment to be a sequence of characters. String is an full-blown object, a char primitive data type is just two bytes in unicode.
I never use a char variable nowdays. Always just stick it in a String.
That's a problem, though if you want to read in the next char after... It's only going to return the first char of each word :P
To read in a single character, you can use the CharArrayReader class or the BufferedReader class. Actually, I think most of Reader's sub classes should be able to read in a single character.
why do you use a char[]??? and not char myChar;
because im at the final stage of my project, i have users input choice of 1 2 or 3 , but if a user inpuuts a non int number like a it gives a error, so if i want to solve these type of problems i have a String choice and then convert it to whatever i want it to be?
You'd want to make sure you use char[] for your passwords though :D
// Json
String (Java Platform SE 6)
|
http://www.javaprogrammingforums.com/%20java-se-apis/717-reading-char-scanner-printingthethread.html
|
CC-MAIN-2018-05
|
refinedweb
| 350
| 82.44
|
Creating Imports
On this page:
Introduction
The import statement adds to the imports section, but the cursor does not move from the current position, and your current editing session does not interrupt. This feature is known as the Import Assistant.
The same possibility applies to the XML files. When you type a tag with an unbound namespace, import assistant suggests to create a namespace and offers a list of appropriate choices.
Importing an XML namespace
To import an XML namespace, follow these steps:
- Open the desired file for editing, and start typing a tag. If a namespace is not bound, the following prompt appears:
- Press Alt+Enter. If there are multiple choices, select the desired namespace from the list.
WebStorm creates a namespace declaration.
Importing TypeScript symbols
In the TypeScript context, WebStorm WebStorm, WebStorm will display the following pop-up message:
Press Alt+Enter to have an import statement generated and inserted automatically.
In either case, WebStorm inserts an
import statement:
|
https://www.jetbrains.com/help/webstorm/2016.3/creating-imports.html
|
CC-MAIN-2017-04
|
refinedweb
| 161
| 55.44
|
Directory Listing
branch for MPI versioned AMG
Darcy flow solver is now supporting 4 solvers
Check for gmsh in main SConstruct file and skip tests that depend on it when the executable is not found.
Added missing cookbook figures from Anthony.
Fixed some minor doxygen issues..'
example10c removed from testing as it is not in the cookbook.
some modifications to fix the cook examples runs for testing
mesh size reduced
import order is critical
Missing script.
Added new example tests.
Added new example tests.
Minor changes to cookbook, gravity example.
minor changes to examples before holiday.
Updates to cookbook documentation for release.
Changes to example09 for memory footprint. One change too help wording in layer_cake function. example09b removed from testing. Not for impending release.
AMG support now block size > 3 (requires clapack or MKL). additional diagnostics for AMG
small correction
Updates to cookbook. Includes new section on variable meshing. To be reviewed.
RandomData added
Some changes to the cookbook examples. Starting Inversion experimentation.
Fixes to example scripts.
New figures.
Added missing import to fix unit test
Rearranged figures for release.
3d interpolateTable support. New more generic interface for table interpolation. tests and doco updated
added quick intro to visualization with VisIt and fixed a file reference.
esys.weipa Python interface documentation.
some clarification on AMG in the documentation.".
Appendix done. Fixed some overfull hboxes.
Finished user's guide chapters up to Appendix.
Faultsystems2d. not finished yet.
Fixed script filename
6.2 Darcy Flux. Note that I commented the gravity flow subsection since it's not written.
Section 6.1.
Finished pycad chapter 5, regenerated eps files
Adapt install guide to new style. Simplify package building scripts to autodetect necessary info and build control file automatically...
Updated relevant sections in install guide to reflect scons option changes. Standalone section needs to be updated before the release.
Removing dead files
Merging dudley and scons updates from branches
Fixed build error
Updates to cookbook, new chapter DC Resis and IP. Using new packages hyperref, natbib.
typo fixed
Missing *.png
Fix doc build error. I will add the figure when I come in tomorrow and turn Darra on.
Updates to cookbook. Fixes to SWP and new Gravitational Potential
up to Chapter 3
up to section 2.1.9
Hacking cookbook..
Fixed a couple of typos.
First steps towards macro elements. at the monent a macro element is identical to its counterpart of 2nd order.
finally there is a 3D version for the fault system class.
Fixed latex compile error. Fixed some overful hboxes..
documentation for units added.
Fixing the build of example tar and zip files so they don't have full paths..
|
https://svn.geocomp.uq.edu.au/escript/branches/amg_from_3530/doc/?view=log&pathrev=6049
|
CC-MAIN-2019-09
|
refinedweb
| 439
| 54.79
|
I load a gpx track to Potlatch 2. It appears as a blue line. I want to edit it to convert it into a path, give it a name and put it in OSM, but no luck!
So, my track is visible as a blue line, but how to edit it in Potlatch 2? If I try to select the track, only a red point appears, but the whole track is not selected.
Anyone?
Thanks!
asked
11 May '11, 10:50
stephanpls
1●2●2●2
accept rate:
0%
edited
11 May '11, 10:53
Take the following steps: Go to "Vector file" in Background and change the "Style" for Enhanced and keep the box "Select" filled. Now, the track will be showed as a thick line that can be edited.
answered
03 Oct '11, 04:49
Valdir Rodri...
1●2●2●3
accept rate:
0%
to continue petschge's answer keep clicking along trace then to connect it to another way use shift click ( search unconnected nodes in this Q&A) the highlighted way can now be tagged,use the box on the left(drag it from left edge of map until big enough) click on "unknown" box below the "no tags set" and select the best description when finished click save then describe what you've done and with what eg trace bing survay then save again wait for “successfully saved” then log out. Note some edits can take a while to appear on the slippy map good luck, searching Q&A before asking questions is some times quicker.
answered
11 May '11, 12:02
andy mackey
11.9k●74●126●262
accept rate:
4%
sorry "unconected nodes" can't be found but this Question answers things to avoid "what-are-the-most-common-mapping-mistakes-that-other-users-make"
You don't convert the GPX track to a path, but draw the path following the GPX track using your local knowledge. This way you can map small wiggles if they are real or map a straight road if the wiggles are just due to the imprecisions of the GPS. The red dot that appears is the first node of the way.
answered
11 May '11, 11:03
petschge
8.0k●20●71●96
accept rate:
21%
edited
03 Oct '11, 13:12
SomeoneElse ♦
32.3k●63●335●756
Ah, now it's clear. Thanks.
I was confused because some weeks ago in Potlatch 2 I DID manage to convert a blue gpx track directly into an editable track. I no more know how I did it....that's why I posted this question.
Alt-click a GPS track to make it an editable way. (Or Shift-Ctrl-click if you're using a daft Linux window manager that intercepts the Alt key for itself.)
Once you sign in you will be able to subscribe for any updates here
Answers
Answers and Comments
Markdown Basics
learn more about Markdown
This is the support site for OpenStreetMap.
Question tags:
gpx ×224
import ×169
question asked: 11 May '11, 10:50
question was seen: 4,163 times
last updated: 03 Oct '11, 13:12
"Found no good GPX points in the input data"
[closed] How to import a gpx without time tags?
Wie kann ich .itm-Daten in GPX-Dateien umwandeln?
GPX import : how to avoid manual creation of node ?
Errorneous GPX zip upload
Uploading a GPX from TTGpsLogger doesn't work
how to import a twl file to osm
Why does a GPX import report "Issue while inserting job into database"?
How should I go about importing a city?
Uploading a small bit of new TIGER data (and 3 other unrelated questions)
First time here? Check out the FAQ!
|
https://help.openstreetmap.org/questions/5110/dont-manage-loading-a-gpx-and-then-editing-it-to-a-path-in-osm?sort=newest
|
CC-MAIN-2019-51
|
refinedweb
| 620
| 78.38
|
Loads a (directed, undirected or multi) graph from a text file InFNm with 1 edge per line (whitespace separated columns, int node ids).
InFNm is a whitespace separated file of several columns: ... <source node id> ... <destination node id> ... Since the function assumes each line of the file encodes a single edge and a line in the file can have more than 2 columns, SrcColId and DstColId must be provided to indicate which column gives the source and which column gives the destination of the edge.
Parameters:
Class of output graph – one of PNGraph, PNEANet, or PUNGraph.
Filename with the description of the graph edges.
The column number in the file, which contains the node id representing the source vertex.
The column number in the file, which contains the node id representing the destination vertex.
Return value:
A Snap.py graph or a network represented by the InFNm of type GraphType.
The following example shows how to load a small file representing a graph:
import snap; Graph = snap.LoadEdgeList(snap.PNGraph, "toy_graph", 0, 1) Graph.Dump() UGraph = snap.LoadEdgeList(snap.PUNGraph, "toy_graph", 0, 1) UGraph.Dump() Network = snap.LoadEdgeList(snap.PNEANet, "toy_graph", 0, 1) Network.Dump()
An example file is given below (toy_graph)
1 1 1 2 2 1 1 3
|
https://snap.stanford.edu/snappy/doc/reference/LoadEdgeList.html
|
CC-MAIN-2017-51
|
refinedweb
| 210
| 68.87
|
#include <hallo.h> Steve Lee wrote on Mon Nov 12, 2001 um 03:37:30PM: > i What is your distribution? If you use initrd booting system, make sure you included the modules for the IDE chipset and IDE harddisks (bl-mj-3 is /dev/hd*) in your initrd image. If you are using Debian Woody, please upgrade to the latest version of initrd-tools (from Sid) and kernel-package. Previous used to have bugs, and even the current kernel-package in unstable is buggy. Gruss/Regards, Eduard. -- <LnxBil> Alfie: Also gehen tut das Ding, die Fehler sehe ich doch beim starten? -- LnxBil über die Bedeutung von "use strict;"
|
https://listman.redhat.com/archives/ext3-users/2001-November/msg00257.html
|
CC-MAIN-2017-04
|
refinedweb
| 108
| 71.85
|
Universal Table Editor is an ASP application to view and edit data in any database you can reach via ADO from your IIS. Compatible databases are e.g. MS Access�, MS SQL Server� or Oracle�. UTE is also able to export the data of a table into comma delimited text files (
.CSV) which are readable e.g. by MS Excel�.
UTE is a set of files representing just one single VBScript class
clsUTE which can be used in simple ASP pages or the most complex environments. Everything UTE uses is encapsulated within the clsUTE class so there shouldn't be any namespace problems at all. UTE defines all variables correctly so it is
option explicit proof. The layout of UTE is completely style sheet driven so it is quite simple adjustable to any layout.
Former UTE versions (<= 1.4) used session variables quite extensively. This is history now! UTE uses no session variables any more. UTE includes an
.inc file defining all language dependant settings and strings. It already comes with a number of pre-defined language files (English, German, French, Italian, Spanish) but it is not much of a problem for you to extend this list by your own.
.CSVfile.
option explicitproof.
To install UTE you just have to copy all files from the ZIP (including sub directories) to a IIS virtual directory (e.g.
ute30). That's all. Launch the index.html page to edit the included demo database.
UTE uses ADO (ActiveX Data Objects - installed on the Server) to access the database. I recommend the Microsoft ADO Pages to get more information on this technology. I have tested UTE with many databases based upon MS Access�, MS SQL Server� and Oracle�. If you run into any trouble after installing UTE you should check for the latest MDAC (Microsoft Data Access Components) version and database providers which are available here.
By calling the ute.asp page without any URL parameters or using the above toolbar button UTE will list all tables within the current database. By clicking on them, the table editor will open for this table.
To open UTE with a specific table you only need to set the
name URL parameter to define the name of the table:
UTE comes with a small demo database being taken from the Microsoft Northwind demo. If you want to connect to another database you need to modify the
ute.asp file (see chapter 4 UTE Reference).
By using the Pages links you can navigate through the entire table. By using the Records per Page you can select the number of records being displayed on one page.
UTE tries to detect all
primary key fields of the table and display them in the most left columns in italic style. This won't work in every case. There are OLEDB provider which don't return these information (whether being called directly or via ODBC). If UTE is not able to detect the
primary key fields of your table, you should try another connection type (see chapter 4.3.1 Connection Types) or define them in the URL with the
pkey[counter] URL parameter:
UTE is able to sort the contents of the table by any column (field) by clicking on the header of each column. Furthermore one can specify any number of fields as URL parameters to sort the table after. To do this, use the
sort[counter] URL parameter. The default sort direction is
ascending. Use additionaly the
sortdir[counter] URL parameter to specify another sort order:
sort2=EmployeeID&sortdir2=desc
Please note that by clicking on a column header you will loose all sort parameters above "1".
UTE displays the fields of the table in the order they have been defined within the database. Earlier UTE versions sorted them alphabetically. If you want them now to be sorted alphabetically you need to set the
sorted URL parameter:
See chapter 4.1 URL Parameter for a reference for all URL parameters.
By using the above toolbar button in the table or form view UTE will display the definitions of the fields within the table.
By using the
,
and
links in the table view it is possible to insert, edit and delete records to/in/from the table.
With clicking on Ok the changes will be made permanent in the database. With clicking on Cancel it will just be returned to the table view without any changes in the database. UTE does not do any field validation but instead simply returns the error messages it receives from ADO. If the error is assignable to a special field the error message will be display directly at the field, otherwise it will be display at the top of the page.
By using the above toolbar button you will be able to define any number of filters to reduce the amount of records within the table. Even though the dialog currently offers just 10 filters this is just a constant definition within UTE.
Each filter will be taken as one
WHERE clause. The filters can be connected by
AND or
OR. To remove filters again (and get all records form the table) just use the Clear button.
There is no direct validation of the values you enter for a filter. If you define invalid values for a filter field UTE will create an invalid SQL statement from it, get's an ODBC error and redirects back to this page and displays the original ODBC error message.
By using the above toolbar button UTE will export the content of the table into a "comma-separated" Text File (
.CSV) which can be imported by other applications like e.g. MS Excel�. The file will look like:
"OrderID","ProductID","Discount","Quantity","UnitPrice" "10248","42","0","10","9,8" "10248","72","0","5","34,8" "10248","11","0","12","14" "10249","14","0","9","18,6" "10249","51","0","40","42,4" ...
UTE will create the data on the fly and sends them to the browser. By setting setting the ContenType and an additional Header the browser will be able to start MS Excel� if desired.
Response.Buffer = TRUE Response.Clear Response.ContentType = "text/csv" Response.AddHeader "Content-Disposition", "inline;filename=" & m_sTable & ".csv"
By using the above toolbar button UTE will display the SQL statement being used to read the data from the database as well. This might be useful when working with filters.
Please use the
ute.asp file as a quite easy example of how to include UTE into any webpage. There is not much to do at all:
<%@ <html> <head> <title><%=ute.HeadLine%> - Universal Table Editor</title> <link rel="stylesheet" type="text/css" href="ute_style.css"> </head> <body bgcolor="#FFFFFF" link="#0000A0" vlink="#0000A0" alink="#0000A0"> <% ute.Draw Set ute = Nothing %> </body> </html>
Chapter 4 UTE Reference lists all public properties and functions the
clsUte class exports and also explains how to connect to a database.
All definitions and the class itself will be included via the
ute_definition.inc file. If you encounter problems e.g. with the URL parameter names UTE uses this is the place to simply give them some other names. I have written UTE as flexible as possible so you can change really a lot without need to dive in deeply into the logic. The layout is completely style sheet driven within the file
ute_style.css.
Within UTE all strings to be displayed on the screen are defined in a separate language include file:
ute_language_*.inc. UTE comes already with a number of predefined languages files:
Per default UTE uses the English file. It is the first include statement within the
ute_definition.inc file. So all you have to do to change the language of UTE is to change this include statement. If you translate UTE into another language please share it with the rest of us (see chapter 6 Some final words for how to share your work) !
There are two kinds of UTE parameters: public and private parameters. Well, URL parameters are not really public and private, but they are meant to. The public parameters should be used by you, the private parameters shouldn't. They are created and used by UTE only.
Please note that UTE will keep ALL your own URL parameters you set additionaly when opening a page where UTE is included in.
You can either use dsn (ODBC) or so called dsn-less connections. Please note that depending on the connection type UTE is not always be able to detect the primary key fields of a table due to differences in the used drivers. If you encounter problems just switch to the other connection type if possible.
If you have created an ODBC database on your machine and connected it to a database you can use the datasource name as connect string:
ute.Init("myDatabase")If you need to login to the database the login information can also be placed within the connect string:
ute.Init("dsn=myDatabase;uid=myName;pwd=myPassword")
Another way to connect to a database is using so called OLE-DB providers instead of ODBC. This is useful if your have no chance to create an ODBC datasource on your web server. An OLE-DB provider will connect to a database directly without using ODBC. The most common case would be to connect to an MS Access� database being placed in some directory of your website. This is how a dsn-less connect string would look like in this case:
ute.Init("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("test.mdb")Examples of other dsn-less connection strings can be found at the ADO Connection String Samples page compiled by Able Consulting, Inc.
This is how the files within UTE are connected to each other:
ute_definitions.inc
ute_language_*.inc
ute_adolib.inc
ute_class.inc
clsUTEclass with a number of private functions being used on loading the page and includes the next files:
ute_class_database.inc
ute_class_table.inc
ute_class_form.inc
ute_class_export.inc
ute_class_filter.inc
To take a view on how UTE looks and works like in real life just visit my UTE pages at
If you want to learn ASP and/or ADO this application might be a good choice to have a closer look on. On the other side it might be a little bit complex for a beginner, so you decide if you simply want to use it, or alter it.
From version 2.0 on I have placed UTE under the GNU General Public License (GPL). This is mainly to make sure that nobody earns big money from the work of others without sharing his own work also with the rest of us and/or hiding the fact that UTE isn't his own work. I think this is just fair, isn't it ?
Due to the fact that my job keeps my quite busy I have also decided to create a new location for the future development of UTE and to invite everyone to take part in it ! The simple key word is:
If you have some good ideas for UTE and want to implement and share them or you have created a new language file please feel free to join the ute-asp project at
Please feel free to join the discussion board here at CodeProject or at SourceForge and if you want just visit my homepage and leave a small note in my guestbook.
Thanks for your interest and enjoy UTE !
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/asp/ute.aspx
|
crawl-002
|
refinedweb
| 1,914
| 63.8
|
Easy Admin Interfaces with Active Admin in RailsBy Joyce Echessa). For now, you’ll have to use the master branch. Also, the maintainers of the Active Admin Github repo warn that the documentation at the official website is outdated and, for the latest docs, you should check the Github repo page itself.
Installation and Setup
For this tutorial, I set up three models.
rails g model Genre name:string rails g model Author first_name:string last_name:string rails g model Book name:string price:decimal author:references genre:references rake db:migrate
The models have the following associations.
app/models/genre.rb
class Genre < ActiveRecord::Base has_many :books end
app/models/author.rb
class Author < ActiveRecord::Base has_many :books end
app/models/book.rb
class Book < ActiveRecord::Base belongs_to :author belongs_to :genre end
To set up Active Admin, add the gem in your Gemfile. For Rails 4 support at the moment, we are tracking master.
gem 'activeadmin', github: 'gregbell/active_admin'
Then install it.
bundle install
Run the generator to install Active Admin. This will create an
AdminUser model, an initializer file for configuring Active Admin and an
app/admin directory that will hold the administration files. It uses Devise for authentication.
rails g active_admin:install
If you had already set up an
AdminUser model, then you can run the following instead, which will use the existing
AdminUser model.
rails g active_admin:install AdminUser
You will get further setup instructions on the terminal for some settings you need to do manually.
Next, run the migration.
rake db:migrate
Start the server and navigate to. You should be able to login using the following:
Username: admin@example.com Password: password
After logging in, the admin dashboard is presented. At the top is a menu showing the models that have been registered with Active Admin. At this point, only the
AdminUser model has been registered. You can view a list of registered admin users, edit their information, and create new ones.
Creating Admin Users
Before registering other models with Active Admin, let’s change the default behaviour for creating admin users. By default, to create an admin user, the admin needs to enter an email, password, and confirmation password. It’d be better if the app only asked for an email address and then sent a link to the user so that they can set their password.
Change the form used to create admin users in
app/admin/admin_user.rb to only contain the email field.
form do |f| f.inputs "Admin Details" do f.input :email end f.actions end
Now, enable an admin to be created without a password by adding the following in the
app/models/admin_user.rb file.
after_create { |admin| admin.send_reset_password_instructions } def password_required? new_record? ? false : super end
The
password_required? method checks if the record is getting created for the first time and returns false if so, thus allowing an admin to be created without a password. The
after_create method sends an email to the registered email address with a link to set password. This has already been set up by Devise since, by default, Devise was installed with the
rememberable sub module. (This is the same email sent when an admin tries to recover their password via the Forgot Password link. You can modify the default template message to suit both changing password and setting password needs).
If you haven’t defined default url options in your environment files, then sending the email will fail. Since we are in development, include the following in the
config/environments/development.rb file.
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
Of course, you need to set up a mailer for the email to be sent. That is out of scope for this tutorial, but you can check the Action Mailer documentation to find out how to send emails in a Rails application. Even without setting up Action Mailer to deliver emails, we can view the email content on the terminal. You can locate the Change Password Link url in the email message and copy and paste it to the browser to test if it works.
Customizing Views
Register our three models:
rails generate active_admin:resource Genre rails generate active_admin:resource Author rails generate active_admin:resource Book
I populated the database with some data by placing the following in the
db/seeds.rb file and ran
rake db:seed
ya = Genre.create! :name => "Young Adult" humor = Genre.create! :name => "Humor" gnovel = Genre.create! :name => "Graphic Novel" crime = Genre.create! :name => "Crime" fantasy = Genre.create! :name => "Fantasy" business = Genre.create! :name => "Business and Finance" collins = Author.create! :first_name => "Suzanne", :last_name => "Collins" kaling = Author.create! :first_name => "Mindy", :last_name => "Kaling" handler = Author.create! :first_name => "Chelsea", :last_name => "Handler" ohba = Author.create! :first_name => "Tsugumi", :last_name => "Ohba" oda = Author.create! :first_name => "Eiichiro", :last_name => "Oda" grisham = Author.create! :first_name => "John", :last_name => "Grisham" patterson = Author.create! :first_name => "James", :last_name => "Patterson" martin = Author.create! :first_name => "George", :last_name => "Martin" tolkien = Author.create! :first_name => "John", :last_name => "Tolkien" ende = Author.create! :first_name => "Michael", :last_name => "Ende" ries = Author.create! :first_name => "Eric", :last_name => "Ries" eyal = Author.create! :first_name => "Nir", :last_name => "Eyal" Book.create! :name => "The Hunger Games", :price => 20.00, :author => collins, :genre => ya Book.create! :name => "Catching Fire", :price => 20.00, :author => collins, :genre => ya Book.create! :name => "Mockingjay", :price => 20.00, :author => collins, :genre => ya Book.create! :name => "Is Everyone Hanging out Without Me?", :price => 20.00, :author => kaling, :genre => humor Book.create! :name => "Are You There, Vodka? It's Me Chelsea", :price => 20.00, :author => handler, :genre => humor Book.create! :name => "Death Note", :price => 20.00, :author => ohba, :genre => gnovel Book.create! :name => "One Piece", :price => 20.00, :author => oda, :genre => gnovel Book.create! :name => "The Pelican Brief", :price => 20.00, :author => grisham, :genre => crime Book.create! :name => "A Time to Kill", :price => 20.00, :author => grisham, :genre => crime Book.create! :name => "Along Came a Spider", :price => 20.00, :author => patterson, :genre => crime Book.create! :name => "A Game of Thrones", :price => 20.00, :author => martin, :genre => fantasy Book.create! :name => "A Clash of Kings", :price => 20.00, :author => martin, :genre => fantasy Book.create! :name => "A Storm of Swords", :price => 20.00, :author => martin, :genre => fantasy Book.create! :name => "A Feast for Crows", :price => 20.00, :author => martin, :genre => fantasy Book.create! :name => "A Dance with Dragons", :price => 20.00, :author => martin, :genre => fantasy Book.create! :name => "The Silmarillion", :price => 20.00, :author => tolkien, :genre => fantasy Book.create! :name => "The NeverEnding Story", :price => 20.00, :author => ende, :genre => fantasy Book.create! :name => "The Lean Startup", :price => 20.00, :author => ries, :genre => business Book.create! :name => "Hooked", :price => 20.00, :author => eyal, :genre => business
Running the application, you can now see the
Authors,
Books and
Genres items on the Dashboard menu. On clicking each menu item, you’ll see a list of items in that collection with
View,
Edit, and
Delete links for each.
Let’s change the
Books page from the default shown below.
First, change the columns that are displayed. Active Admin displays columns for all fields that your object has, but in this case we will remove the
Created At and
Updated At columns and add the author name and genre name columns. This is done within the
index method in
app/admin/book.rb, where the included columns are specified.
index do column :name column :author column :genre column :price end
Active Admin will detect the
belongs_to relationship that
Book has with
Author and
Genre, but you will notice that for the Author column, the name of the entry is displayed as
Author #1 (depending on the id of the record). Looking at the Author dropdown menu that is on the Filters sidebar on the right, notice that the Author object name is what is displayed and not something that is human-readable.
This is due to how Active Admin decides on what name to use as the display name for an object.
# Active Admin makes educated guesses when displaying objects, this is # the list of methods it tries calling in order setting :display_name_methods, [ :display_name, :full_name, :name, :username, :login, :title, :email, :to_s ]
To fix this, define a
to_s method for the Author model in the
app/models/author.rb file.
class Author < ActiveRecord::Base has_many :books def to_s "#{first_name} #{last_name}" end end
On refreshing the page, the Author column will now display the author’s first and last names.
You can also do some manipulation on the data before it is displayed. Let’s change the ‘Price’ column to display its currency. We’ll use the
number_to_currency helper for this. For dollars, no options need to be passed to the method.
ActiveAdmin.register Book do index do column :name column :author column :genre column :price do |product| number_to_currency product.price end default_actions end end
The
default_actions method adds the “View”, “Edit” and “Destroy” links.
You can change the name of a column by specifying the new name before the field name in the index method.
column 'New Name', :name
On the right side of the page is a filter that is useful in searching through records. You might not require some of the default attributes it offers. For the Book option, let’s specify the attributes we want to use to filter. In
app/admin/book.rb add
filter :name filter :author filter :genre filter :price
Active Admin selects the most relevant filter type based on the attribute type. For the author and genre attributes, they are being displayed in select drop-down menus. We might want to filter records belonging to more than one genre or author, so a select menu will not be useful for this. Let’s change this to display the collection items as checkboxes.
filter :author, :as => :check_boxes filter :genre, :as => :check_boxes
The sidebar can be modified to show more information. As an example, add a sidebar to the
Author Show page listing all the books that an author has written in a table. In the
app/admin/author.rb file, make the following changes.
ActiveAdmin.register Author do sidebar 'Books by this Author', :only => :show do table_for Book.joins(:author).where(:author_id => author.id) do |t| t.column("Title") { |book| book.name } end end end
Importing Data
By default, the interface allows us to create records one by one. This can be inefficient if we have a lot of data that we need to save or we want to use data from another application. It’s possible to enable CSV importation in the application.
We’ll use the
active_admin_importable gem for this. In your Gemfile add:
gem 'active_admin_importable'
And then execute
bundle install.
To enable CSV import on the Author page, in
app/admin/author.rb add the following.
active_admin_importable
An
Import Authors button will have appeared at the top right corner of the page. Click on it and browse your local file system for the csv file you want to import. The file should have a header row corresponding with your model attributes. You don’t have to include all columns, as default values will be inserted for columns you leave out.
I created a CSV file with the following two records and imported it.
First name,Last name Jane,Doe John,Doe
Downloading Data
Active Admin enables you to download the data in CSV, XML or JSON formats.
When you download the CSV file, you will see the model’s attributes as the file’s headers. You can indicate what is included in the CSV file. For the Author model, format our CSV file to only include the author’s first and last names.
In
app/admin/author.rb include the following.
csv do column :first_name column :last_name end
You can also enable Spreadsheet exports. Add the following to the Gemfile.
gem 'activeadmin-axlsx'
Run
bundle install. On running the app, you will see an XLSX link included on every resource page as one of the options for downloading data.
It’s possible to format the data exported in the spreadsheet. Below, the author first and last names are included, and the header color is changed. In
app/admin/author.rb add.
xlsx(:header_style => {:bg_color => 'C0BFBF', :fg_color => '000000' }) do delete_columns :id, :created_at, :updated_at end
If you don’t want to offer XML as a download option, you can change the options for a particular model by adding the following in the model’s Active Admin file. For example, in
app/admin/author.rb add the statement below, which will only change the links on the Author page.
index download_links: [:csv, :xlsx]
To set the options for all resources in your namespace add the following to the
config/initializers/active_admin.rb file.
ActiveAdmin.setup do |config| config.namespace :admin do |admin| admin.download_links = [:csv, :xlsx] end end
Conclusion
We have looked at some common customizations, but there are a ton more features that Active Admin has that we haven’t covered. To find out more, start with the documentation and the Github page.
|
https://www.sitepoint.com/easy-admin-interfaces-active-admin-rails/
|
CC-MAIN-2017-30
|
refinedweb
| 2,148
| 59.5
|
The new PhpStorm 2018.1 EAP build (181.3986.12) is now available! You can download it here or via JetBrains Toolbox App. Or, if you have the previous PhpStorm 2018.1 EAP build (181.3870.19) installed, you should soon get a notification in the IDE about a patch update.
This build delivers new features, bug fixes, and improvements for PHP and the Web, and includes the latest improvements in IntelliJ Platform.
Notable changes
- Live templates for HTTP client – easily create complex requests WI-40855
-
- Goto Symbol navigation improvements – we now accept namespaces and all php notations for class members WI-40827 WI-7436 WI-15581
Apart from above, this build brings many important bug fixes and usability improvements, including these:
- GitHub authentication issues resolved WI-27765
- Phing: 403 when trying to download latest phar via IDE WI-40863
- Remote SSH External tools don’t see project local servers WI-27765.3986.12 for your platform from the project EAP page or click “Update” in your JetBrains Toolbox App. And please do report any bugs and feature request to our Issue Tracker.
Your JetBrains PhpStorm Team
The Drive to Develop
|
https://blog.jetbrains.com/phpstorm/2018/02/phpstorm-2018-1-eap-181-3986-12/
|
CC-MAIN-2018-39
|
refinedweb
| 191
| 65.12
|
The function int putc(int character, FILE *stream); writes a character to the given stream and increment the internal position indicator by one.
Function prototype of putc
int putc(int character, FILE *stream);
- character : This is the character to be written on stream.
- stream : A pointer to a FILE object which identifies a stream.
Return value of putc
This function returns the character written in stream, on success. If an error occurs, EOF is returned and the error indicator is set.
C program using putc function
The following program shows the use of putc and getc function to write and read characters in a stream respectively. The following program writes a string(one character at time using putc) in a new file and again prints it's content on screen using getc.
#include <stdio.h> #include <string.h> int main (){ FILE *file; char *string = "putc C Standard Library function"; int c, counter, length = strlen(string); file = fopen("textFile.txt", "w+"); for(counter = 0; counter<length; counter++){ putc(string[counter], file); } /* Reset file pointer location to first character */ rewind(file); /* Read characters from file */ while(!feof(file)){ c = getc(file); printf("%c", c); } fclose(file); return(0); }
Output
putc C Standard Library function
The following program shows the use of putc function to write a characters on a standard output stream stdout.
#include <stdio.h> int main (){ int c; printf("Enter a character\n"); scanf("%c", &c); printf("You entered : "); putc(c, stdout); getch(); return(0); }
Output
Enter a character A You entered : A
|
http://www.techcrashcourse.com/2015/08/putc-stdio-c-library-function.html
|
CC-MAIN-2018-17
|
refinedweb
| 253
| 60.85
|
Updated on Kisan Patel
The
group operator transforms sequence into a sequence of groups.
The
group operator can be used to project a result grouped by a
key. It can be used as an alternative to the from clause and allows you to use single-value keys as well as multiple-value keys.
The
group operator implements
IGrouping<TKey, T> interface.
The
group operator will end a query, use
into to continue the query.
For Example,
var query = from c in customers group customers by c.City into groupbyCities orderby groupbyCities.Key ascending select groupbyCities;
Let’s take example to understand how group operator works.
using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApp { class Program { static void Main(string[] args) { List customers = new List{ new Customer{ Id = 1, Name = "Kisan", City="Ladol" }, new Customer{ Id = 2, Name = "Kite", City = "Ladol" }, new Customer{ Id = 3, Name = "Ketul", City = "Vijapur" }, new Customer{ Id = 4, Name = "Kisan", City = "Vijapur" }, }; var query = from c in customers group c by c.City; foreach (var group in query) { Console.WriteLine("Group City : " + group.Key); foreach (var name in group) { Console.WriteLine(name.Id + " - " + name.Name); } } } } public class Customer { public int Id { get; set; } public string Name { get; set; } public string City { get; set; } } }
the output of the above C# program…
|
http://csharpcode.org/blog/c-linq-grouping-operator/
|
CC-MAIN-2019-18
|
refinedweb
| 217
| 58.08
|
.
I always miss 3D printer when build any project. You can make a cool 3D for printed cage if you have access to 3D printer to bring more professional look.
You can easily modify it to work as wireless keyboard, wireless mouse or wireless presenter.
Step 1: What You Need
COMPONENTS
- Arduino Micro (Seeedstudio) or Pro Micro (Sparkfun)
- Arduino Pro Mini (Seeedstudio) or ATmega328
- Grove - Thumb Joystick (Seeedstudio)
- 315Mhz RF link kit (Seeedstudio)
- Tactile Button (5pcs) (Sparkfun)
- Polymer Lithium Ion Battery (Sparkfun)
- Lithium Battery Charger Module (Dfrobot)
- USB Male Type A Connector (Sparkfun)
- Vero Board
- Jumper wire
- A LED & 220 ohm resistor
- On/Off Switch
HAND TOOLS
- Soldering Iron
- Wire Cutter
- Hot Glue Gun
- Desoldering pump
Basic soldering skill is required to make the project successful.
Step 2: Making the Receiver (Little Desoldering)
My wireless joystick has two parts. One is receiver which will be connected to PC via USB port. Another is transmitter and this is the actual joystick in your hand. As I mentioned earlier, Receiver unit should contains 32U4 comes equipped with a full-speed USB transceiver. For the purpose I used cool & tiny Pro Micro from Sparkfun. You may used others variant like Arduino Micro or DUE.
Let's make receiver first as it has less connections required. I assumed you have some soldering experience, if not you may try this instructables (How-to-solder).
I used 433MHz FM receiver with the Pro Micro to receive signal from joystick. First, you need to desolder 4 pins header from the receiver unit. It will help you to easily adjust the receiver to Pro Micro board.
Step 3: Making the Receiver (Connecting Pro Micro to RF Receiver)
Now, you should connect the RF receiver to the Pro Micro. RF receiver has 4 pins. One for VCC, one for GND and rest two pins for data. Connect VCC pin to Pro Micro's VCC pin & GND to Pro Micro's ground. Basically two data pins are one pin. You can connect any one to the Pro Micro's I/O pin. You may use any of the I/O pin but I used pin 9 of Pro Micro. I used jumper wire to connect two things together like figures.
After soldering you have to fix two things together. For that I used a insulator between them otherwise these may short circuited accidentally and may damaged the receiver or Pro Micro.
Step 4: Making the Receiver (Uploading the Program)
If you followed the previous steps you are in the final stage of making receiver. Use glue or tap or band to fix all the things. I used rubber band to do the job. Pictures are added. Finally you need a USB cable to to connect it with the PC. I missed one thing. You may used a short piece of jumper wire as antenna which will increase the rang of your wireless joystick.
I think you already made your receiver. Just upload the following program to the receiver to make it complete. You will notice in the sketch three library ware used. Keyboard and Mouse library is included to Arduino IDE but you have to add VirtualWire library to talk to RF receiver.
You can learn more about keyboard and mouse library from Sparkfun tutorial.
#include <Mouse.h> #include <Keyboard.h> #include <VirtualWire.h> const int led_pin = 13; const int transmit_pin = 11; const int receive_pin = 9; const int transmit_en_pin = 3; #define KEY_UP_ARROW 0xDA #define KEY_DOWN_ARROW 0xD9 #define KEY_LEFT_ARROW 0xD8 #define KEY_RIGHT_ARROW 0xD7 #define KEY_BACKSPACE 0xB2 void setup() { delay(1000); Serial.begin(9600); // Debugging only Serial.println("setup"); // 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 { digitalWrite(led_pin, HIGH); // Flash a light to show received good message // Message with a good checksum received, print it. Serial.print("Got: "); Serial.println((char)buf[0]); char c = (char)buf[0]; if(c=='W'){ Keyboard.write('w'); delay(100); } if(c=='A'){ Keyboard.write('a'); delay(100); } if(c=='S'){ Keyboard.write('s'); delay(100); } if(c=='D'){ Keyboard.write('d'); delay(100); } if(c=='U'){ Keyboard.write(KEY_UP_ARROW); delay(100); } if(c=='B'){ Keyboard.write(KEY_DOWN_ARROW); delay(100); } if(c=='L'){ Keyboard.write(KEY_LEFT_ARROW); delay(100); } if(c=='R'){ Keyboard.write(KEY_RIGHT_ARROW); delay(100); } if(c=='G'){ Keyboard.write(KEY_BACKSPACE); delay(100); } if(c=='1'){ Mouse.move(0,5,0); delay(100); } if(c=='2'){ Mouse.move(0,10,0); delay(100); } if(c=='3'){ Mouse.move(0,15,0); delay(100); } if(c=='4'){ Mouse.move(0,20,0); delay(100); } if(c=='5'){ Mouse.move(5,0,0); delay(100); } if(c=='6'){ Mouse.move(10,0,0); delay(100); } if(c=='7'){ Mouse.move(15,0,0); delay(100); } if(c=='8'){ Mouse.move(20,0,0); delay(100); } } }
Step 5: Making the Transmitter (Soldering Buttons & IC)
Our receiver unit is ready. Now, it is the time to make main thing the joystick. I used one x-y axis joystick module and 5 momentary buttons for the things. For the shortage of time I used veroboard for the complete task but a PCB board will definitely make it more reliable and more beautiful. I think a typical veroboard is enough. Fritzing board layout for the complete system with source file are attached below.
First, solder 5 momentary buttons at the right side of the board. Then put and solder a 28 pins IC base at the middle of the board. Ic base is not mandatory byt I always prefer to use it. It protects the IC from burning during soldering and it makes the IC movable.
Step 6: Add Jumper Wires to Connect Buttons With IC
One thing I should mention here, I used Standalone ATmega328 microcontroller instead of Arduino Pro Mini. You can used as you like. A 16 MHz crystal is required and for that I soldered it with the board. I also add a on/off button with a indicator LED. Do not forget to used a 220-330 ohm current limiting resistor with led.
Step 7: Making Joystick (Connecting RF Transmitter and Li-ion Charger)
Now, connect the RF transmitter to the board. RF transmitter has three pin. One for data transmission and another two pins for biasing. Data pin need to connect one of the digital I/O pin of Atmega microcontroller. I used pin 9 of Arduino which is pin physical pin 15 of ATmega328.
After connecting RF transmitter I connected Li-ion charger module to chard the battery which I will connect later to the board. You should use some glue to fix it with the board strongly. Hot glue may be a good option.
Step 8: Making Joystick (Connecting Joystick Module)
Now connect joystick module to the board which will act as a mouse for greater experience of gaming. Joystick's has 5 pins. Two for VCC and ground. Actually joystick's has tow potentiometer and the value of the potentionmeter changes for rotating the nob. One pot is for X - axis and another is for Y - axis. Two analog input pins are required for connecting. I used A0 and A1. Joystick has one switch also which may be used to identify mouse click. Used any of Arduino digital pin to connect. it.
Step 9: Connecting the Battery
Now you have to connect the rechargeable Li-ion battery to the board. Connect it according to the circuit. Battery should be fixed with the board tightly. I used double sided tap for the purpose.
After connecting battery connect a charger port to the charging module. I you done all thing correctly your battery will start charging. Test it.
Step 10: Uploading of the Program
All connections and soldering are completed. It is the right time to program the board. I developed the rogram using Arduino IDE. Then I burned the program to the IC using Arduion UNO and then put the IC to the board. If you like to used only atmega IC like me instead of using full arduino board you may follow this tutorial (From Arduino to a Microcontroller on a Breadboard).
Here is the program I used for my joystick. I also added the file below. Arduino VirtualWire library was used for interfacing with RF transceiver.
//.................................. #include <VirtualWire.h> const int led_pin = 13; const int transmit_pin = 9; const int receive_pin = 10; const int transmit_en_pin = 3; int horzPin = A0; // Analog output of horizontal joystick pin int vertPin = A1; // Analog output of vertical joystick pin int selPin = 11; //; char *controller; String msgV, msgH; int W=8, A=6, S=5, D=7, SPACE=2; void setup() { pinMode(13,OUTPUT); delay(1000); Serial.begin(9600); // Debugging only Serial.println( pinMode(5, INPUT); pinMode(6, INPUT); pinMode(7, INPUT); pinMode(8, INPUT); pinMode(2, INPUT); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(8, HIGH); digitalWrite(2, HIGH); delay(1000); } void loop(){ vertValue = analogRead(vertPin) - vertZero; // read vertical offset horzValue = analogRead(horzPin) - horzZero; // read horizontal offset if(digitalRead(W)== LOW){ controller="W"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100); } if(digitalRead(A)== LOW){ controller="A"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100); } if(digitalRead(S)== LOW){ controller="S"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100); } if(digitalRead(D)== LOW){ controller="D"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100); } if(digitalRead(SPACE)== LOW){ controller="G"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100); } if (vertValue >= 50){ //Mouse.move(0, vertValue/sensitivity, 0); // move mouse on y axis if(vertValue/sensitivity ==1) controller = "1"; else if(vertValue/sensitivity ==2) controller = "2"; else if(vertValue/sensitivity ==3) controller = "3"; else controller = "4"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100);} if (horzValue >= 50){ if(horzValue/sensitivity ==1) controller = "5"; else if(horzValue/sensitivity ==2) controller = "6"; else if(horzValue/sensitivity ==3) controller = "7"; else controller = "8"; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone delay(100);} }
Step 11: Making Cage
I have no access to any laser cutter. If you have you can make nice box for the joystick.
I have made a box using PVC sheet. Cut to pieces of PVC sheet according to your PCB. Attach one piece of the board to the bottom side of PCB. You have to make some hole to the top piece for the buttons, power LED & joystick. I used tracing paper to trace the buttons position. Images are attached. Then I used a knife to make hole to the top sheet. Then I fixed it to PCB by hot glue.
10 Discussions
1 year ago
Thank you for your
2 years ago
nice project u get there...can i ask, is it work of the gaming controller?
2 years ago
Can I use this to control a hand held gimbal with an alexmos control board.
2 years ago
hi , how can i use this wireless gaming to control six servomotors , do you think that could be poossible?
2 years ago
Can we use this for rc cars.
2 years ago
Thank you sir for sharing a nice and impressive project
2 years ago
Really Impressive work .. I can understand how much u might have struggled to do all this kind of projects ..All the best
Reply 2 years ago
Thank you
2 years ago
great!
all the best for your future projects.
Reply 2 years ago
Thank you for your inspiration.
|
https://www.instructables.com/id/DIY-Wireless-Joystick-Wireless-Gaming/
|
CC-MAIN-2018-51
|
refinedweb
| 1,937
| 66.33
|
dakota ferrell1,454 Points
how can I get this code to work?
l1 = ([1, 2, 3, 1, 2, 3])
l3 = set(l1)
l2 = list(set(l1)) l4 = list(l3) print(l1, l2, l3, l4)
def user_number (num): user_num = input ("whats your number?") num = user_num return user_num
number = print(user_number(1))
if user_number == 2: print("found")
2 Answers
Steven Parker181,132 Points
It's hard to read Python without Markdown formatting, and it's not clear what the program is intended to do. But one thing that stands out even now is that "user_number" is defined as a function but then later compared it with the number "2" as if it was a variable.
Also, "print" doesn't return anything so it's not useful to assign to the variable "number" (which is then not used anyway).
Steven Parker181,132 Points
You almost had it, you just need to add parentheses to call your function:
if user_number() == 2:
Steven Parker181,132 Points
Sure, but it doesn't look like you'd need that here. Or what did you have in mind?
dakota ferrell1,454 Points
dakota ferrell1,454 Points
im really just trying to think of away to get a if to print out a message to a certain number even though the number might change for instance the user inserts the number 1 then the if stament runs and they get a message but what if user2 uses the number 2 I want them to get the same message. I know there are better ways of doing this but I was wondering if I can make a if stament to run without knowing what the value is at a given point.
|
https://teamtreehouse.com/community/how-can-i-get-this-code-to-work
|
CC-MAIN-2020-10
|
refinedweb
| 281
| 67.42
|
Matplotlib provides a function,
streamplot, to create a plot of streamlines representing a vector field. The following program displays a representation of the electric field vector resulting from a multipole arrangement of charges. The multipole is selected as a power of 2 on the command line (1=dipole, 2=quadrupole, etc.)
It requires Matplotlib 1.5+ because of the choice of colormap (
plt.cm.inferno): this can be replaced with another (for example
plt.cm.hot) if using an older version of Matplotlib.
import sys import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle def E(q, r0, x, y): """Return the electric field vector E=(Ex,Ey) due to charge q at r0.""" den = np.hypot(x-r0[0], y-r0[1])**3 return q * (x - r0[0]) / den, q * (y - r0[1]) / den # Grid of x, y points nx, ny = 64, 64 x = np.linspace(-2, 2, nx) y = np.linspace(-2, 2, ny) X, Y = np.meshgrid(x, y) # Create a multipole with nq charges of alternating sign, equally spaced # on the unit circle. nq = 2**int(sys.argv[1]) charges = [] for i in range(nq): q = i%2 * 2 - 1 charges.append((q, (np.cos(2*np.pi*i/nq), np.sin(2*np.pi*i/nq)))) # Electric field vector, E=(Ex, Ey), as separate components Ex, Ey = np.zeros((ny, nx)), np.zeros((ny, nx)) for charge in charges: ex, ey = E(*charge, x=X, y=Y) Ex += ex Ey += ey fig = plt.figure() ax = fig.add_subplot(111) # Plot the streamlines with an appropriate colormap and arrow style color = 2 * np.log(np.hypot(Ex, Ey)) ax.streamplot(x, y, Ex, Ey, color=color, linewidth=1, cmap=plt.cm.inferno, density=2, arrowstyle='->', arrowsize=1.5) # Add filled circles for the charges themselves charge_colors = {True: '#aa0000', False: '#0000aa'} for q, pos in charges: ax.add_artist(Circle(pos, 0.05, color=charge_colors[q>0])) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ax.set_xlim(-2,2) ax.set_ylim(-2,2) ax.set_aspect('equal') plt.show()
The electric field of a dipole:
$ python efield.py 1
The electric field of an octopole:
$ python efield.py 3
Comments are pre-moderated. Please be patient and your comment will appear soon.
Stafford 2 years, 7 months ago
What clever program, Loved it. I had to change the 'inferno' to 'hot' as we were warned in the opening comments. Didn'tLink | Reply
realise I was using an outdated version of matplotlib.
christian 2 years, 7 months ago
Thanks, Stafford – the issue of colormaps is one that exercises some people a great deal: for a good article about how awful the default colormap, jet, is, take a look here: | Reply
Steven Armour 1 year, 10 months ago
Would you be opposed to me publishing a reproduction of this example that I made with the python yt lib () to the yt repository examples archive? (they need non-astro examples like nothing else) I have already made a prototype of what I am purposing for my E&M class last fall and would also like you to review the photo notebook as well as the final notebook to make sure there are no errors in trying to visualize the vector field volumetrically.Link | Reply
Sincerly
Steven Armour
christian 1 year, 10 months ago
Not at all – you're welcome to the example and any code here you find useful. I'd be happy to take a look at the Notebook you are preparing for your EM class.Link | Reply
Best wishes,
Christian
Youcef 1 year, 8 months ago
Hello,Link | Reply
i have some trouble running this program, it gives me this error if you can help me figure out what's the problem:
nq = 2**int(sys.argv[1])
IndexError: list index out of range
Thanks for your time
christian 1 year, 8 months ago
Hi Youcef,Link | Reply
The program expects the user to provide the order of the multipole on the command line (e.g. 1 for dipole, 2 for quadrupole etc.), so you should run the code with e.g.
python multipole.py 3
to plot a figure for an octopole.
Youcef 1 year, 8 months ago
Hello again Christian,Link | Reply
I did what you told me and it worked, so thanks a lot for the help and the quick response !
good day
Joaquín 9 months ago
Hello Christian,Link | Reply
I am a beginner in python, what do you exactly would write in the code for a dipole ?
I know you already answered the question but i need you to be more specific please.
christian 9 months ago
Dear Joaquín,Link | Reply
You need to save the code somewhere and open a command prompt (Terminal, whatever). If you navigate to the directory in which you've saved the code (on a Mac or *nix system, use the cd command; on windows I think it's chdir), you can just type:
python efield.py 1
to run the code for a dipole (2 for a quadrupole, 3 for a hexapole, etc), assuming you saved the code as efield.py and your python installation has the correct libraries installed. You might find it useful to install Anaconda () to manage your python installation.
I hope that helps,
Christian
Lina 1 year, 6 months ago
Is it possible to get the coordinates of the different streamlines ?Link | Reply
Also how can I interpolate between the streamlines ?
christian 1 year, 6 months ago
Hi Lina,Link | Reply
The call to streamplot returns a container object, stream_container, from which you can obtain the lines making up the plot as stream_container.lines, and get their coordinates from there.
If you want the lines to be closer together, you can set the density argument to streamplot when you call it, as described in the documentation: []
Mark 1 year, 6 months ago
Perfect for creating custom field plots to add into my teaching notes.Link | Reply
christian 1 year, 6 months ago
I'm glad you find it useful – thanks for dropping by.Link | Reply
Keith 1 year, 6 months ago
In a couple of places hypot(x,y) should be used instead of sqrt(x**2+y**2).Link | Reply
christian 1 year, 6 months ago
That's a good idea – I've made the changes.Link | Reply
Thanks, Christian
Xinyuan Wei 1 year, 4 months ago
Hello,Link | Reply
I wonder In line 8: den = np.hypot(x-r0[0], y-r0[1])**1.5
if the exponent 1.5 should be replaced by 3?
christian 1 year, 4 months ago
Thanks for that catch, Xinyaun – you're absolutely right. I changed the previous code to use np.hypot without thinking it through. I've fixed it now.Link | Reply
Cheers,
Christian
mattes 5 months, 2 weeks ago
This is a nice code! But I have one question:Link | Reply
Not any steamline is equal. This is seen in your ocutpole (right top, red pole), where one steamline is straight. I want all lines look equally. Do you know how to do this?
Cheers,
mattes
New Comment
|
https://scipython.com/blog/visualizing-a-vector-field-with-matplotlib/
|
CC-MAIN-2019-22
|
refinedweb
| 1,186
| 73.37
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to copy field value in odoo 8 ?
How to copy field value in odoo . .
Let say i have two field called name and name1
i want to show name field and hide name1 field.
if i update name field it also need to upade name1 field. . .
Any idea other than on_change
Hello,
You can set value on create and write method when you save the record.
@api.model
def create(self, vals):
if vals.get('name'):
vals['name1'] = vals.get('name')
your_obj = super(your_obj, self).create(vals)
return your_obj
@api.model
def write(self, vals):
if vals.get('name'):
vals['name1'] = vals.get('name')
your_obj = super(your_obj, self).write(vals)
return True
Hello,
I will definetively go for a functional field (stored in base if needed).
Assuming name is a char (but it will work for any type of field)
from openerp import api
@api.depends('name')
def _mimic_name(self):
for rec in self:
rec.name1 = rec.name
name = fields.Char('Name')
name1 = fields.Char('Name1', compute='_mimic_name', store=True)
As I said, store=True is optional, it depends of wheter you want the field to be persistant in database or calculated on the fly.
Hope it helps!
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
|
https://www.odoo.com/forum/help-1/question/how-to-copy-field-value-in-odoo-8-88255
|
CC-MAIN-2017-47
|
refinedweb
| 254
| 70.39
|
Introduction to MongoDB for Java, PHP and Python Developers
Introduction to NoSQL Architecture with MongoDB for Java, PHP and Python Developers
This article covers using MongoDB as a way to get started with NoSQL. It presents an introduction to considering NoSQL, why MongoDB is a good NoSQL implementation to get started with, MongoDB shortcommings and tradeoffs, key MongoDB developer concepts, MongoDB architectural concepts (sharding, replica sets), using the console to learn MongoDB, and getting started with MongoDB for Python, Java and PHP developers. The article uses MongoDB, but many concepts introduced are common in other NoSQL solutions. The article should be useful for new developers, ops and DevOps who are new to NoSQL.
From no NoSQL to sure why not
The first time I heard of something that actually could be classified as NoSQL was from Warner Onstine, he is currently working on some CouchDB articles for InfoQ. Warner was going on and on about how great CouchDB was. This was before the term NoSQL was coined. I was skeptical, and had just been on a project that was converted from an XML Document Database back to Oracle due to issues with the XML Database implementation. I did the conversion. I did not pick the XML Database solution, or decide to convert it to Oracle. I was just the consultant guy on the project (circa 2005) who did the work after the guy who picked the XML Database moved on and the production issues started to happen.
This was my first document database. This bred skepticism and distrust of databases that were not established RDBMS (Oracle, MySQL, etc.). This incident did not create the skepticism. Let me explain.
First there were all of the Object Oriented Database (OODB) folks for years preaching how it was going to be the next big thing. It did not happen yet. I hear 2013 will be the year of the OODB just like it was going to be 1997. Then there were the XML Database people preaching something very similar, which did not seem to happen either at least at the pervasive scale that NoSQL is happening.
My take was, ignore this document oriented approach and NoSQL, see if it goes away. To be successful, it needs some community behind it, some clear use case wins, and some corporate muscle/marketing, and I will wait until then. Sure the big guys need something like Dynamo and BigTable, but it is a niche I assumed. Then there was BigTable, MapReduce, Google App Engine, Dynamo in the news with white papers. Then Hadoop, Cassandra, MongoDB, Membase, HBase, and the constant small but growing drum beat of change and innovation. Even skeptics have limits.
Then in 2009, Eric Evans coined the term NoSQL to describe the growing list of open-source distributed databases. Now there is this NoSQL movement-three years in and counting. Like Ajax, giving something a name seems to inspire its growth, or perhaps we don't name movements until there is already a ground swell. Either way having a name like NoSQL with a common vision is important to changing the world, and you can see the community, use case wins, and corporate marketing muscle behind NoSQL. It has gone beyond the buzz stage. Also in 2009 was the first project that I worked on that had mass scale out requirements that was using something that is classified as part of NoSQL.
2009 was when MongoDB was released from 10Gen, the NoSQL movement was in full swing. Somehow MongoDB managed to move to the front of the pack in terms of mindshare followed closely by Cassandra and others (see figure 1). MongoDB is listed as a top job trend on Indeed.com, #2 to be exact (behind HTML 5 and before iOS), which is fairly impressive given MongoDB was a relativly latecomer to the NoSQL party.
Figure 1: MongoDB leads the NoSQL pack
MongoDB is a distributed document-oriented, schema-less storage solution similar to CouchBase and CouchDB. MongoDB uses JSON-style documents to represent, query and modify data. Internally data is stored in BSON (binary JSON). MongoDB's closest cousins seem to be CouchDB/Couchbase. MongoDB supports many clients/languages, namely, Python, PHP, Java, Ruby, C++, etc. This article is going to introduce key MongoDB concepts and then show basic CRUD/Query examples in JavaScript (part of MongoDB console application), Java, PHP and Python.
Disclaimer: I have no ties with the MongoDB community and no vested interests in their success or failure. I am not an advocate. I merely started to write about MongoDB because they seem to be the most successful, seem to have the most momentum for now, and in many ways typify the very diverse NoSQL market. MongoDB success is largely due to having easy-to-use, familiar tools. I'd love to write about CouchDB, Cassandra, CouchBase, Redis, HBase or number of NoSQL solution if there was just more hours in the day or stronger coffee or if coffee somehow extended how much time I had. Redis seems truly fascinating.
MongoDB seems to have the right mix of features and ease-of-use, and has become a prototypical example of what a NoSQL solution should look like. MongoDB can be used as sort of base of knowledge to understand other solutions (compare/contrast). This article is not an endorsement. Other than this, if you want to get started with NoSQL, MongoDB is a great choice.
MongoDB a gateway drug to NoSQL
MongoDB combinations of features, simplicity, community, and documentation make it successful. The product itself has high availability, journaling (which is not always a given with NoSQL solutions), replication, auto-sharding, map reduce, and an aggregation framework (so you don't have to use map-reduce directly for simple aggregations). MongoDB can scale reads as well as writes.
NoSQL, in general, has been reported to be more agile than full RDBMS/ SQL due to problems with schema migration of SQL based systems. Having been on large RDBMS systems and witnessing the trouble and toil of doing SQL schema migrations, I can tell you that this is a real pain to deal with. RDBMS / SQL often require a lot of upfront design or a lot schema migration later. In this way, NoSQL is viewed to be more agile in that it allows the applications worry about differences in versioning instead of forcing schema migration and larger upfront designs. To the MongoDB crowd, it is said that MongoDB has dynamic schema not no schema (sort of like the dynamic language versus untyped language argument from Ruby, Python, etc. developers).
MongoDB does not seem to require a lot of ramp up time. Their early success may be attributed to the quality and ease-of-use of their client drivers, which was more of an afterthought for other NoSQL solutions ("Hey here is our REST or XYZ wire protocol, deal with it yourself"). Compared to other NoSQL solution it has been said that MongoDB is easier to get started. Also with MongoDB many DevOps things come cheaply or free. This is not that there are never any problems or one should not do capacity planning. MongoDB has become for many an easy on ramp for NoSQL, a gateway drug if you will.
MongoDB was built to be fast. Speed is a good reason to pick MongoDB. Raw speed shaped architecture of MongoDB. Data is stored in memory using memory mapped files. This means that the virtual memory manager, a very highly optimized system function of modern operating systems, does the paging/caching. MongoDB also pads areas around documents so that they can be modified in place, making updates less expensive. MongoDB uses a binary protocol instead of REST like some other implementations. Also, data is stored in a binary format instead of text (JSON, XML), which could speed writes and reads.
Another reason MongoDB may do well is because it is easy to scale out reads and writes with replica sets and autosharding. You might expect if MongoDB is so great that there would be a lot of big names using them, and there are like: MTV, Craigslist, Disney, Shutterfly, Foursqaure, bit.ly, The New York Times, Barclay’s, The Guardian, SAP, Forbes, National Archives UK, Intuit, github, LexisNexis and many more.
Caveats
MongoDB indexes may not be as flexible as Oracle/MySQL/Postgres or other even other NoSQL solutions. The order of index matters as it uses B-Trees. Realtime queries might not be as fast as Oracle/MySQL and other NoSQL solutions especially when dealing with array fields, and the query plan optimization work is not as far as long as more mature solutions. You can make sure MongoDB is using the indexes you setup quite easily with an explain function. Not to scare you, MongoDB is good enough if queries are simple and you do a little homework, and is always improving.
MongoDB does not have or integrate a full text search engine like many other NoSQL solutions do (many use Lucene under the covers for indexing), although it seems to support basic text search better than most traditional databases.
Every version of MongoDB seems to add more features and addresses shortcoming of the previous releases. MongoDB added journaling a while back so they can have single server durability; prior to this you really needed a replica or two to ensure some level of data safety. 10gen improved Mongo's replication and high availability with Replica Sets.
Another issue with current versions of MongoDB (2.0.5) is lack of concurrency due to MongoDB having a global read/write lock, which allows reads to happen concurrently while write operations happen one at a time. There are workarounds for this involving shards, and/or replica sets, but not always ideal, and does not fit the "it should just work mantra" of MongoDB. Recently at the MongoSF conference, Dwight Merriman, co-founder and CEO of 10gen, discussed the concurrency internals of MongoDB v2.2 (future release). Dwight described that MongoDB 2.2 did a major refactor to add database level concurrency, and will soon have collection level concurrency now that the hard part of the concurrency refactoring is done. Also keep in mind, writes are in RAM and eventually get synced to disk since MongoDB uses a memory mapped files. Writes are not as expensive as if you were always waiting to sync to disk. Speed can mitigate concurrency issues.
This is not to say that MongoDB will never have some shortcomings and engineering tradeoffs. Also, you can, will and sometimes should combine MongoDB with a relational database or a full text search like Solr/Lucene for some applications. For example, if you run into issue with effectively building indexes to speed some queries you might need to combine MongoDB with Memcached. None of this is completely foreign though, as it is not uncommon to pair RDBMS with Memcached or Lucene/Solr. When to use MongoDB and when to develop a hybrid solution is beyond the scope of this article. In fact, when to use a SQL/RDBMS or another NoSQL solution is beyond the scope of this article, but it would be nice to hear more discussion on this topic.
The price you pay for MongoDB, one of the youngest but perhaps best managed NoSQL solution, is lack of maturity. It does not have a code base going back three decades like RDBMS systems. It does not have tons and tons of third party management and development tools. There have been issues, there are issues and there will be issues, but MongoDB seems to work well for a broad class of applications, and is rapidly addressing many issues.
Also finding skilled developers, ops (admins, devops, etc.) that are familiar with MongoDB or other NoSQL solutions might be tough. Somehow MongoDB seems to be the most approachable or perhaps just best marketed. Having worked on projects that used large NoSQL deployments, few people on the team really understand the product (limitations, etc.), which leads to trouble.
In short if you are kicking the tires of NoSQL, starting with MongoDB makes a lot of sense.
MongoDB concepts
MongoDB is document oriented but has many comparable concepts to traditional SQL/RDBMS solutions.
- Oracle: Schema, Tables, Rows, Columns
- MySQL: Database, Tables, Rows, Columns
- MongoDB: Database, Collections, Document, Fields
- MySQL/Oracle: Indexes
- MongoDB: Indexes
- MySQL/Oracle: Stored Procedures
- MongoDB: Stored JavaScript
- Oracle/MySQL: Database Schema
- MongoDB: Schema free!
- Oracle/MySQL: Foreign keys, and joins
- MongoDB: DBRefs, but mostly handled by client code
- Oracle/MySQL: Primary key
- MongoDB: ObjectID
If you have used MySQL or Oracle here is a good guide to similar processes in MongoDB:
You can see a trend here. Where possible, Mongo tries to follow the terminology of MySQL. They do this with console commands as well. If you are used to using MySQL, where possible, MongoDB tries to make the transition a bit less painful.
SQL operations versus MongoDB operations
MongoDB queries are similar in concept to SQL queries and use a lot of the same terminology. There is no special language or syntax to execute MongoDB queries; you simply assemble a JSON object. The MongoDB site has a complete set of example queries done in both SQL and MongoDB JSON docs to highlight the conceptual similarities. What follows is several small listings to compare MongoDB operations to SQL.
Insert
SQL
INSERT INTO CONTACTS (NAME, PHONE_NUMBER) VALUES('RICK HIGHTOWER','520-555-1212')
MongoDB
db.contacts.insert({name:'RICK HIGHTOWER',phoneNumber:'520-555-1212'})
Selects
SQL
SELECT name, phone_number FROM contacts WHERE age=30 ORDER BY name DESC
MongoDB
db.contacts.find({age:30}, {name:1,phoneNumber:1}).sort({name:-1})
SQL
SELECT name, phone_number FROM contacts WHERE age>30 ORDER BY name DESC
MongoDB
db.contacts.find({age:{$gt:33}}, {name:1,phoneNumber:1}).sort({name:-1})
Creating indexes
SQL
CREATE INDEX contact_name_idx ON contact(name DESC)
MongoDB
db.contacts.ensureIndex({name:-1})
Updates
SQL
UPDATE contacts SET phoneNumber='415-555-1212' WHERE name='Rick Hightower'
MongoDB
db.contacts.update({name:'Rick Hightower'}, {$set:{phoneNumber:1}}, false, true)
Additional features of note
MongoDB has many useful features like Geo Indexing (How close am I to X?), distributed file storage, capped collection (older documents auto-deleted), aggregation framework (like SQL projections for distributed nodes without the complexities of MapReduce for basic operations on distributed nodes), load sharing for reads via replication, auto sharding for scaling writes, high availability, and your choice of durability (journaling) and/or data safety (make sure a copy exists on other servers).
Architecture Replica Sets, Autosharding
The model of MongoDB is such that you can start basic and use features as your growth/needs change without too much trouble or change in design. MongoDB uses replica sets to provide read scalability, and high availability. Autosharding is used to scale writes (and reads). Replica sets and autosharding go hand in hand if you need mass scale out. With MongoDB scaling out seems easier than traditional approaches as many things seem to come built-in and happen automatically. Less operation/administration and a lower TCO than other solutions seems likely. However you still need capacity planning (good guess), monitoring (test your guess), and the ability to determine your current needs (adjust your guess).
Replica Sets
The major advantages of replica sets are business continuity through high availability, data safety through data redundancy, and read scalability through load sharing (reads). Replica sets use a share nothing architecture. A fair bit of the brains of replica sets is in the client libraries. The client libraries are replica set aware. With replica sets, MongoDB language drivers know the current primary. Langauge driver is a library for a particular programing language, think JDBC driver or ODBC driver, but for MongoDB. All write operations go to the primary. If the primary is down, the drivers know how to get to the new primary (an elected new primary), this is auto failover for high availability. The data is replicated after writing. Drivers always write to the replica set's primary (called the master), the master then replicates to slaves. The primary is not fixed. The master/primary is nominated.
Typically you have at least three MongoDB instances in a replica set on different server machines (see figure 2). You can add more replicas of the primary if you like for read scalability, but you only need three for high availability failover. There is a way to sort of get down to two, but let's leave that out for this article. Except for this small tidbit, there are advantages of having three versus two in general. If you have two instances and one goes down, the remaining instance has 200% more load than before. If you have three instances and one goes down, the load for the remaining instances only go up by 50%. If you run your boxes at 50% capacity typically and you have an outage that means your boxes will run at 75% capacity until you get the remaining box repaired or replaced. If business continuity is your thing or important for your application, then having at least three instances in a replica set sounds like a good plan anyway (not all applications need it).
Figure 2: Replica Sets
In general, once replication is setup it just works. However, in your monitoring, which is easy to do in MongoDB, you want to see how fast data is getting replicated from the primary (master) to replicas (slaves). The slower the replication is, the dirtier your reads are. The replication is by default async (non-blocking). Slave data and primary data can be out of sync for however long it takes to do the replication. There are already whole books written just on making Mongo scalable, if you work at a Foursquare like company or a company where high availability is very important, and use Mongo, I suggest reading such a book.
By default replication is non-blocking/async. This might be acceptable for some data (category descriptions in an online store), but not other data (shopping cart's credit card transaction data). For important data, the client can block until data is replicated on all servers or written to the journal (journaling is optional). The client can force the master to sync to slaves before continuing. This sync blocking is slower. Async/non-blocking is faster and is often described as eventual consistency. Waiting for a master to sync is a form of data safety. There are several forms of data safety and options available to MongoDB from syncing to at least one other server to waiting for the data to be written to a journal (durability). Here is a list of some data safety options for MongoDB:
- Wait until write has happened on all replicas
- Wait until write is on two servers (primary and one other)
- Wait until write has occurred on majority of replicas
- Wait until write operation has been written to journal
(The above is not an exhaustive list of options.) The key word of each option above is wait. The more syncing and durability the more waiting, and harder it is to scale cost effectively.
Journaling: Is durability overvalued if RAM is the new Disk? Data Safety versus durability
It may seem strange to some that journaling was added as late as version 1.8 to MongoDB. Journaling is only now the default for 64 bit OS for MongoDB 2.0. Prior to that, you typically used replication to make sure write operations were copied to a replica before proceeding if the data was very important. The thought being that one server might go down, but two servers are very unlikely to go down at the same time. Unless somebody backs a truck over a high voltage utility poll causing all of your air conditioning equipment to stop working long enough for all of your servers to overheat at once, but that never happens (it happened to Rackspace and Amazon). And if you were worried about this, you would have replication across availability zones, but I digress.
At one point MongoDB did not have single server durability, now it does with addition of journaling. But, this is far from a moot point. The general thought from MongoDB community was and maybe still is that to achieve Web Scale, durability was thing of the past. After all memory is the new disk. If you could get the data on second server or two, then the chances of them all going down at once is very, very low. How often do servers go down these days? What are the chances of two servers going down at once? The general thought from MongoDB community was (is?) durability is overvalued and was just not Web Scale. Whether this is a valid point or not, there was much fun made about this at MongoDB's expense (rated R, Mature 17+).
As you recall MongoDB uses memory mapped file for its storage engine so it could be a while for the data in memory to get synced to disk by the operating system. Thus if you did have several machines go down at once (which should be very rare), complete recoverability would be impossible. There were workaround with tradeoffs, for example to get around this (now non issue) or minimize this issue, you could force MongoDB to do an fsync of the data in memory to the file system, but as you guessed even with a RAID level four and a really awesome server that can get slow quick. The moral of the story is MongoDB has journaling as well as many other options so you can decide what the best engineering tradeoff in data safety, raw speed and scalability. You get to pick. Choose wisely.
The reality is that no solution offers "complete" reliability, and if you are willing to allow for some loss (which you can with some data), you can get enormous improvements in speed and scale. Let's face it your virtual farm game data is just not as important as Wells Fargo's bank transactions. I know your mom will get upset when she loses the virtual tractor she bought for her virtual farm with her virtual money, but unless she pays real money she will likely get over it. I've lost a few posts on twitter over the years, and I have not sued once. If your servers have an uptime of 99 percent and you block/replicate to three servers than the probability of them all going down at once is (0.000001) so the probability of them all going down is 1 in 1,000,000. Of course uptime of modern operating systems (Linux) is much higher than this so one in 100,000,000 or more is possible with just three servers. Amazon EC2 offers discounts if they can't maintain an SLA of 99.95% (other cloud providers have even higher SLAs). If you were worried about geographic problems you could replicate to another availability zone or geographic area connected with a high-speed WAN. How much speed and reliability do you need? How much money do you have?
An article on when to use MongoDB journaling versus older recommendations will be a welcome addition. Generally it seems journaling is mostly a requirement for very sensitive financial data and single server solutions. Your results may vary, and don't trust my math, it has been a few years since I got a B+ in statistics, and I am no expert on SLA of modern commodity servers (the above was just spit balling).
If you have ever used a single non-clustered RDBMS system for a production system that relied on frequent backups and transaction log (journaling) for data safety, raise your hand. Ok, if you raised your hand, then you just may not need autosharding or replica sets. To start with MongoDB, just use a single server with journaling turned on. If you require speed, you can configure MongoDB journaling to batch writes to the journal (which is the default). This is a good model to start out with and probably very much like quite a few application you already worked on (assuming that most application don't need high availability). The difference is, of course, if later your application deemed to need high availability, read scalability, or write scalability, MongoDB has your covered. Also setting up high availability seems easier on MongoDB than other more established solutions.
If you can afford two other servers and your app reads more than it writes, you can get improved high availability and increased read scalability with replica sets. If your application is write intensive then you might need autosharding. The point is you don't have to be Facebook or Twitter to use MongoDB. You can even be working on a one-off dinky application. MongoDB scales down as well as up.
Autosharding
Replica sets are good for failover and speeding up reads, but to speed up writes, you need autosharding. According to a talk by Roger Bodamer on Scaling with MongoDB, 90% of projects do not need autosharding. Conversely almost all projects will benefit from replication and high availability provided by replica sets. Also once MongoDB improves its concurrency in version 2.2 and beyond, it may be the case that 97% of projects don't need autosharding.
Sharding allows MongoDB to scale horizontally. Sharding is also called partitioning. You partition each of your servers a portion of the data to hold or the system does this for you. MongoDB can automatically change partitions for optimal data distribution and load balancing, and it allows you to elastically add new nodes (MongoDB instances). How to setup autosharding is beyond the scope of this introductory article. Autosharding can support automatic failover (along with replica sets). There is no single point of failure. Remember 90% of deployments don’t need sharding, but if you do need scalable writes (apps like Foursquare, Twitter, etc.), then autosharding was designed to work with minimal impact on your client code.
There are three main process actors for autosharding: mongod (database daemon), mongos, and the client driver library. Each mongod instance gets a shard. Mongod is the process that manages databases, and collections. Mongos is a router, it routes writes to the correct mongod instance for autosharding. Mongos also handles looking for which shards will have data for a query. To the client driver, mongos looks like a mongod process more or less (autosharding is transparent to the client drivers).
Figure 4: MongoDB Autosharding
Autosharding increases write and read throughput, and helps with scale out. Replica sets are for high availability and read throughput. You can combine them as shown in figure 5.
Figure 5: MongoDB Autosharding plus Replica Sets for scalable reads, scalable writes, and high availability
You shard on an indexed field in a document. Mongos collaborates with config servers (mongod instances acting as config servers), which have the shard topology (where do the key ranges live). Shards are just normal mongod instances. Config servers hold meta-data about the cluster and are also mongodb instances.
Shards are further broken down into 64 MB chunks called chunks. A chunk is 64 MB worth of documents for a collection. Config servers hold which shard the chunks live in. The autosharding happens by moving these chunks around and distributing them into individual shards. The mongos processes have a balancer routine that wakes up so often, it checks to see how many chunks a particular shard has. If a particular shard has too many chunks (nine more chunks than another shard), then mongos starts to move data from one shard to another to balance the data capacity amongst the shards. Once the data is moved then the config servers are updated in a two phase commit (updates to shard topology are only allowed if all three config servers are up).
The config servers contain a versioned shard topology and are the gatekeeper for autosharding balancing. This topology maps which shard has which keys. The config servers are like DNS server for shards. The mongos process uses config servers to find where shard keys live. Mongod instances are shards that can be replicated using replica sets for high availability. Mongos and config server processes do not need to be on their own server and can live on a primary box of a replica set for example. For sharding you need at least three config servers, and shard topologies cannot change unless all three are up at the same time. This ensures consistency of the shard topology. The full autosharding topology is show in figure 6. An excellent talk on the internals of MongoDB sharding was done by Kristina Chodorow, author of Scaling MongoDB, at OSCON 2011 if you would like to know more.
Figure 6: MongoDB Autosharding full topology for large deployment including Replica Sets, Mongos routers, Mongod Instance, and Config Servers
MapReduce
MongoDB has MapReduce capabilities for batch processing similar to Hadoop. Massive aggregation is possible through the divide and conquer nature of MapReduce. Before the Aggregation Framework MongoDB's MapReduced could be used instead to implement what you might do with SQL projections (Group/By SQL). MongoDB also added the aggregation framework, which negates the need for MapReduce for common aggregation cases. In MongoDB, Map and Reduce functions are written in JavaScript. These functions are executed on servers (mongod), this allows the code to be next to data that it is operating on (think stored procedures, but meant to execute on distributed nodes and then collected and filtered). The results can be copied to a results collections.
MongoDB also provides incremental MapReduce. This allows you to run MapReduce jobs over collections, and then later run a second job but only over new documents in the collection. You can use this to reduce work required by merging new data into existing results collection.
Aggregation Framework
The Aggregation Framework was added in MongoDB 2.1. It is similar to SQL group by. Before the Aggregation framework, you had to use MapReduce for things like SQL's group by. Using the Aggregation framework capabilities is easier than MapReduce. Let's cover a small set of aggregation functions and their SQL equivalents inspired by the Mongo docs as follows:.
Count
SQL
SELECT COUNT(*) FROM employees
MongoDB
db.users.employees([ { $group: {_id:null, count:{$sum:1}} } ])
Sum salary where of each employee who are not retired by department
SQL
SELECT dept_name SUM(salary) FROM employees WHERE retired=false GROUP BY dept_name
MongoDB
db.orders.aggregate([ { $match:{retired:false} }, { $group:{_id:"$dept_name",total:{$sum:"$salary"}} } ])
This is quite an improvement over using MapReduce for common projections like these. Mongo will take care of collecting and summing the results from multiple shards if need be.
Installing MongoDB
Let's mix in some code samples to try out along with the concepts.
To install MongoDB go to their download page, download and untar/unzip the download to ~/mongodb-platform-version/. Next you want to create the directory that will hold the data and create a mongodb.config file (/etc/mongodb/mongodb.config) that points to said directory as follows:
Listing: Installing MongoDB
$ sudo mkdir /etc/mongodb/data $ cat /etc/mongodb/mongodb.config dbpath=/etc/mongodb/data
The /etc/mongodb/mongodb.config has one line dbpath=/etc/mongodb/data that tells mongo where to put the data. Next, you need to link mongodb to /usr/local/mongodb and then add it to the path environment variable as follows:
Listing: Setting up MongoDB on your path
$ sudo ln -s ~/mongodb-platform-version/ /usr/local/mongodb $ export PATH=$PATH:/usr/local/mongodb/bin
Run the server passing the configuration file that we created earlier.
Listing: Running the MongoDB server
$ mongod --config /etc/mongodb/mongodb.config
Mongo comes with a nice console application called mongo that let's you execute commands and JavaScript. JavaScript to Mongo is what PL/SQL is to Oracle's database. Let's fire up the console app, and poke around.
Firing up the mongos console application
$ mongo MongoDB shell version: 2.0.4 connecting to: test … > db.version() 2.0.4 >
One of the nice things about MongoDB is the self describing console. It is easy to see what commands a MongoDB database supports with the db.help() as follows:
Client: mongo db.help()
>Status() - returns if profiling is on and slow threshold db.getReplicationInfo() db.getSiblingDB(name) get the db at the same server as this one db.isMaster() check replica primary status db.killOp(opid) kills the current operation in the db db.listCommands() lists all the db commands db.logout() db.fsyncLock() flush data to disk and lock server for backups db.fsyncUnock() unlocks server following a db.fsyncLock()
You can see some of the commands refer to concepts we discussed earlier. Now let's create a employee collection, and do some CRUD operations on it.
Create Employee Collection
> use tutorial; switched to db tutorial > db.getCollectionNames(); [ ] > db.employees.insert({name:'Rick Hightower', gender:'m', gender:'m', phone:'520-555-1212', age:42}); Mon Apr 23 23:50:24 [FileAllocator] allocating new datafile /etc/mongodb/data/tutorial.ns, ...
The use command uses a database. If that database does not exist, it will be lazily created the first time we access it (write to it). The db object refers to the current database. The current database does not have any document collections to start with (this is why db.getCollections() returns an empty list). To create a document collection, just insert a new document. Collections like databases are lazily created when they are actually used. You can see that two collections are created when we inserted our first document into the employees collection as follows:
> db.getCollectionNames(); [ "employees", "system.indexes" ]
The first collection is our employees collection and the second collection is used to hold onto indexes we create.
To list all employees you just call the find method on the employees collection.
> db.employees.find() { "_id" : ObjectId("4f964d3000b5874e7a163895"), "name" : "Rick Hightower", "gender" : "m", "phone" : "520-555-1212", "age" : 42 }
The above is the query syntax for MongoDB. There is not a separate SQL like language. You just execute JavaScript code, passing documents, which are just JavaScript associative arrays, err, I mean JavaScript objects. To find a particular employee, you do this:
> db.employees.find({name:"Bob"})
Bob quit so to find another employee, you would do this:
> db.employees.find({name:"Rick Hightower"}) { "_id" : ObjectId("4f964d3000b5874e7a163895"), "name" : "Rick Hightower", "gender" : "m", "phone" : "520-555-1212", "age" : 42 }
The console application just prints out the document right to the screen. I don't feel 42. At least I am not 100 as shown by this query:
> db.employees.find({age:{$lt:100}}) { "_id" : ObjectId("4f964d3000b5874e7a163895"), "name" : "Rick Hightower", "gender" : "m", "phone" : "520-555-1212", "age" : 42 }
Notice to get employees less than a 100, you pass a document with a subdocument, the key is the operator ($lt), and the value is the value (100). Mongo supports all of the operators you would expect like $lt for less than, $gt for greater than, etc. If you know JavaScript, it is easy to inspect fields of a document, as follows:
> db.employees.find({age:{$lt:100}})[0].name Rick Hightower
If we were going to query, sort or shard on employees.name, then we would need to create an index as follows:
db.employees.ensureIndex({name:1}); //ascending index, descending would be -1
Indexing by default is a blocking operation, so if you are indexing a large collection, it could take several minutes and perhaps much longer. This is not something you want to do casually on a production system. There are options to build indexes as a background task, to setup a unique index, and complications around indexing on replica sets, and much more. If you are running queries that rely on certain indexes to be performant, you can check to see if an index exists with
db.employees.getIndexes(). You can also see a list of indexes as follows:
> db.system.indexes.find() { "v" : 1, "key" : { "_id" : 1 }, "ns" : "tutorial.employees", "name" : "_id_" }
By default all documents get an object id. If you don't not give it an object an _id, it will be assigned one by the system (like a criminal suspects gets a lawyer). You can use that _id to look up an object as follows with findOne:
> db.employees.findOne({_id : ObjectId("4f964d3000b5874e7a163895")}) { "_id" : ObjectId("4f964d3000b5874e7a163895"), "name" : "Rick Hightower", "gender" : "m", "phone" : "520-555-1212", "age" : 42 }
Java and MongoDB
Pssst! Here is a dirtly little secret. Don't tell your Node.js friends or Ruby friends this. More Java developers use MongoDB than Ruby and Node.js. They just are not as loud about it. Using MongoDB with Java is very easy.
The language driver for Java seems to be a straight port of something written with JavaScript in mind, and the usuability suffers a bit because Java does not have literals for maps/objects like JavaScript does. Thus an API written for a dynamic langauge does not quite fit Java. There can be a lot of useability improvement in the MongoDB Java langauge driver (hint, hint). There are alternatives to using just the straight MongoDB language driver, but I have not picked a clear winner (mjorm, morphia, and Spring data MongoDB support). I'd love just some usuability improvements in the core driver without the typical Java annotation fetish, perhaps a nice Java DAO DSL (see section on criteria DSL if you follow the link).
Setting up Java and MongoDB
Let's go ahead and get started then with Java and MongoDB.
Download latest mongo driver from github (), then put it somewhere, and then add it to your classpath as follows:
$ mkdir tools/mongodb/lib $ cp mongo-2.7.3.jar tools/mongodb/lib
Assuming you are using Eclipse, but if not by now you know how to translate these instructions to your IDE anyway. The short story is put the mongo jar file on your classpath. You can put the jar file anywhere, but I like to keep mine in ~/tools/.
If you are using Eclipse it is best to create a classpath variable so other projects can use the same variable and not go through the trouble. Create new Eclipse Java project in a new Workspace. Now right click your new project, open the project properties, go to the Java Build Path->Libraries->Add Variable->Configure Variable shown in figure 7.
Figure 7: Adding Mongo jar file as a classpath variable in Eclipse
For Eclipse from the "Project Properties->Java Build Path->Libraries", click "Add Variable", select "MONGO", click "Extend…", select the jar file you just downloaded.
Figure 8: Adding Mongo jar file to your project
Once you have it all setup, working with Java and MongoDB is quite easy as shown in figure 9.
Figure 9 Using MongoDB from Eclipse
The above is roughly equivalent to the console/JavaScript code that we were doing earlier. The BasicDBObject is a type of Map with some convenience methods added. The DBCursor is like a JDBC ResultSet. You execute queries with DBColleciton. There is no query syntax, just finder methods on the collection object. The output from the above is:
Out: { "_id" : { "$oid" : "4f964d3000b5874e7a163895"} , "name" : "Rick Hightower" , "gender" : "m" , "phone" : "520-555-1212" , "age" : 42.0} { "_id" : { "$oid" : "4f984cce72320612f8f432bb"} , "name" : "Diana Hightower" , "gender" : "f" , "phone" : "520-555-1212" , "age" : 30}
Once you create some documents, querying for them is quite simple as show in figure 10.
Figure 10: Using Java to query MongoDB
The output from figure 10 is as follows:
Rick? { "_id" : { "$oid" : "4f964d3000b5874e7a163895"} , "name" : "Rick Hightower" , "gender" : "m" , "phone" : "520-555-1212" , "age" : 42.0} Diana? { "_id" : { "$oid" : "4f984cae72329d0ecd8716c8"} , "name" : "Diana Hightower" , "gender" : "f" , "phone" : "520-555-1212" , "age" : 30} Diana by object id? { "_id" : { "$oid" : "4f984cce72320612f8f432bb"} , "name" : "Diana Hightower" , "gender" : "f" , "phone" : "520-555-1212" , "age" : 30}
Just in case anybody wants to cut and paste any of the above, here it is again all in one go in the following listing.
Listing: Complete Java Listing
package com.mammatustech.mongo.tutorial; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.DB; public class Mongo1Main { public static void main (String [] args) throws Exception { Mongo mongo = new Mongo(); DB db = mongo.getDB("tutorial"); DBCollection employees = db.getCollection("employees"); employees.insert(new BasicDBObject().append("name", "Diana Hightower") .append("gender", "f").append("phone", "520-555-1212").append("age", 30)); DBCursor cursor = employees.find(); while (cursor.hasNext()) { DBObject object = cursor.next(); System.out.println(object); } //> db.employees.find({name:"Rick Hightower"}) cursor=employees.find(new BasicDBObject().append("name", "Rick Hightower")); System.out.printf("Rick?\n%s\n", cursor.next()); //> db.employees.find({age:{$lt:35}}) BasicDBObject query = new BasicDBObject(); query.put("age", new BasicDBObject("$lt", 35)); cursor=employees.find(query); System.out.printf("Diana?\n%s\n", cursor.next()); //> db.employees.findOne({_id : ObjectId("4f984cce72320612f8f432bb")}) DBObject dbObject = employees.findOne(new BasicDBObject().append("_id", new ObjectId("4f984cce72320612f8f432bb"))); System.out.printf("Diana by object id?\n%s\n", dbObject); } }
Please note that the above is completely missing any error checking, or resource cleanup. You will need do some of course (try/catch/finally, close connection, you know that sort of thing).
Python MongoDB Setup
Setting up Python and MongoDB are quite easy since Python has its own package manager.
To install mongodb lib for Python MAC OSX, you would do the following:
$ sudo env ARCHFLAGS='-arch i386 -arch x86_64' $ python -m easy_install pymongo
To install Python MongoDB on Linux or Windows do the following:
$ easy_install pymongo
or
$ pip install pymongo
If you don't have easy_install on your Linux box you may have to do some
sudo apt-get install python-setuptools or
sudo yum install python-setuptools iterations, although it seems to be usually installed with most Linux distributions these days. If easy_install or pip is not installed on Windows, try reformatting your hard disk and installing a real OS, or if that is too inconvient go here.
Once you have it all setup, you will can create some code that is equivalent to the first console examples as shown in figure 11.
Figure 11: Python code listing part 1
Python does have literals for maps so working with Python is much closer to the JavaScript/Console from earlier than Java is. Like Java there are libraries for Python that work with MongoDB (MongoEngine, MongoKit, and more). Even executing queries is very close to the JavaScript experience as shown in figure 12.
Figure 12: Python code listing part 2
Here is the complete listing to make the cut and paste crowd (like me), happy.
Listing: Complete Python listing
import pymongo from bson.objectid import ObjectId connection = pymongo.Connection() db = connection["tutorial"] employees = db["employees"] employees.insert({"name": "Lucas Hightower", 'gender':'m', 'phone':'520-555-1212', 'age':8}) cursor = db.employees.find() for employee in db.employees.find(): print employee print employees.find({"name":"Rick Hightower"})[0] cursor = employees.find({"age": {"$lt": 35}}) for employee in cursor: print "under 35: %s" % employee diana = employees.find_one({"_id":ObjectId("4f984cce72320612f8f432bb")}) print "Diana %s" % diana
The output for the Python example is as follows:
{u'gender': u'm', u'age': 42.0, u'_id': ObjectId('4f964d3000b5874e7a163895'), u'name': u'Rick Hightower', u'phone': u'520-555-1212'} {u'gender': u'f', u'age': 30, u'_id': ObjectId('4f984cae72329d0ecd8716c8'), u'name': u'Diana Hightower', u'phone': u'520-555-1212'} {u'gender': u'm', u'age': 8, u'_id': ObjectId('4f9e111980cbd54eea000000'), u'name': u'Lucas Hightower', u'phone': u'520-555-1212'}
All of the above but in PHP
Node.js , Ruby, and Python in that order are the trend setter crowd in our industry circa 2012. Java is the corporate crowd, and PHP is the workhorse of the Internet. The "get it done" crowd. You can't have a decent NoSQL solution without having good PHP support.
To install MongoDB support with PHP use pecl as follows:
$ sudo pecl install mongo
Add the mongo.so module to php.ini.
extension=mongo.so
Then assuming you are running it on apache, restart as follows:
$ apachectl stop $ apachectl start
Figure 13 shows our roughly equivalent code listing in PHP.
Figure 13 PHP code listing
The output for figure 13 is as follows:
Output: array ( '_id' => MongoId::__set_state(array( '$id' => '4f964d3000b5874e7a163895', )), 'name' => 'Rick Hightower', 'gender' => 'm', 'phone' => '520-555-1212', 'age' => 42, ) array ( '_id' => MongoId::__set_state(array( '$id' => '4f984cae72329d0ecd8716c8', )), 'name' => 'Diana Hightower', 'gender' => ‘f', 'phone' => '520-555-1212', 'age' => 30, ) array ( '_id' => MongoId::__set_state(array( '$id' => '4f9e170580cbd54f27000000', )), 'gender' => 'm', 'age' => 8, 'name' => 'Lucas Hightower', 'phone' => '520-555-1212', )
The other half of the equation is in figure 14.
Figure 14 PHP code listing
The output for figure 14 is as follows:
Output Rick? array ( '_id' => MongoId..., 'name' => 'Rick Hightower', 'gender' => 'm', 'phone' => '520-555-1212', 'age' => 42, ) Diana? array ( '_id' => MongoId::..., 'name' => 'Diana Hightower', 'gender' => ‘f', 'phone' => '520-555-1212', 'age' => 30, ) Diana by id? array ( '_id' => MongoId::..., 'name' => 'Diana Hightower', 'gender' => 'f', 'phone' => '520-555-1212', 'age' => 30, )
Here is the complete PHP listing.
PHP complete listing
<!--?php $m = new Mongo(); $db = $m->selectDB("tutorial"); $employees = $db->selectCollection("employees"); $cursor = $employees->find(); foreach ($cursor as $employee) { echo var_export ($employee, true) . "< br />"; } $cursor=$employees->find( array( "name" => "Rick Hightower")); echo "Rick? < br /> " . var_export($cursor->getNext(), true); $cursor=$employees->find(array("age" => array('$lt' => 35))); echo "Diana? < br /> " . var_export($cursor->getNext(), true); $cursor=$employees->find(array("_id" => new MongoId("4f984cce72320612f8f432bb"))); echo "Diana by id? < br /> " . var_export($cursor->getNext(), true); ?>
If you like Object mapping to documents you should try the poorly named MongoLoid for PHP
.
Additional shell commands, learning about MongoDB via the console
One of the nice things that I appreciate about MongoDB, that is missing from some other NoSQL implementation, is getting around and finding information with the console application. They seem to closely mimic what can be done in MySQL so if you are familiar with MySQL, you will feel fairly at home in the mongo console.
To list all of the databases being managed by the mongod instance, you would do the following:
> show dbs local (empty) tutorial 0.203125GB
To list the collections being managed by a database you could do this:
> show collections employees system.indexes
To show a list of users, you do the following:
> show users
To look at profiling and logging, you do this:
> show profile db.system.profile is empty Use db.setProfilingLevel(2) will enable profiling .. > show logs global > show log global Mon Apr 23 23:33:14 [initandlisten] MongoDB starting : pid=11773 port=27017 dbpath=/etc/mongodb/data 64-bit… … Mon Apr 23 23:33:14 [initandlisten] options: { config: "/etc/mongodb/mongodb.config", dbpath: "/etc/mongodb/data" }
Also the commands and JavaScript functions themselves have help associated with them. To see all of the operations that DBCollection supports you could do this:
> db.employees.help() DBCollection help db.employees.find().help() - show DBCursor help db.employees.count() db.employees.dataSize() db.employees.distinct( key ) - eg. db.employees.distinct( 'x' ) db.employees.drop() drop the collection db.employees.dropIndex(name) db.employees.dropIndexes() db.employees.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups db.employees.reIndex() db.employees.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. db.employees.find( {x:77} , {name:1, x:1} ) db.employees.find(...).count() db.employees.find(...).limit(n) db.employees.find(...).skip(n) db.employees.find(...).sort(...) db.employees.findOne([query]) db.employees.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } ) db.employees.getDB() get DB object associated with collection db.employees.getIndexes() db.employees.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) db.employees.mapReduce( mapFunction , reduceFunction , {optional params=""} ) db.employees.remove(query) db.employees.renameCollection( newName , {droptarget} ) renames the collection. db.employees.runCommand( name , {options} ) runs a db command with the given name where the first param is the collection name db.employees.save(obj) db.employees.stats() db.employees.storageSize() - includes free space allocated to this collection db.employees.totalIndexSize() - size in bytes of all the indexes db.employees.totalSize() - storage allocated for all data and indexes db.employees.update(query, object[, upsert_bool, multi_bool]) db.employees.validate( {full} ) – SLOW db.employees.getShardVersion() - only for use with sharding db.employees.getShardDistribution() - prints statistics about data distribution in the cluster ...
Just to show a snake eatings its own tail, you can even get help about help as follows:
> help db.help() help on db methods db.mycoll.help() help on collection methods rs.help() help on replica set methods help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things to know help mr mapreduce > help … show dbs show database names show collections show collections in current database show users show users in current database show profile show most recent system.profile entries time>= 1ms show logs show the accessible logger names show log [name] prints out the last segment of log in memory,
The MongoDB console reminds me of a cross between the MySQL console and Python's console. Once you use the console, it is hard to imagine using a NoSQL solution that does not have a decent console (hint, hint).
Conclusion
The poorly named NoSQL movement seems to be here to stay. The need to have reliable storage that can be easily queried without the schema migration pain and scalability woes of traditional RDBMS is increasing. Developers want more agile systems without the pain of schema migration. MongoDB is a good first step for developers dipping their toe into the NoSQL solution space. It provides easy to use tools like its console and provides many language drivers. This article covered the basics of MongoDB architecture, caveats and how to program in MongoDB for Java, PHP, JavaScript and Python developers.
I hope you enjoyed reading this article 1/2 as much as I enjoyed writing it. --Rick Hightower
Resources
- The Little MongoDB Book by Karl Seguin
- Scaling MongoDB book by Kristina Chodorow, O'Reilly Media, January 2011
- MongoSF presentations, 2012, San Francisco CA
- MongoDB documentation website
- Java and Object Relationship Mapping article Mapping by Brian Dilley, 2012
- MongoDB Concurrency Internals v 2.2 presentation by Dwight Merriman, 2012
- MongoDB Sharding Internals video presentation by Kristina Chodorow, 2011
- MongoDB: The Definitive Guide book by Kristina Chodorow and Michael Dirolf, Sep 8, 2010
- Scaling with MongoDB Strangeloop talk hosted on InfoQ by Roger Bodamer
- Some of the ideas of the early success of MongoDB I got by talking to Roger Bodamer
- Initial inspiration for this article was from this slidedeck on MongoDB, and it served as an outline for the article (It might be useful for those who don't have time to read this article, i.e., co-workers, bosses, etc.).
- The site indeed.com has job trends which are useful but not 100% accurate for getting a feel of what people are actually using in the wild devoid of too much slant. There is a rise in job demand for Ninjas.
- Various blogs, and forums
About the Author
Rick Hightower, CTO of Mammatus, has worked as a CTO, Director of Development and a Developer for the last 20 years. He has been involved with J2EE since its inception. He worked at an EJB container company in 1999, and did large scale Java web development since 2000 (JSP, Servlets, etc.). He has been working with Java since 1996 (Python since 1997), and writing code professionally since 1990. Rick was an early Spring enthusiast. Rick enjoys bouncing back and forth between C, PHP, Python, Groovy and Java development. He has written several programming and software development books as well as many articles and editorials for journals and magazines over the years. Lately he has been focusing on NoSQL, and Cloud Computing development.
Informative
by
brian dilley
Great Informative Post
by
omprakash vat
|
http://www.infoq.com/articles/mongodb-java-php-python/
|
CC-MAIN-2014-52
|
refinedweb
| 8,666
| 55.24
|
Building a collection of my common use Sass mixins, functions and snippets. All written with SCSS syntax. Mixins for CSS3 animation, @keyframes and transition defintions.
Curated list of awesome Sass and SCSS frameworks, libraries, style guides, articles, and resources..sass scss css
This is a bare bones HTML/CSS framework. This is what I'll typically start off most web projects with. It includes a CSS reset and a bunch of minimal boilerplate styles that should come in useful for any project, including a responsive grid, typography, buttons, icons and forms.scss responsive-grid boilerplate bootstrap sass html mobile
SASS mixins which makes it easy to use css3 in SASS or SCSS powered projects
PreCSS
Spectre.css is a lightweight, responsive and modern CSS framework. css-framework responsive-grid flexbox utilities modern lightweight framework responsive mobile-friendly front-end sass
Crumpet is a deliciously simple SASS/SCSS responsive framework that keeps your HTML clean & stays out of your way. Tidy HTML - Uses placeholder selectors to reduce the size of your HTML. No one likes messy.sass framework.css sass flexbox responsive front-end framework space150. Breakpoint also allows you to get the context of your media queries from your code, allowing you to write dynamic mixins based on their media query context.sass responsive rwd eyeglass-module breakpoint
include-media is a Sass library for writing CSS media queries in an easy and maintainable way, using a natural and simplistic syntax. I spent quite some time experimenting with different libraries and mixins available out there, but eventually all of them failed to do everything I needed in an elegant way. Some of them wouldn't let me mix set breakpoints with case-specific values, others wouldn't properly handle the CSS OR operator and most of them had a syntax that I found complicated and unnatural.sass scss mediaquery breakpoint eyeglass-module
A progress tracker written in SASS with flexbox to be flexible and responsive out of the box. This can be used to illustrate a multi stage process e.g. form, quiz or a timeline. Once you have downloaded the code, run the commands below to view the demo.scss flexbox progress-tracker sass progress tracker multi step multi-step stage multi-stage css
Example of a two column, responsive, centered grid. All grid layout classes and responsive width classes are modifiers. $av-namespace Global prefix for layout and cell class names. Default: grid.css sass scss bem grid-layout grid oocss libsass scss sass-files scss-files css preprocessor sass style.
|
https://www.findbestopensource.com/product/magnetikonline-sass-boilerplate
|
CC-MAIN-2020-45
|
refinedweb
| 423
| 55.64
|
/* machine description file for hp9000 series 200 or 300 on either HPUX or BSD.="note"
NOTE-START
HP 9000 series 200 or 300 (-machine=hp9000s300)
These machines are 68000-series CPUs running HP-UX
(a derivative of sysV with some BSD features) or BSD 4.3 ported by Utah.
If you're running HP-UX, specify `-opsystem=hpux'.
If you're running BSD, specify `-opsystem=bsd4-3'.
NOTE-END */
/* I don't understand why we have to do this at all! -JimB */
#if 0
/* Do this here at the top of the file; including sys/wait.h may
include <endian.h>, which defines BIG_ENDIAN, which will conflict
with our definition of BIG_ENDIAN if we do this at the bottom. */
#ifndef NOT_C_CODE
#ifndef NO_SHORTNAMES
#include <sys/wait.h>
#define WAITTYPE int
#endif
#define WRETCODE(w) (((w) >> 8) & 0377)
#endif
#endif
/* Define NOMULTIPLEJOBS on versions of HPUX before 6.5. */
/* #define NOMULTIPLEJOBS */
/* Define this symbol if you are running a version of HP-UX
which predates version 6.01 */
/* #define HPUX_5 */
/*. */
#ifndef hp9000s300
#define hp9000s300
#endif
/* */
/* For University of Utah 4.3bsd implementation on HP300s.
The #ifndef __GNUC__ definitions are required for the "standard" cc,
a very old, brain-dead version of PCC. */
#ifdef BSD4_3
/* Tell crt0.c that this is an ordinary 68020. */
#undef hp9000s300
#define m68000
#define CRT0_DUMMIES bogus_a6,
#define HAVE_ALLOCA
#ifndef __GNUC__
#define LIBS_DEBUG /* don't have -lg that works */
#define C_DEBUG_SWITCH /* don't support -g */
#endif
#undef LOAD_AVE_TYPE
#undef LOAD_AVE_CVT
#define LOAD_AVE_TYPE long
#define LOAD_AVE_CVT(x) ((int) (((double) (x)) / 2048.0 * 100.0))
#endif /* BSD4_3 */
#ifndef BSD4_3
/* The following definitions are for HPUX only. */
/* The symbol in the kernel where the load average is found
is named _avenrun on this machine. */
#define LDAV_SYMBOL "_avenrun"
/* Data type of load average, as read out of kmem. */
#define LOAD_AVE_TYPE double
/* Convert that into an integer that is 100 for a load average of 1.0 */
#define LOAD_AVE_CVT(x) ((int) ((x) * 100.0))
#ifdef __GNUC__
#define HAVE_ALLOCA
#endif
/* This library is needed with -g, on the 200/300 only. */
#if !defined(__GNUC__) || defined(__HPUX_ASM__)
#define LIBS_DEBUG /usr/lib/end.o
#endif
/* Need a TEXT_START. On the HP9000/s300 that is 0. */
#ifdef __GNUC__
#define TEXT_START 0
#endif
/* The symbol FIONREAD is defined, but the feature does not work
on the 200/300. */
#define BROKEN_FIONREAD
/* In older versions of hpux, for unknown reasons, S_IFLNK is defined
even though symbolic links do not exist.
Make sure our conditionals based on S_IFLNK are not confused.
Here we assume that stat.h is included before config.h
so that we can override it here.
Version 6 of HP-UX has symbolic links. */
#ifdef HPUX_5
#undef S_IFLNK
#endif
/* Define the BSTRING functions in terms of the sysV functions.
Version 6 of HP-UX supplies these in the BSD library,
but that library has reported bugs in `signal'. */
/* #ifdef HPUX_5 */
#define bcopy(a,b,s) memcpy (b,a,s)
#define bzero(a,s) memset (a,0,s)
#define bcmp memcmp
/* #endif */
/* On USG systems these have different names.
Version 6 of HP-UX supplies these in the BSD library,
which we currently want to avoid using. */
#define index strchr
#define rindex strrchr
/* Define C_SWITCH_MACHINE to be +X if you want the s200/300
* Emacs to run on both 68010 and 68020 based hp-ux's.
*
* Define OLD_HP_ASSEMBLER if you have an ancient assembler
*
* Define HPUX_68010 if you are using the new assembler but
* compiling for a s200 (upgraded) or s310. 68010 based
* processor without 68881.
*/
/* These switches increase the size of some internal C compiler tables.
They are required for compiling the X11 interface files. */
#ifndef HPUX_5
#ifndef __GNUC__
#define C_SWITCH_MACHINE -Wc,-Nd4000,-Ns3000
#endif
#endif
/* Define NEED_BSDTTY if you have such. */
#ifndef NOMULTIPLEJOBS
#define NEED_BSDTTY
#endif
#endif /* not BSD4_3 */
|
https://emba.gnu.org/emacs/emacs/-/blame/5df583315f5e5c9f53473e7ad60fb3a334f05cd2/src/m/hp9000s300.h
|
CC-MAIN-2021-31
|
refinedweb
| 622
| 59.09
|
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
flatland
Flatland maps between rich, structured Python application data and the string-oriented flat namespace of web forms, key/value stores, text files and user input. Flatland provides a schema-driven mapping toolkit with optional data validation.
Flatland is great for:
- Collecting, validating, re-displaying and processing HTML form data
- Dealing with rich structures (lists, dicts, lists of dicts, etc.) in web data
- Validating JSON, YAML, and other structured formats
- Associating arbitrary Python types with JSON, .ini, or sys.argv members that would otherwise deserialize as simple strings.
- Reusing a single data schema for HTML, JSON apis, RPC, ....
Availability
The hg flatland tip can be installed via easy_install flatland==dev.
|
https://bitbucket.org/jek/flatland
|
CC-MAIN-2017-47
|
refinedweb
| 133
| 50.12
|
This is the first part of a series of tutorials on C#. In this part we are introducing the fundamental concepts of the language and it's output, the Microsoft Intermediate Language (MSIL). We will take a look at object-oriented programming (OOP) and what C# does to make OOP as efficient as possible to realize in practice.
For further reading a list of references will be given in the end. The references provide a deeper look at some of the topics discussed in this tutorial.
A little bit of warning before reading this tutorial: The way that this tutorial works is that it defines a path of usability. This part of the tutorial is essentially required before doing anything with C#. After this first tutorial everyone should be able to write a simple C# program using basic object-oriented principles. Hence more advanced or curious readers will probably miss some parts. As an example we will not investigate exception handling, exciting possibilities with the .NET-Framework like LINQ and more advanced language features like generics or lambda expressions. Here our aim is to give a soft introduction to C# for people coming from other languages.
The right development environment
Before we can start doing something we should think about where we want to do something. A logical choice for writing a program is a text editor. In case of C# there is an even better option: using the Microsoft Visual Studio (VS)! However, there are more options, that have been designed specifically with C# in mind. If we want to have a cross-platform IDE then MonoDevelop is a good choice. On Windows a free alternative to VS and MonoDevelop is SharpDevelop.
Using a powerful IDE like Visual Studio will help us a lot when writing programs with the .NET-Framework. Features like IntelliSense (an intelligent version of auto-complete, which shows us the possible method calls, variables and available keywords for a certain code position), breakpoints (the program's execution can be paused and inspected at desired code positions) and graphical designers for UI development will help us a lot in programming efficiently.
Additionally the Visual Studio gives us integrated version control, an object browser and documentation tools. Another bonus for writing C# projects with the Visual Studio is the concept of solutions and projects. In Visual Studio one usually creates a solution for a development project. A solution file can contain several projects, which can be compiled to libraries (.dll) and executables (.exe files). The solution explorer enables us to efficiently manage even large scale projects.
The project files are used by the MSBuild application to compile all required files and link to the dependencies like libraries or the .NET-Framework. We, as a developer, do not need to worry anymore about writing makefiles. Instead we just add files and references (dependencies) to projects, which will be compiled and linked in the right order automatically.
There are several shortcuts / functions that will make VS a real pleasure:
- CTRL + SPACE, which forces IntelliSense to open.
- CTRL + ., which opens the menu if VS shows an option point (this will happen if a namespace is missing or if we rename a variable).
- F5, to build and start debugging.
- CTRL + F5, to build and execute without debugging.
- F6, just build.
- F10, to jump to the next line within the current function (step over) when debugging.
- F11, to jump to the line in the next or current function (step into) when debugging.
- F12, to go to the definition of the identifier at the caret's position.
- SHIFT + F12, to find all references of the identifier at the caret's position.
Of course those keyboard shortcuts can be changed and are not required. Everything that can be done with shortcuts is also accessible by using the mouse. On the other hand there are more options and possibilities than shortcuts.
Where do get the Visual Studio? There are several options, some of them even free. Students enrolled in an university who is participating in the DreamSparks / MSDNAA program usually have the option of download Visual Studio (up to Ultimate) for free. Otherwise one can download public beta versions or language-bound specialized versions of the Visual Studio, called Express Edition.
In this tutorial we will only focus on console applications. GUI will be introduced in the next tutorial. To create a new console application project in VS we simple have to use the menu File: Then we select New, Project. In the dialog we select C# on the left side and then Console application on the right side. Finally we can give our project a name like SampleConsoleApp. That's it! We already created our first C# application.
Basic concepts
C# is a managed, static strong-typed language with a C like syntax and object-oriented features similar to Java. All in all one can say that C# is very close to Java to start with. There are some really great features in the current version of C#, but in this first tutorial we exclude them.
The managed means two things: First of all we do not need to care about the memory anymore. This means that people coming from C or C++ can stop worrying about freeing the memory allocated for their objects. We only create objects and do something with them. Once we stopped using them, a smart program called the Garbage Collector (GC) will take care of them. The next figure shows how the Garbage Collector works approximately. It will detect unreferenced objects, collect them and free the corresponding memory. We do not have much control about the point in time when this is happening. Additionally the GC will do some memory optimization, however, this is usually not done directly after freeing the memory.
This results in some overhead on the memory and performance side, but has the advantage that it is basically impossible to have segmentation faults in C#. However, memory leaks are still a problem if we keep references of objects that are no longer required.
The static strong-typed language means that the C# compiler needs to know the exact type of every variable and that the type-system must be coherent. There is no cast to a
void datatype, which lets us basically do anything, however, we have a datatype called
Object on top, which might result in similar problems. We will discuss the consequences of the
Object base type later on. The strong part gives us a hint that operations may only be used if the operation is defined for the elements. There are no explicit casts happening without our knowledge.
We have another consequence of C# being managed: C# is not native, nor interpreted - it is something between. The compiler generates no assembly code, but the so called Microsoft Intermediate Language (MSIL). This trick saves us the re-compilations for different platforms. In case of C# we just compile once and obtain a so called Common Language Runtime (CLR) assembly. This assembly will be Just-In-Time (JIT) compiled during runtime. Another feature is that optimizations will also take place during runtime. Often occurring method calls will be in-lined and not required statements will be omitted automatically.
In theory this could result in (depending on the used references) platform-independent programs, however, this implies that all platforms have the requirements to start and JIT compile CLR assemblies. Right now Microsoft limits the .NET-Framework to the Windows family, however, Xamarin offers a product called Mono, which gives us a solution that also works on Linux and Mac.
Coming back to the language itself we will see that the object-oriented features are inspired by those of Java. In C# only a slightly different set of keywords has been used. The
extend keyword of Java has been replaced by the C++ operator colon
:. There are other areas where the colon has been used an operator with a different (but related) meaning.
Let's have a look at a sample Hello Tech.Pro code.
//Those are the namespaces that are (by default) included using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; //By default Visual Studio creates already a namespace namespace HelloWorld { //Remember: Everything (variables, functions) has to be encapsulated class Program { //The entry point is called Main (capital M) and has to be static static void Main(string[] args) { //Writing something to the console is easily possible using the //class Console with the static method Write or WriteLine Console.WriteLine("Hello Tech.Pro!"); } } }
This looks quite similar to Java, except the casing. Comments can be placed by using slashes (comment goes until the end of the line with no possibility to switch back before), or using a slash and an asterisk character. In the latter case the comment has to be ended with the reverse, i.e. an asterisk and a slash. This kind of comment is called a block comment. Visual Studio also has a special mode of comments, that is triggered once three slashes are entered.
Back to the code: While we do not need to place our classes in a namespace, Visual Studio creates one by default. The creation of a class is, however, required. Every method and variable needs to be encapsulated. This is why C# is considered to be strongly-object-oriented. Data encapsulation is, as we will see, an important feature of object-oriented programming and therefore necessary in C#.
There are already some other things that we can learn from this small sample. First, C# uses (as it has to) a class called
Console for console based interaction. This class only contains so called static members like the
WriteLine function. A static member is such a member that can be accessed without creating an instance of the class, i.e. static members cannot be reproduced. They only exist once and exist without being explicitly created. Functions of a class are called methods.
The main entry point called
Main can only exist once, which is why it has to be
static. Another reason is that it has to live in a class. If it would not be static, the class would first have to be created (as all non-static members can only be accessed by created objects called instances of a class). Now we have a chicken-and-egg problem. How can we tell the program to build an instance of the class (such that the
Main method can be accessed), without having a method where we start doing something? Hence the requirement on the
Main method being
static.
Another thing we can learn is that the parameter
args is obviously an array. It seems that an array is used as a datatype, whereas in C the variable is the array and the type would be string. This is by design and has some useful implications. We will later see that every array is based on an object-oriented principle called inheritance, which specifies a basic set of fields and implementations. Every array type has a field called
Length, which contains the number of elements in the array. This is no longer hidden and needs to be passed as an additional parameter, which is why the standard
Main method of a C# program only has 1 parameter compared to the standard C
main method with 2 parameters.
Namespaces
Namespaces might be a new concept for people coming from the C programming language. Namespaces try to bring order to the world of types. Even though C# allows us to have multiple methods with the same name (called method overloading), but a unique signature (return type and parameters), it does not allow us to use the same name for a type.
This restriction could result in serious problems. If we consider the case of using (requiring) two (independent) internal libraries, it is possible that both libraries define a type with the same name. Now there would be no way to use both types (if compiling would be possible at all!). At best we could use one type.
This is where namespaces come to rescue. A namespace is like a container where we can place types in. However, that container is only a string that will be used by the compiler to distinguish between types. Even though the dot (like in
a.b) is usually used to create the impression of an relation between two strings (in this case
a and
b), there is no restriction that a namespace has to exist before creating another one it it, e.g.
a has not to be defined or used somewhere before using
a.b.
Usually we would have to place that namespace in front of every type always, however, using C#'s
using keyword we tell the compiler to implicitly do that for all types of the used namespace. Types of the current namespace are also implicitly used by the compiler. There is only one exception i.e., if we want to use a type that is defined in multiple used namespaces. In that scenario, we always have to explicitly specify the namespace of the type we want to use.
Datatypes and operators
Before we can actually start doing something we need to introduce the basic set of datatypes and operators. As already mentioned C# is a static strongly-typed language, which is why we need to care about datatypes. In the end we will have to specify what's the type behind any variable.
There is a set of elementary datatypes, which contains the following types:
bool(1 byte) used for logical expressions (true, false)
char(2 bytes) used for a single (unicode) character
short(2 bytes) used for storing short integers
int(4 bytes) used for computations with integers
long(8 bytes) used for computations with long integers
float(4 bytes) used for computations with single precision floating point numbers
double(8 bytes) used for computations with double precision floating point numbers
decimal(16 bytes) used for computations with fixed precision floating point numbers
There are also modified datatypes like unsigned integer (
uint), unsigned long (
ulong) and many more available. Additionally a really well working class for using strings has been delivered. The class is just called
string and works as one would expect, except that a lot of useful helpers are directly available.
Types alone are quite boring, since we can only instantiate them, i.e. create objects based on their definition. It gets more interesting once we connect them by using operators. In C# we have the same set of operators (and more) as in C:
- Logical operators like
==,
!=,
<,
<=,
>,
>=,
!,
&&,
||
- Bit operators like
^,
&,
|,
<<,
>>
- Arithmetic operators like
+,
-,
*,
/,
%,
++,
--
- The assignment operator
=and combinations of the assignment operator with the binary operators
- The ternary operator
? :(inline condition) to return either the left or right side of the colon depending on a condition specified before the question mark
- Brackets
()to change the operator hierarchy
Additionally C# has some inbuilt-methods (defined as unary operators) like
typeof or
sizeof and a set of really useful type operators:
- The standard cast operator
()as in C
- The reference cast operator
as
- The type conformance checker
is
- The null-coalescing operator
??
- The inheritance operator
:
Let's see some of those types and operators in action:
using System; class Program { static void Main(string[] args) { //5 here is an integer literal int a = 5; //A double value is a floating point literal. double x = 2.5 + 3.7; //A single value is given by a floating point literal with the suffix f. float y = 3.1f; //Using quotes will automatically generated constant strings string someLiteral = "This is a string!"; string input = Console.ReadLine(); //int, string, double, float, ... are just keywords - in fact, they are represented //by Int32, String, Double, Single - which have static (and non-static) members. a = int.Parse(input);//Here we use the static method [int Parse(string)] of Int32. //Output of a mod operation - adding string and something (or something and string) //will always result in a string. Additionally we have the regular operator ordering //which performs a % 10 before the string and a get concatenated. Console.WriteLine("a % 10 = " + a % 10); } }
We will see more operators and basic types in action throughout this series of tutorials. It should be noted that all operators will by default return a new type, leaving the original variable unchanged. Another important aspect is there is a fixed operator hierarchy, which is basically like the operator hierarchy in C. We do not need to learn this, since we can always use brackets to change the default hierarchy. Additionally the operator hierarchy is quite natural in following rules like dot before dash, i.e. multiplication and division before addition and subtraction.
Reference and value types
A very important concept for understanding C# is the difference between reference and value types. Once we use a
class, we are using a reference type. On the other side any object that is a
struct will be handled as a value type. The important difference is that reference types will be passed by reference, i.e. we will only pass a copy of the position of the object, and not a copy of the object itself. Any modification on the object will result in a modification on the original object.
The other case is the one with value types. If we give a method an argument that is a
struct (that includes integers, floating point numbers, a boolean, a character and more) we will get a copy of the passed object. This means that modifications on the argument will never result in a modification on the original object.
The whole concept is quite similar to the the concept of pointers in C. The only difference is that we do not actually have access to the address and we do not have to dereference the variable to get access to the values behind it. One could say that C# handles some of the things automatically that we would have to write by hand in C/C++.
In C# we have access to two keywords that can be passed together with the argument definition. One important keyword is called
ref. This allows us to access the original value in the case of passing in structures. For classes the consequence is that the original pointer is actually passed in, allowing us to change the position of it. This sounds quite strange at first, but we will see that in most cases there is no difference between an explicit
ref on a class instance to an implicit by just passing the class. The only difference is that we can actually reset the pointer, like in the following code.
using System; class Program { static void Main() { //A string is a class, which can be instantiated like this string s = "Hi there"; Console.WriteLine(s);//Hi there ChangeString(s); Console.WriteLine(s);//Hi there ChangeString(ref s); Console.WriteLine(s);//s is now a null reference } static void ChangeString(string str) { str = null; } static void ChangeString(ref string str) { str = null; } }
The other important keyword is called
out. Basically
out is like
ref. There are a few differences that are worth mentioning:
outvariables need to be assigned in the method that has them as parameters.
outvariables do not need to be assigned in the method that passes them as parameters.
outvariables mark the variable as being used for (additional) outgoing information.
The main usage of
out parameters is as the name suggests: We now have an option to distinguish between "just" references and parameters, which will actually return something. The .NET-Framework uses
out parameters in some scenarios. Some of those scenarios are the
TryParse methods found on the basic structures like
int,
double and others. Here a
bool is returned, giving us an indicator if the given
string can be converted. In case of a successful conversion the variable given in form of an
out parameter will be set to the corresponding value.
All the talk about reference (
class) and value (
struct) types is useless if we do not know how to create such types. Let's have a look at a simple example:
using System; class Program { static void Main(string[] args) { //Usually C# forbids us to leave variables unitialized SampleClass sampleClass; SampleStruct sampleStruct; //However, C# thinks that an out-Function will do the initialization HaveALook(out sampleClass); HaveALook(out sampleStruct); } static void HaveALook(out SampleClass c) { //Insert a breakpoint here to see the //value of s before the assignment: //It will be null... c = new SampleClass(); } static void HaveALook(out SampleStruct s) { //Insert a breakpoint here to see the //value of s before the assignment: //It will NOT be null... s = new SampleStruct(); } //In C# you can created nested classes class SampleClass { } //A structure always inherits ONLY from object, //we cannot specify other classes (more on that later) //However, an arbitrary number of interfaces can //be implemented (more on that later as well) struct SampleStruct { } }
In the example above we are creating two types called
SampleClass and
SampleStruct. We can instantiate new objects from those type definitions using the
new keyword. This is not new (pun intended) for programmers coming from Java or C++, but certainly something new for programmers coming from C. In C we would use the
malloc function in case of a class (giving us a pointer) and nothing with a structure (giving us a value). There is, however, one big advantage of using that
new keyword: It will not only do the right memory allocation (on the heap in case of a reference type, or the stack in case of a value type), but also call the corresponding constructor. We will later see what a constructor is, and what kind of benefits it gives us.
Coming back to our example we see that we do not instantiate anything with the
new keyword in the
Main method, however, we do use it in the methods called
HaveALook, which differ by the parameter type they expect. Using breakpoints in those methods we can see that the class variable is actually NOT set (the passed in value of the variable is
null, which is the constant for a pointer that is not set), while the structure has already some value.
Control flow
Now that we introduced the basic concepts behind C#, as well as elementary datatypes and available operators, we just need one more thing before we can actually go ahead and write actual C# programs. We need to know how to control the program flow, i.e. how to introduce conditions and loops.
This is pretty much the same as in C, as we are dealing with a C-style syntax. That being said we have to follow these rules:
- Conditions can be introduced by using
ifor
switch.
- A loop is possible by using
for,
while,
do-
while.
- A loop will be stopped by using the
breakkeyword (will stop the most inner loop).
- A loop can skip the rest and return to the condition with the
continuekeyword.
- C# also has an iterator loop called
foreach.
- Another possibility is the infamous
gotostatement - we will not discuss this.
- There are other ways of controlling the program flow, but we will introduce those later.
The next program code will introduce a few of the mentioned possibilities.
using System; class Program { static void Main(string[] args) { //We get some user input with the ReadLine() method string input = Console.ReadLine(); //Let's see if this is empty or not if(input == "") { Console.WriteLine("The input is empty!"); } else { //A string is a char array and has a Length property //It also can be accessed like a char array, giving //us single chars. for(int i = 0; i < input.Length; i++) { switch(input[i]) { case 'a': Console.Write("An a - and not ... "); //This is always required, we cannot just fall through. goto case 'z'; case 'z': Console.WriteLine("A z!"); break; default: Console.WriteLine("Whatever ..."); //This is required even in the last block break; } } } } }
The iterator loop called
foreach is not available in C. It is possible to use
foreach with every type that defines some kind of iterator. We will see what this means later on. For now we only have to know that every array already defines such an iterator. The following code snippet will use the
foreach-loop to output each element of an array.
//Creating an array is possible by just appending [] to any datatype int[] myints = new int[4]; //This is now a fixed array with 4 elements. Arrays in C# are 0-based //hence the first element has index 0. myints[0] = 2; myints[1] = 3; myints[2] = 17; myints[3] = 24; //This foreach construct is new in C# (compared to C++): foreach(int myint in myints) { //Write will not start a new line after the string. Console.Write("The element is given by "); //WriteLine will do that. Console.WriteLine(myint); }
There are some restrictions on
foreach as compared to
for. First of all, it is not as efficient as a
for-loop, taking one more operation to start the loop, and calling always the iterators
Next method at the end of each iteration. Second we cannot change the current element. This is due to the fact that
foreach operates on iterators, which are in general immutable, i.e. a single element cannot be changed. This is also required to keep the iteration consistent.
Object-oriented programming
Object-oriented programming is a method of focusing around objects instead of functions. Therefore the declaration of types is a key aspect of object-oriented programming. Everything has to be part of a type, even if it is just static without any instance dependency.
There are downsides of this pattern of course. Instead of writing
sin(),
cos(),
sign() etc. we have to write
Math.Sin(),
Math.Cos() and
Math.Sign() since the (very helpful) math functions need to be inside a type (in this case the class
Math) as well.
So what are the key aspects of object-oriented programming?
- Data encapsulation
- Inheritance
- Relations between types
- Declaring dependencies
- Maintainability
- Readability
By creating classes to carry large, reusable packages of data we provide encapsulation. The inheritance process helps us mark a strong relation between types and reuse the same basic structure. Encapsulating functions in types will group what belongs together and reduce code by omitting required parameters. Also misusage will be prevented by default. All in all, the main goal is too reduce maintenance efforts by improving readability and increasing the compiler's power in error detection.
The main concept for OOP is the type-focus. The central type is certainly a class. Structures are also important, but will only be used in edge cases. Structures make sense if we have only a small payload, or want to create quite elementary small types that will have stronger immutable features than classes.
Let's have a look again at how we create a class (the type) and how we create class objects (instances):
//Create a class definition class MyClass { public void Write(string name) { Console.WriteLine("Hi there... {0}!", name); } } //Create a class instance (code to be placed in a method) MyClass instance = new MyClass();
A class makes sense once we want to reuse a set of methods with a fixed set of variables additionally to some parameters for those methods. A class is also very useful once we want to use an already existing set of variables and / or methods. If we just want a collection of functions that is unrelated to any set of fixed (called instance dependent) variables, then we create static classes where we can just insert static methods and variables. Good examples of such static classes are the
Console and
Math class. They cannot be instantiated (instances of static classes, i.e. classes that do not contain instance dependent code, do not make any sense) and provide only functions with a set of parameters.
Inheritance and polymorphism
Now we are coming to the inheritance issue. To simplify things we can think of inheritance as a recursive copy paste process by the compiler. All members of the parent (
base) class will be copied.
class MySubClass : MyClass { public void WriteMore() { Console.WriteLine("Hi again!"); } }
As already mentioned the inheritance operator is the
:. In this example we create a new type called
MySubClass, which inherits from
MyClass.
MyClass has been defined in the previous section and does not define an explicit inheritance. Therefore
MyClass inherits from
Object.
Object itself just defines four methods, that are:
ToString, which is a very comfortable way of defining how an instance of the type should presented as a string.
Equals, which is a generic way of comparing two arbitrary objects of equality.
GetHashCode, which gets a numeric indicator if two objects could be equal.
GetType, which gets the meta-information on the specific type of the current instance.
These four methods are available at
MyClass and
MySubClass instances (copy paste!). Additionally
MyClass defines a method called
Write, which will also be available for all
MySubClass instances. Finally
MySubClass defines a method called
WriteMore, which will only be available for
MySubClass instances.
Right now the inheritance concept is already a little bit useful, but it is not very powerful. The concept of polymorphism will enable us to specialize objects using inheritance. First we will introduce the
virtual keyword. This keyword lets us specify that a (
virtual marked) method can be re-implemented by more specialized (or derived) classes.
class MyClass { //This method is now marked as re-implementable public virtual void Write(string name) { //Using a placeholder in a string.Format()-able method Console.WriteLine("Hi {0} from MyClass!", name); } }
If we now want to re-implement the
Write method in the
MySubClass class, then we have to do that explicitly by marking the re-implementation as
override. Let's have a look:
class MySubClass : MyClass { //This method is now marked as re-implemented public override void Write(string name) { Console.WriteLine("Hi {0} from MySubClass!", name); } }
What is the great benefit of this? Let's check out some example code snippet:
//We create two variables of type MyClass MyClass a = new MyClass(); MyClass b = new MySubClass(); //Now we call the Write() method on each of them, the only //difference being that in fact b is a more specialized type a.Write("Flo"); //Outputs ... from MyClass! b.Write("Flo"); //Outputs ... from MySubClass!
So the trick is that without knowing about the more specialized instance behind it, we are able to access to specialized implementation available in
mySubClass. This is called polymorphism and basically states that classes can re-implement certain methods, which can then be used again without knowing about the specialization or re-implementation at all.
Already here we can benefit from polymorphism, since we are able to
override the four methods given by
Object. Let's consider the following example:
using System; class Program { static void Main(string[] args) { MyClassOne one = new MyClassOne(); MyClassTwo two = new MyClassTwo(); Console.WriteLine(one);//Displays a strange string that is basically the type's name Console.WriteLine(two);//Displays "This is my own class output" } } class MyClassOne { /* Here we do not override anything */ } class MyClassTwo { public override string ToString() { return "This is my own class output"; } }
Here the method
WriteLine solves the problem of having to display any input as a sequence of characters by using the
ToString method of
Object. This enables
WriteLine to output any object, even objects that are unknown. Everything that
WriteLine cares about is that the given argument is actually an instance of
Object (that applies to every object in C#), which means that the argument has a
ToString method. Finally the specific
ToString method of the argument is called.
Access modifiers
Access modifiers play an important rule in forcing programmers to apply to a given object-oriented design. They hide members to prevent undefined access, define which members take part in the inheritance process and what objects are visible outside of a library.
Right here we already have to note that all restrictions placed by modifiers are only artificial. The compiler is the only protector of those rules. This means that those rules will not prevent unauthorized access to e.g. a variable during runtime. Therefore setting access modifiers to spawn some kind of security system is certainly a really bad idea. The main idea behind those modifiers is the same as with object-oriented programming: Creating classes that encapsulate data and force other programmers in a certain pattern of access. This way, finding the right way of using certain objects should be simpler and more straight forward.
C# knows a whole bunch of such modifier keywords. Let's have a look at them with a short description:
private, declares that a member is neither visible from outside the object, nor does it take part in the inheritance process.
protected, declares that a member is not visible from outside the object, however, the member takes part in the inheritance process.
internal, declares that a member or type is visible outside the object, but not outside the current library.
internal protected, has the meaning of
internalOR
protected.
public, declares that a member or type is visible everywhere.
Most of the time we can specify the modifier (there are some exceptions to this rule, as we will see later), however, we can also always omit it. For types directly placed in a namespace, the default modifier is
internal. This makes quite some sense. For types and members placed in a type (like a class or structure), the default modifier is
private.
This makes sense since it is just a best practice from C++: We always should have started with a
private declaration in C++, otherwise every member would have been
public (this has been one of the bad design decisions of C++). So while C++ took the way of taking the weakest access modifier as standard (
public), C# always uses the strongest one (
internal or
private).
using System; //No modifier, i.e. the class Program is internal class Program { //No modifier, i.e. the method Main() is private static void Main() { MyClass c = new MyClass(); //Works int num = c.WhatNumber(); //Does not work //int num = c.RightNumber(); } } //MyClass is visible from this library and other libraries public class MyClass { //This one can only be accessed from MyClass private int a; //Classes inheriting from MyClass can access b like MyClass can protected int b; //No modifier, i.e. the method RightNumber() is private int RightNumber() { return a; } //This will be seen from the outside public int WhatNumber() { //Access inside the class is possible return RightNumber(); } } //MySubClass is only visible from this library internal class MySubClass : MyClass { int AnotherRightNumber() { //Works b = 8; //Does not work - a cannot be accessed since it is private return a; } }
There are some restrictions that will be enforced by the compiler. The reverse case of the example above, where we set
MyClass
internal and
MySubClass
public is not possible. The compiler detects, that having
MySubClass visible to the outside must require
MyClass to also be visible to the outside. Otherwise we have a specialization of a type where the basic type is unknown.
The same is true in general, like when we return an instance of a type that is
internal in a method that is visible to the outside (
public with the type being
public). In this case the compiler will also tell us that the type that is returned has a stronger access modifier set.
In C# every non-static method has access to the class instance pointer variable
this. This variable is treated like a keyword and points to the current class instance. Usually the keyword can be omitted before calling methods of the class instance, however, there are multiple scenarios where the
this is very useful.
One of those scenarios is to distinguish between local and global variables. Consider the following example:
class MyClass { string str; public void Change(string str) { //Here this.str is the global variable str and //str is the local (passed as parameter) variable this.str = str; } }
Since methods marked as
static are independent of instances, we cannot use the
this keyword. Additionally to the
this pointer there is also a
base pointer, which gives us access to all (for the derived class accessible) members of the base class instance. This way it is possible to call already re-implemented or hidden methods.
class MySubClass : MyClass { public override void Write(string name) { //First we want to use the original implementation base.Write(name); //Then our own Console.WriteLine("Hi {0} from MySubClass!", name); } }
In the example, we are accessing the original implementation of the
Write method from the re-implementation.
Properties
People coming from C++ will know the problem of restricting access to variables of a class. In generally one should never expose variables of a class, such that other classes could change it without the class being notified. Therefore the following piece of code was written quite often in C++ (code given in C#):
private int myVariable; public int GetMyVariable() { return myVariable; } public void SetMyVariable(int value) { myVariable = value; }
This is a clean code and we (as developers) now have the possibility to react to variable's external changes by inserting some lines of code before
myVariable = value. The problem with this code is that
- we really only want to show that this is just a wrapper around
myVariableand that
- we need to write too much code for this simple pattern.
Therefore the C# team introduced a new language feature called properties. Using properties the code above boils down to:
private int myVariable; public int MyVariable { get { return myVariable; } set { myVariable = value; } }
This looks much cleaner now. Also the access changed. Before we accessed
myVariable like a method (using
a = GetMyVariable() or
SetMyVariable(b)), but now we access myVariable like a variable (using
a = MyVariable or
MyVariable = b). This is more like the programmer's original intention and saves us some lines of code.
Internally the compiler will still create those (get / set) methods, but we do not care about this. We will just use properties with either a
get block, a
set block, or both, and everything will work.
The constructor
The constructor is a special kind of method that can only be called implicitly and never explicitly. A constructor is automatically called when we allocate memory with the
new keyword. In perfect alignment with standard methods, we can overload the constructor by having multiple definitions that differ by their parameters.
Every class (and structure) has at least one constructor. If we did not write one (until now we did not), then the compiler places a standard (no parameters, empty body) constructor. Once we define one constructor, the compiler does not insert a default constructor.
The signature of a constructor is special. It has no return type, since it does implicitly return the new instance, i.e. an instance of the class. Also a constructor is defined by its name, which is the same name as the class. Let's have a look at some constructors:
class MyClass { public MyClass() { //Empty default constructor } public MyClass(int a) { //Constructor with one argument } public MyClass(int a, string b) { //Constructor with two arguments } public MyClass(int a, int b) { //Another constructor with two arguments } }
This looks quite straight forward. In short, a constructor is a method with the name of the class that specifies no return value. Using the various constructors is possible when instantiating an object of the class.
MyClass a = new MyClass();//Uses the default constructor MyClass b = new MyClass(2);//Uses the constructor with 1 argument MyClass c = new MyClass(2, "a");//Uses the constructor with 2 arguments MyClass d = new MyClass(2, 3);//Uses the other constructor with 2 arguments
Of course it could be that one constructor would need to do the same work as another constructor. In this case it seems like we only have two options:
- Copy & paste the content.
- Extracting the content into a method, which is then called by both constructors.
The first is a simple no-go after the DRY (Don't Repeat Yourself) principle. The second one is maybe also not fine, since this could result in the method being abused on other locations. Therefore C# introduces the concept of chaining constructors. Before we actually execute instructions from one constructor, we call another constructor. The syntax relies on the colon
: and the current class instance pointer
this:
class MyClass { public MyClass() : this(1, 1) //This calls the constructor with 2 arguments { } public MyClass(int a, int b) { //Do something with a and b } }
Here the default constructor uses the constructor with 2 parameters to do some initialization work. The initialization work is the most popular use-case of a constructor. A constructor should be a lightweight method that does some preprocessing / setup / variable initialization.
The colon operator for the constructor chaining is used for a reason. Like with inheritance every constructor has to call another constructor. If no call is specified (i.e. no previous constructor), then the called constructor is the default constructor of the base class. Therefore the second constructor in the previous example does actually look like the following:
public MyClass(int a, int b) : base() { //Do something with a and b }
The additional line is, however, redundant, since the compiler will automatically insert this. There are only two cases where we have to specify the base constructor for the constructor chaining:
- When we actually want to call another base constructor than the default constructor of the base class.
- and When there is no default constructor of the base class.
The reason for the constructor chaining with the base class constructor is illustrated in the next figure.
We see that in this class hierarchy in order to create an instance of
Porsche, an instance of
Car has to be created. This creation, however, requires the creation of an instance of a
Vehicle, which requires the instantiation of
Object. Each instantiation is associated with calling a constructor, which has to be specified. The C# compiler will automatically call the empty constructor, but this is only possible in case such a constructor exists. Otherwise we have to tell the compiler explicitly what to call.
There are also cases where other access modifiers for a constructor might make sense. If we want to prevent instantiation of a certain type (like with
abstract), we could create one default constructor and make it
protected. On the other hand the following is a simple so-called Singleton pattern:
class MyClass { private static MyClass instance; private MyClass() { } public static MyClass Instance { get { if(instance == null) instance = new MyClass(); return instance; } } }
Now we cannot create instances of the class, but we can access the static property
Instance by using
MyClass.Instance. This property not only has access to the static variable
instance, but also has access to all
private members like the
private constructor. Therefore, it can create an instance and return the created instance.
This implementation has two main advantages:
- Because the instance is created inside the
Instanceproperty method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.
- The instantiation is not performed until an object asks for an instance. This approach is referred to as lazy instantiation. This avoids instantiating unnecessary singletons when the application starts.
We will not discuss other design patterns in this series of tutorials.
Abstract classes and interfaces
There is one more thing we need to discuss in this tutorial. Sometimes we want to create classes that should just be a sketch for some more specialized implementations. This is like creating a template for classes. We do not want to use the template directly (instantiate it), but we want to derive from the class (use the template), which should save us some time. The keyword for marking a class as being a template is
abstract. Abstract classes cannot be instantiated, but can be used as types of course. Such a class can also mark members as being
abstract. This will require derived classes to deliver the implementation:
abstract class MyClass { public abstract void Write(string name); } class MySubClass : MyClass { public override void Write(string name) { Console.WriteLine("Hi {0} from an implementation of Write!", name); } }
Here we mark the
Write method as being abstract, which has two consequences:
- There is no method body (the curly brackets are missing) in the first method definition.
MySubClassis required to
overridethe
Writemethod (or in general: all methods that are marked
abstractand not implemented yet).
Also the following code will fail, since we create an instance of
MyClass, which is now marked as being abstract.
//Ouch, MyClass is abstract! MyClass a = new MyClass(); //This works fine, MyClass can still be used as a type MyClass b = new MySubClass();
An important restriction in doing OOP with C# is the limitation to inheritance from one class only. If we do not specify a base class then
Object will be used implicitly otherwise the explicitly specified class will be used. The restriction to one class in the inheritance process makes sense, since it keeps everything well-defined and prohibits weird edge cases. There is an elegant way around this limitation, which builds upon using so called
interface types.
An
interface is like a code-contract. Interfaces define which functionalities should be provided by the classes or structures that implement them, but they do not say any word about how the exact function looks like. That being said we can think of those interfaces as abstract classes without variables and with only
abstract members (methods, properties, ...).
Let's define a very simple interface:
interface MyInterface { void DoSomething(); string GetSomething(int number); }
The defined interface contains two methods called
DoSomething and
GetSomething. The definitions of these methods look very similar to the definitions of abstract methods, except we are missing the keywords
public and
abstract. This is by design. The idea is that since every member of an interface is
abstract (or to be more precise: misses an implementation), the keyword is redundant. Another feature is that every method is automatically being treated as
public.
Implementing an interface is possible by using the same syntax as with classes. Let's consider two examples:
class MyOtherClass : MyInterface { public void DoSomething() { } public string GetSomething(int number) { return number.ToString(); } } class MySubSubClass : MySubClass, MyInterface { public void DoSomething() { } public string GetSomething(int number) { return number.ToString(); } }
This snippet should demonstrate a few things:
- It is possible to implement only one interface and no class (this will result in inheriting directly from
Object)
- We can also implement one ore more interfaces and additionally a class (explicit inheritance)
- We always have to implement all methods of the "inherited" interface(s)
- Also as a side note we do not need to re-implement
Writemethod on the
MySubSubClass, since
MySubClassalready implements this
It should be clear that we cannot instantiate interfaces (they are like abstract classes), but we can use them as types. Therefore it would be possible to do the following:
MyInterface myif = new MySubSubClass();
Usually interface types start with a big I in the .NET-Framework. This is a useful convention to recognize interfaces immediately. In our journey, we will discover some useful interfaces that are quite important for the .NET-Framework. Some of these interfaces are used by C# implicitly.
Interfaces also gives us another option for implementing their methods. Since we can implement multiple interfaces, it is possible that two methods with the same name and signature will be included. In this case there must be a way to distinguish between the different implementations. This is possible by a so-called explicit implementation. An explicitly implemented interface will not contribute to the class directly. Instead one has to cast the class to the specific interface type in order to access the members of the interface.
Here is an explicit implementation:
class MySubSubClass : MySubClass, MyInterface { //Explicit (no public and MyInterface in front) void MyInterface.DoSomething() { } //Explicit (no public and MyInterface in front) string MyInterface.GetSomething(int number) { return number.ToString(); } }
Explicit and implicit implementations of definitions from an interface can be mixed. Hence we can only be sure to get access to all members defined by an interface, if we cast an instance to that interface.
Exception handling
There are many things that have been designed with OOP in mind in C#. One of those things is exception handling. Every exception has to derive from the
Exception class, which has been placed in the
System namespace. In general we should always try to avoid exceptions, however, there are cases where an exception could easily happen. One such example is found in communication with the file system. Here we are talking to the OS, which sometimes has no other choice than to throw an exception. There could be various reasons, e.g.:
- The given path is invalid.
- The file cannot be found.
- We do not have sufficient rights to access the files.
- The file is corrupt and cannot be read.
Of course the OS API could just return a pseudo file or pseudo content and everything would work. The problem with such a handling is that this does not represent reality, and we would have no way to detect that obviously something went wrong. Another option would be to return an error code, but this would result in a C like API and it would leave the handling to the programmer. If the programmer now would do a bad job (like ignoring the returned error code), the user would never see that something went wrong.
Here is where exceptions come into play. The important thing about an exception is that once an exception is possible, we should think about handling it. In order to handle such an exception, we need a way to react to it. The construct is the same as in C++ or Java: Thrown exceptions can be caught.
try { FunctionWhichMightThrowException(); } catch { //React to it }
In the example, we call a method named
FunctionWhichMightThrowException. Calling this method might result in an exception, which is why we put it in a
try-block. The
catch-block is only entered if an exception is thrown, otherwise it will be ignored. What this example is not capable of doing is reacting to the specific exception. Right now we just react to any exception, without touching the exception that has been thrown. This is, however, very important and should therefore be done:
try { FunctionWhichMightThrowException(); } catch(Exception ex) { //React to it e.g. Console.WriteLine(ex.Message); }
Since every exception has to derive from
Exception, this will always work and we will always be able to access to the property
Message. This is a so called catch'em all block. Sometimes, however, we want to distinguish between the various exceptions. Coming back to our example with the file system above, we can expect that every unique scenario (e.g. path invalid, file not found, insufficient rights, ...) will throw a different kind of exception. We could differentiate between those exceptions by defining more
catch-blocks:
byte[] content = null; try { content = File.ReadAllBytes(/* ... */); } catch (PathTooLongException) { //React if the path is too long } catch (FileNotFoundException) { //React if the file has not been found } catch (UnauthorizedAccessException) { //React if we have insufficient rights } catch (IOException) { //React to a general IO exception } catch (Exception) { //React to any exception that is not yet handled }
There should be two lessons from this example.
- We can specify multiple
catch-blocks, each with its own handling. The only limitation is that we should specify it in such a order, that the most general exception is called last, while the most specific is first.
- We do not need to name the variable of the exception. If we name it we will get access to the
Exceptionobject, but sometimes we do not care about the specific object. Instead we just want to differentiate between the various exceptions.
Now that we can catch those nasty exceptions, we may want to throw exceptions ourselves. This is done by using the
throw keyword. Let's see some sample code:
void MyBuggyMethod() { Console.WriteLine("Entering my method"); throw new Exception("This is my exception"); Console.WriteLine("Leaving my method"); }
If we call this method we will see that the second
WriteLine method will not be called. Once an exception is thrown the method is left immediately. This goes on until a suitable
try-
catch-block is wrapping the method call. If no such block is found then the application will crash. This behavior is called bubbling. Alternatively we could have also written our own class that derives from
Exception:
class MyException : Exception { public MyException : this("This is my exception") { } }
Now our code above could have been changed to become the following:
void MyBuggyMethod() { Console.WriteLine("Entering my method"); throw new MyException(); Console.WriteLine("Leaving my method"); }
Coming back again to our example that plays around with the file system. In this scenario we might end up with some open file handle. Therefore, whether we get some exception or not, we want to close that handle to clean up the open resources. In this scenario another block would be very helpful. A block that performs a final action that does not depend on the actions in the
try or any
catch block. Of course such a block exists and is called a
finally-block.
FileStream fs = null; try { fs = new FileStream("Path to the file", FileMode.Open); /* ... */ } catch(Exception) { Console.WriteLine("An exception occurred."); return; } finally { if(fs != null) fs.Close(); }
Here we should note that
return in one block will still call the code in the
finally-block. So in total we have the option of using a
try-
catch, a
try-
catch-
finally or a
try-
finally block. The last one will not catch the exception (i.e. the exception will bubble up), but still invoke the code that is given in the
finally-block (no matter what happens in the
try-block).
Outlook
In the next tutorial we will learn about more advanced features in C# and extend our knowledge in object-oriented programming. With our knowledge in C# improving, we are ready to dive more into the .NET-Framework.
Thanks a lot for this tutorial!! It helps me a lot in preparing my Ms in Bioinformatics!!!
One of the finest tutorials on C# I've seen. I really like the "advanced beginner" angle... This is just what the doctor ordered... I had to wade through so much to understand the fundamentals of C# and this helped me cement my understanding of a few things that I was struggling to wrap my head around (i.e. the nuances of inheritance).
Great Work!!
Thanks a lot! I'm really glad you liked it and found it useful.
Wonderful tutorial. Thanks very much
Thanks a lot. I'm glad that you like it!
Greate Article~!. I m novice to using on C++ , Someday, I want to learn about C#.
C# is definitely worth a look. It is clean and gives you a quick and reliable way of creating (even HUGE) projects. Also the language itself contains some really nice features, which make programming look easy.
Great article, although it was mainly about what OOP is rather than the language itself. I'm definitely reading the next ones to learn more about C#, though. One thing: in the code block where you create your own exception you don't inherit System.Exception. I don't know enough about C# to be sure this is wrong, but it sure looks wrong. :)
You are right, my mistake. I corrected the code snippet. Since my lecture makes no strong requirement on knowing about OOP (and C# is a lot about OOP) I have to cover it (briefly). The next one will go deeper into features of C#, I promise!
Thanks for your feedback!
This is great stuff, I look forward to your next tutorial!
Thanks a lot! It should be up very soon.
I assume there is a typo where there are two access modifiers named 'internal'? Is there an external?
There is kind of a typo (to be more precise: a formatting mistake). It should be
internal protected(instead of
internalprotected). I will correct this! C# also has a keyword called
extern, but this is no modifier. In fact
externtells the compiler that the defined method is implemented externally (the keyword is used in combination with library imports over the
DllImportflag). Thanks for the comment!
|
http://tech.pro/tutorial/1172/an-advanced-introduction-to-c
|
CC-MAIN-2014-42
|
refinedweb
| 9,412
| 54.63
|
I'm currently writing part of a lab program for a data structures class I'm taking. I'm only partway into the lab, so there's not much written at the moment.
First, let me apologize in advance. This code will be a bit messy, as the last two CS classes I had were not in C++, and it's been almost a year since I've coded much of anything (last semester's class was Computer Organization, taught with MIPS32 and such).
I'm encountering a seg fault. The gdb debugger's report on the segfault is as follows:
I have narrowed down the search to what seems to be the problem code, but I don't see anything wrong with it... The problem code, and the related variable, are underlined.I have narrowed down the search to what seems to be the problem code, but I don't see anything wrong with it... The problem code, and the related variable, are underlined.Code:Program received signal SIGSEGV, Segmentation fault. __strlen_sse2 () at ../sysdeps/x86_64/multiarch/../strlen.S:31 31 ../sysdeps/x86_64/multiarch/../strlen.S: No such file or directory. in ../sysdeps/x86_64/multiarch/../strlen.S
I'm unfamiliar with s.find and string::npos. I pulled them off a reference site, and attempted to use them, so I wouldn't be surprised if that's where the problem was.I'm unfamiliar with s.find and string::npos. I pulled them off a reference site, and attempted to use them, so I wouldn't be surprised if that's where the problem was.Code:#include <iostream> #include <fstream> #include <string> #include <map> #include <cstdlib> #include <iomanip> using namespace std; class Song{ public: string title; int time; int track; }; class Album{ public: map <int, Song*> songs; string name; int time; }; class Artist{ public: map <string, Album*> albums; string name; int time; int nsongs; }; int main(int argc, char* argv[]) { ifstream fin; string filename; int min; int sec; int time; size_t found; string s; Song* curSong; filename = argv[1]; if(argc == 2 && filename.find(".txt") != string::npos){ fin.open(argv[1]); if(fin.fail()){ cerr << "Problem opening " << filename << endl; exit(1); } } else{ cerr << "Please use format: lib_info filename.txt\n"; exit(1); } while(!fin.eof()){ fin >> s; for(found = s.find("_"); found != string::npos; found = s.find("_")) { s.replace(found, 1, " "); } curSong->title = s; fin >> s; sscanf(s.c_str(), "%d:%d", &min, &sec); curSong->time = min*60 + sec; fin >> s; fin >> s; fin >> s; fin >> s; sscanf(s.c_str(), "%i", &(curSong->track)); } return (0); }
In case it's needed, here's a sample input file.
Code:Countdown 2:25 Coltrane,_John Giant_Steps Jazz 3 Down_In_Brazil 6:07 Walton,_Cedar Naima Jazz 4 Giant_Steps 4:02 Puente,_Tito El_Rey Jazz 5 Giant_Steps 4:46 Coltrane,_John Giant_Steps Jazz 1 Mr._P.C. 7:02 Coltrane,_John Giant_Steps Jazz 7 Naima 4:24 Coltrane,_John Giant_Steps Jazz 6 Naima 5:16 Lyle,_Bobby Night_Breeze Jazz 5 Naima 5:36 Tjader,_Cal A_Fuego_Vivo Jazz 6 Naima 7:49 Walton,_Cedar Naima Jazz 6 Naima 8:38 Walton,_Cedar Eastern_Rebellion Jazz 2 This_Guy's_In_Love_With_You 8:10 Walton,_Cedar Naima Jazz 2
|
http://cboard.cprogramming.com/cplusplus-programming/140561-can%27t-solve-certain-seg-fault.html
|
CC-MAIN-2015-48
|
refinedweb
| 529
| 72.36
|
Before I start I am not asking for anyone to JUST give me the answer, but I would like help on where to go and what it means when I am told to add blank here.
My assignment this week deals with creating a date program. I have to have a user input and it must follow the correct formatting or else the program needs to inform the user that it is incorrect. Format is 02/11 (month/day) It will then convert the numbers into "February 11"
Here is what I have so far. I am stuck and could use a little push in the right direction.
import java.util.Scanner; public class DateDriver { public static void main (String [] args) { Scanner scan = new Scanner(System.in); Date date = new Date(); System.out.println("Enter a date in the form mm/dd ('q' to quit): "); String quit = scan.next(); if (quit.equals("q") || quit.equals("Q")) { // } else { System.out.println(""); } } }
public class Date { int month; int day; public Date(int month, int day) { month = month; day = day; } public int getMonth() { return month; } public int getDay() { return day; } }
Thanks for all the help in advanace. I would like to stress that I want to do the work I just do not understand exactly what I am doing.
This post has been edited by macosxnerd101: 20 September 2011 - 01:12 PM
Reason for edit:: Renamed title to be more descriptive
|
http://www.dreamincode.net/forums/topic/247921-date-formatting-program/
|
CC-MAIN-2016-40
|
refinedweb
| 238
| 71.34
|
Subject: [ggl] Headers order (was: problems with Boost Geometry Xcode compile?)
From: Mateusz Loskot (mateusz)
Date: 2010-03-11 16:48:57
Bruno Lalande wrote:
>>.
Bruno,
You're right, of course.
I wasn't referring to macros only, but to all definitions, to headers
as a whole.
> So it makes sense to include everything that can declare a weird
> macro as late as possible. :-) ).
Aha once again! Generally, I agree :-) but specifically I don't really
believe it's robust enough to make it a strong convention.
Quick test with GCC shows that even if I really want to be C++ purist,
I'm being offered with pile of unrelated garbage:
#include <iostream>
#ifdef _GNU_SOURCE
#error _GNU_SOURCE
#endif
#ifdef _POSIX_SOURCE
#error _POSIX_SOURCE
#endif
#ifdef _XOPEN_SOURCE
#error _XOPEN_SOURCE
#endif
#ifdef _SVID_SOURCE
#error _SVID_SOURCE
#endif
#ifdef _ISOC99_SOURCE
#error _ISOC99_SOURCE
#endif
int main(){}
$ g++ -Wall -pedantic -std=c++98 -ansi test.cpp
test.cpp:3:2: error: #error _GNU_SOURCE
test.cpp:6:2: error: #error _POSIX_SOURCE
test.cpp:9:2: error: #error _XOPEN_SOURCE
test.cpp:12:2: error: #error _SVID_SOURCE
test.cpp:15:2: error: #error _ISOC99_SOURCE
>>.
Yes, you've clarified it to me above.
> But the rule I gave can't be a general rule anyway: when it comes to
> include some headers in the .h and others in the .cpp, you can't
> satisfy it in all cases. You have to find compromises.
Yes, that's right. Practical conclusion seems to sound that we should
not care about the order, but I think it's a good idea to not to freely
spread and interleave headers, but to keep things clean.
As I said, I do agree with the order you proposed.
Best regards,
-- Mateusz Loskot, Charter Member of OSGeo,
Geometry list run by mateusz at loskot.net
|
https://lists.boost.org/geometry/2010/03/0674.php
|
CC-MAIN-2020-34
|
refinedweb
| 297
| 67.76
|
Ben Hyde wrote:
>
> Ben Laurie writes:
> >Dean Gaudet wrote:
> >>
> >> How about someone describe the actual difficulties that lead to this whole
> >> gc discussion before we take it any further?
> >>
> >>...
> >
> >Cheers,
> >
> >Ben.
>
> Ok, but ... My model of pools is that they are owned by some activity,
> and when that activity completes they are reclaimed. Activites
> are usually implemented by a single thread, or process. Of course
> not always, for example a pool owned by a module for it's internal
> state who's life cycle is delimeted the init file loading.
>
> When an activity happens not to have it's own thread/process there is
> always one who's extent is longer than the activity and the pool can
> nest inside of it.
>
> Having a single root pool is nicer, to my sense of style, than using
> NULL as the root since it leaves clear the sequencing and certainty of
> how things are torndown. Leaving a few globals in the namespace for
> generally useful pools? My eyes see that as is useful, rather than
> noisy.
Currently the root pool is not global (I haven't checked the status in
apache-nspr, though, but I assume it hasn't changed) - and there is no
global pool that persists over a reset (which is exactly why you'd use a
NULL root currently).
Making the root pool available somehow would also keep me happy.!
|
http://mail-archives.apache.org/mod_mbox/httpd-dev/199809.mbox/%3C35FD2CD6.70978213@algroup.co.uk%3E
|
CC-MAIN-2016-07
|
refinedweb
| 231
| 65.86
|
#include <mpi.h> int MPI_Type_ub(MPI_Datatype datatype, MPI_Aint *displacement)
INCLUDE 'mpif.h' MPI_TYPE_UB(DATATYPE, DISPLACEMENT, IERROR) INTEGER DATATYPE, DISPLACEMENT, IERROR
This deprecated routine is not available in C++.
MPI_Type_ub returns the lower bound of a data type.
The "pseudo-datatypes," MPI_LB and MPI_UB, can be used, respectively, to mark the upper bound (or the lower(0), disp(0)), ..., (type(n-1), disp(n-1))}then the lower bound of Typemap is defined to be
(min(j) disp(j) if no entry has lb(Typemap) = ( basic type lb (min(j) {disp(j) such that type(j) = lb} otherwiseSimilarly, the upper bound of Typemap is defined to be
(max(j) disp(j) + sizeof(type(j) = lb}
|
http://www.makelinux.net/man/3/M/MPI_Type_ub
|
CC-MAIN-2014-10
|
refinedweb
| 114
| 52.8
|
Intel Claims Smallest, Fastest Transistor 116
The Angry Clam writes: "Supposedly, Intel has really micronized transistors." Seems that "Intel engineers have designed and manufactured a handful of transistors that are only 20 nanometers, or 0.02 microns, in size." There's some of the usual discussion of how long Moore's Law can hold, but also a bit of discussion about what will replace silicon dioxide in a few years. Reader omnirealm points to a similar story at the New York Times as well.
Re:Californians look at too much porn (Score:1)
I won't do much good on a dial-in ip, at first thought. But addressing 'matters' like these to isp's surely worked before and I wouldn't know why it wouldn't work now.
It would be a relief to finally see some action against this and lots of other abuse of slashdot. A joke is a joke, but you can actually go too far.
Re:If only the Earth's temp were lower.... (Score:1)
What is apparently necessary is a different design for a transistor (or a gate). It turn out to be as revolutionary as the shift from vacuum tube to semiconductor transistor. It may be an application of modern techniques to an old and forgotten idea. Or perhaps Moore's Law will quietly ebb out...
What I'm personally rooting for is a change in the idea of computing. If people can build reasonably large quantum computers, maybe they can figure out something besides factoring large numbers that they are actually good at computing. FPGAs also sound both neat and promising.
Realistically, even if this is the last generation of transistor shrinkage, it'll still take years for this to hit the desktop. That is quite a long time for people to come out with ingenious new schemes. Well... cross your fingers, anyway.
Re:Another Limit: Planck Time (Score:1)
Re:Another Limit: Planck Time (Score:2)
Maybe in 100 years, computers will be smart enough to realize that 1.1+1.1+1.1+...+1.1 can be computed as 1.1*ULONG_MAX.
Re:Another Limit: Planck Time (Score:2)
> enough to realize that 1.1+1.1+1.1+...+1.1
> can be computed as 1.1*ULONG_MAX.
\begin{pedant}
Unlikely, given that the value obtained by successive additions and the value obtained by multiplication differ substantially in the 11th decimal place. IEEE floating point numbers are not the same as the real line.
\end{pedant}
Re:No kidding (Score:2)
Which Handful is that ? 5 ( as in the fingers on a hand) or enogh to fill a palm. For something this small you are talking several million.
Re:Moore's law-type performace increases can conti (Score:1)
Less power (Score:1)
After what I've been reading here lately, power-consuming seems to be just what California needs
;)
Re:Moore's Law II (Score:2)
Face it. We're bloated right now. If processors never got any faster ever, we'd still be bloated.
Re:The Change (Score:2)
Re:The Change (Score:2)
2^2 = 4
4^2 = 16
16^2 = 256
.. and so on.
Re:Obligatory AI quote (Score:2)
Right on the mark. We'll hate it anyway (anybody want a dancing paperclip? "The new Pentium V chip will be fast enough for the a line-dancing and juggling paperclip." It's still a lousy annoying paperclip.
AI requires more than just fast transistors and 3D graphics.
And all stock people should remember why the big crash happened back in the 80s: Yes: Computer trading and all these automatic trading programs suddenly shouting 'sell sell' in chorus. Let's all not learn from the past and do that again, that was fun (irony).
Handful (Score:1)
Re:Another Limit: Planck Time (Score:1)
[Saint Stephen]
Re:Another Limit: Planck Time (Score:1)
[Saint Stephen]
Re:Other limits will stop you before Plank time (Score:1)
[Saint Stephen]
Re:Another Limit: Planck Time (Score:2)
Let's get from here to there.
First, why do we have to be stuck with stupid binary after all these years? Surely we can make the "wires" sensitive enough to recognize more than two electrical states. Lots more computing power in the same "physical space."
Back at the turn of the century Goethe showed that non-trivial systems are not automatic, which ultimately is why we futz around with non-perfectly optimizing compilers that can't recognize that this problem is a single multiplication. A colleague was telling me about NP-completness, and how with the lambda calculus (don't know much about it) we can verify completeness of a system (but what about consistency)? In other words, you can generate every possible truth, but you can't prove it doesn't generate falsehoods. Sounds like the problem you'd have with quantum computing: you'd still have to be able to recognize the "correct" result from all possible correct and incorrect results in the answer set.
Flame on!
[Saint Stephen]
Another Limit: Planck Time (Score:4)
I wrote a C++ program which initializes a double to 1.1; then adds 1.1 to it 4 billion times (ULONG_MAX).
On my PIII 500 mhz laptop (circa 1998-99) sometime, this program runs in 30 seconds.
On my new P4 1.7 ghz, it runs in 12 seconds.
I didn't check, but I think Plank time is about 10-47 seconds. Assuming the time it takes to execute one of these 4 billion steps, and if it continues to cut in half every three years, we'll hit planck time in about 100 years.
In other words, there is a fundamental limit on how quickly we can know one single fact (planck time), and our children will hit that by the end of their lifetimes.
What then?
[Saint Stephen]
CPU Power can allow a semi-AI (Score:1)
I would think that given enough horsepower, we should be able to brute force compute all the possible solutions for a problem. Add to that a little statistical math and you might possibly be able to build a minimal AI that could help with some decisions.
So I guess what we need is a massive online peer-to-peer statistical repository. That way, one system could "learn" from others.
/me heads to bed.
--
Adam Sherman
Re:The Change (Score:1)
--
Re:The Change (Score:2)
By "people" do you mean "blind people feeling things with their feet"?
A centimeter is 0.4 inches. I don't know about most people, but I can sure see things smaller than that.
--
Re:Another Limit: Planck Time (Score:2)
--
hey! (Score:1)
Re:Moore's law-type performace increases can conti (Score:1)
Re:Another Limit: Planck Time (Score:1)
Re:Moore's law-type performace increases can conti (Score:1)
Re:Microsoft + Intel conspiracy (Score:2)
You see, it's not just MS that spews bloatware. Its simply that while in the UNIX market, different organizations spew bloatware, while in Windows-land, all bloatware spewing is efficiently consolidated into one company.
Re:Uses in DNA super computers? (Score:2)
Re:this is just a middle step. (Score:2)
Re:Problems with 20 GHz processors (Score:3)
Re:Another Limit: Planck Time (Score:1)
if (i == 0)
Re:Another Limit: Planck Time (Score:1)
> C++ is not a very efficient language
Well, this little program:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
const double a = 1.1;
int main()
{
double d = a;
unsigned long i;
for (i = 0; i < ULONG_MAX; i++)
{
d += a;
}
printf("%lf\n", d);
return 0;
}
Compiled into this:
.file "repadd.c"
.version "01.01"
gcc2_compiled.:
.globl a
.section
.align 8
.type a,@object
.size a,8
a:
.long 0x9999999a,0x3ff19999
.LC1:
.string "%lf\n"
.align 8
.LC0:
.long 0x9999999a,0x3ff19999
.align 8
.LC16:
.long 0x99999999,0x40319999
.text
.align 16
.globl main
.type main,@function
main:
pushl %ebp
movl %esp, %ebp
pushl %eax
fldl
fldl
pushl %eax
movl $15, %eax
.p2align 4,,7
.L36:
fadd %st(1), %st
addl $30, %eax
cmpl $-2, %eax
jbe
fstp %st(1)
subl $12, %esp
fstpl (%esp)
pushl $.LC1
call printf
xorl %eax, %eax
movl %ebp, %esp
popl %ebp
ret
.Lfe1:
.size main,.Lfe1-main
.ident "GCC: (GNU) 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)"
Do you think you can make it much faster using hand-crafted assembly code? Admittedly, I used C instead of C++, but that doesn't make any difference for anything as small as this.
Re:Obligatory AI quote (Score:1)
In my opinion there is very little physical that cannot be emulated with computers, given enough processing speed and memory.
The End of Work? (Score:5)
``You log on in the morning and (the computer) gives you two or three options: 'Have you thought about doing one of these things? I've done the calculations for you,''' Marcyk said.
If the computer is so smart, why not just tell it to initiate whatever stock transactions it thinks is best? Come to think of it, if computers are that smart, you'll be out of a job and you won't have any money to invest in stocks unless you inherited an estate or had some money stashed away from the time when you were working.
When that happens, we'll need a new law to replace Moore's law: the number of unemployed people will double every seven days. Andy Grove will be heard saying "Where is the limit? Show me the limit, goddamnit!" while an angry and hungry mob tries to force its way into the lobby of Intel's headquarters, brandishing pitchforks and God knows what else.
Moore's Law, Ammendments (Score:1)
Ammendment I: Bus speed shall pretty much stay dormant, until some asshole decides to get off his ass and do something about it.
Ammendment II: Tape as a hard storage solution will stick around like Herpes. Sure some gerks at Livermoore will screw around with rubies and diamonds, but the reality is one upgrade of the 8-track after another.
Ammendment III: A hard drive's fragility will double every 18-24 months. Shit, the instructions on the last hard drive I got said, "Do not breathe in room with hard drive before installation."
Ammendment IV: The average number of patches required between releases of software shall double every 18-24 months.
Ammendment V: The number of hours it takes you to turn of the stupid marketeering features of the new windows Office release, like auto-capitalizer, will double every 18-24 months.
Ammendment VI: (added by Microsoft recently) The ammount of money you pay us for software you have to buy will now double every 18-24 months.
Ammendment VII: The number of months before Mozilla 1.0 is released doubles every 18-24 months.
Ammendment VIII: The number of people who use emacs and the number of people who use vi hasn't changed since 1992 and may become one of the constants of physics (like the speed of light).
Ammendment IX: The editorial skills of the
Ammendment X: The number of stupid patents issued shall double every 18-24 months.
Ammendment XI: The number of RAID variations shall double every 18-24 months and the number of different labels for the same variation shall also double every 18-24 months.
Ammendment XII: The chances of a
"The Intern-what?" - Vince Cerf
Re:Another Limit: Planck Time (Score:3)
But, all of this is irrelevant, because there is no limit on how quickly we can know a single fact, because we can determine a theoretical infinite number of facts from a single query with quantum computing.
Re:The Change (Score:1)
So, really, that should be most people can't make out much detail smaller than 1/10th of a centimeter and the transistors we're talking about are 50,000 times smaller...
Re:The Change (Score:1)
I both showed that I didn't have a grasp of the metric system AND that I didn't understand that the poster was talking about not being able to see the whole CPU, not just the transistor (which you've not been able to see for years).
I guess I'm being moderated up for my unsupported suppositions later in the post, but that's not really any different than the post I was responding to. He just had different unsupported suppositions...
I wish I had mod points so I could set my own post to "Overrated". Oh, but you can't mod your own posts, can you? That should be changed. Everyone should be allowed to apply Overrated to their own posts...
Re:The Change (Score:5)
We're talking about 0.02 microns here. Most people can't make out any detail smaller than a centimeter. 0.02 microns would be 500,000 times smaller than what can be seen with the unaided eye!
I really don't understand your reasoning. Are you saying that we are motivated to improve our technology all the time? What does this have to do with Moore's Law and specific predictions about how fast our technology improves?
If anything, I think that Moore's Law might be a self-fulfilling prophecy.
We just don't have that great a motivation to improve processor technology these days. We have processor technology that is beyond the dreams of engineers 30 years ago. For the most part, we have reached a point where most of the needs of applications of massively powerful computing are currently realized in today's machines.
Sure, faster is better, but does faster translate to big development dollars to outdo Moore's Law when researchers and developers are constantly trying to develop software and systems to keep up with the huge gains that were seeing with Moore's Law? In this scenario, Moore's Law is how fast machines improve because Moore said as much and that's what drives the designers to improve, keeping up with and staying ahead of Moore's Law. The designers don't want to be in the group that finally failed to live up to the expectations of the industry, but there's also no particular motivation to get ahead of Moore's Law's predictions either.
Take the above with a grain of salt. It's just conjecture, of course.
Other limits will stop you before Plank time (Score:2)
Disclaimer: While I have a Ph.D. in plasma physics and did a large amount of scientific computing in my thesis, this is not an area on which I am an expert. However I do know that a number of high quality physicists have given this a fair amount of thought (like Feynmann and Wheeler for instance) and have read some of their work.
The big limit is thermodynamic. The minimum energy it takes to flip a bit is of order k_b T_a where k_b is Boltzmann's constant and T_a is the ambient temperature (I think Wheeler was the first to show this limit through clever gedanken experiments but I could be wrong). The ambient temperature of the universe as measured to high precision by the cosmic microwave background black body radiation spectrum is T_a ~ 2.8 K (that is ~ -270 C or ~ -460 F for the unit challenged but remember Celsius and Fahrenheit are not referenced from absolute zero for the following formula).
So, suppose your calculation needs to flip N bits and you want to do it in time tau. Then the thermodynamic minimum theoretical power requirements for your computer are of order:
P ~ N k_b T_a / tau
So you want to do a complex calculation in on a Plank time scale length? I hope you have the power output of a supernova available. Of course, this is the minimum. You have to account all the inefficiences in generation, cooling
Also, for reference, the Plank length and Plank time are the measurement scales made by constructing quantities of the appropriate unit out of Plank's constant h, the speed of light c and the gravitational coupling constant G. Crudely speaking, it is the length scale at which conjectured quantum gravity effects dominate. Planck length considerations aren't really factored into theoretical limits of computation as other more obvious limits are reached first (like the above limit).
A more practical issue is whether or not computer miniturization can continue below the rapidly approaching atomic length scale (~1 A). For example, could you make logic gates based on complex inter-nuclear interactions or based out of non-linear vacuum dielectric polarization of hard gamma rays (i.e. compton backscattering off virtual electron-positron pairs) or other such known exotica of modern physics?
Kevin
Re:If only the Earth's temp were lower.... (Score:2)
___________________________________________
I'm somewhat ignorant of chemistry, but HO2 is neither water, nor possible with proton/electron bonding, since hydrogen has a +1 charge, and oxygen -2.
--
Re:Recent slashdot story.. (Score:2)
Re:Silicon dioxide replacements (Score:2)
Exactly. And by the time we're finished with this obsession of ours with faster computing(since physics will stop us at some point), we'll start seeing better computing [mit.edu]. I think we'll start to see more special purpose cpu's and hardware for pervasive computing and the focus will be become less on innovation and the next greatest thing(since we all tire of it some time) and more towards integration. Computing will be truly pervasive and really will make things easier this time(read: paper office).
-----
"Goose... Geese... Moose... MOOSE!?!?!"
How? (Score:1)
Re:Another Limit: Planck Time (Score:1)
All Your Base Are Belong To Us!!!
Re:Another Limit: Planck Time (Score:1)
All Your Base Are Belong To Us!!!
Handfull to transistors? (Score:1)
A HANDFUL of .02 micron transistors?? (Score:1)
Hell.. A handful of transistors that small would be enough to produce several thousand or so processors... Get busy!!! Chop Chop!!
Re:The Change (Score:1)
That makes reading this comment very difficult indeed.
Re:Another Limit: Planck Time (Score:1)
I think the problems facing engineers in the future will be finding ways of increasing parellism within hardware, and of course developing software to take advantage of those features.
Re:Another Limit: Planck Time (Score:1)
Re:The Change (Score:2)
How small a detail you can make out depends pretty critically on how close you are to the detail in question. A human hair is only hundred microns (i.e. a few hundredths of a centimeter) wide, but people have no making out individual hairs at close range. I routinely work with tubing that's 140 microns in outer diameter, and I personally have no trouble seeing it- though it gives some of my co-workers fits. 60 micron diameter optical fiber is a bit tougher to see, but still doesn't require a microscope.
There are some limits, though. The shortest wavelength that the eye can see is about 0.35 microns, and the laws of optics say that you can't make out details much smaller than one wavelength. Light will just diffract around anything much smaller, so it's physically impossible to see something 0.02 microns across, even with a theoretically perfect visible light microscope. That's the exact reason that these kinds of features have been so difficult to make; the same rule that limits the resolving power of a perfect visible light microscope also limits the size of feature you can make with visible light lithography. To make something 0.02 microns across they have to use very short wavelength EM radiation.
Re:If only the Earth's temp were lower.... (Score:2)
Dude, hydrogen dioxide isn't water. Water is H2O (dihydrogen monoxide). Hate to rain on your parade, just thought I should point it out.
enough already! (Score:1)
Every few months were hear about how things are smaller, faster, better, more. Too bad it'll be 10 or 20 years before this stuff filters down to the consumer level.
Re:The Change (Score:1)
Ha ha ha ! And this is fucking "insightful"??
Please.
1cm is 1/2.54 of a fucking inch.
Most people can easily see a fraction of 1mm which is 0.1 cm.
With a naked eye, yes.
Re:The Change (Score:1)
>technology these days. We have processor technology that is beyond the
>dreams of engineers 30 years ago. For the most part, we have reached a
>point where most of the needs of applications of massively powerful
>computing are currently realized in today's machines.
Ha! Just wait till Quake 4 hits the shelves, we'll see what you'll be saying then!
Seriously, current computing power is FAR below what is needed for realistic simulation of reality. When you look at CGI in the movies nowadays, and you've got a good eye, you'll see it still 'feels' artificial, though they used multi-computer render-farms for them, and computations took months. And that's only flat 2D projection of a 3D scene, in a resolution (about 8000X8000 pixels) that's much less than what single human eye can achieve, and sound is still digitized from natural sources, and they don't do all the simultaion of physics - much of that is pre-directed, 'hand'-animated, and all the logic of the scene is a human's work (computers didn't process the 'what if a ship hits an iceberg' rules when they were making Titanic!)
No, today's machines are far from realizing the need for computing power. Not only in VR uses. What about scientific processing of data? Would SETI exist if we didn't need much more processing power than we have now? What about intuitive user interfaces? I saw Nautilus from my new Mandrake 8.0 _crawl_ on my PIII 550, 256 Mb RAM just yesterday.
Re:Another Limit: Planck Time (Score:1)
So the limit you mentioned will be hit sooner if the current trend continues, but it's questionable if it'll really matter.
The Change (Score:5)
Example: a floppy disk's size can be pushed to the limit, and finally we have 1.4MB floppies.. but sooner or later, you need a CD. And then a DVD. Et cetera.
It'll still be quite a while, but eventually silicon will simply be the wrong technology, the wrong process. Of course, a processor technology lasts MUCH longer than a subcomponent, such as a floppy drive technology.
Moore's Law. Too bad it's "only" x2 and not ^2.
Re:The Change (Score:1)
The slashdot 2 minute between postings limit:
/.'ers since Spring 2001.
Pissing off hyper caffeineated
Re:The Change (Score:1)
The slashdot 2 minute between postings limit:
/.'ers since Spring 2001.
Pissing off hyper caffeineated
Re:The End of Work? (Score:2)
The slashdot 2 minute between postings limit:
/.'ers since Spring 2001.
Pissing off hyper caffeineated
Re:Recent slashdot story.. (Score:1)
heh...dont drop the 'bit' bucket in that lab... (Score:1)
-- "nobody move! I just droped 5 pounds of
That would be way worse than loosing a contact in the snow...
I wonder thou, how many of these little guys would it take to amount to 5 pounds?
NO SPORK
future speeds (Score:2)
I keep thinking about the problems with military gear where they have to worry about cosmic rays knocking out circuits. I don't know how usable these things will be in high radiation areas unless there is substantial redundancy built in.
And to speculate on what we'll run on this puppies. or the cooling systems.
Oh My!
Problems with 20 GHz processors (Score:3)
I'm sorry, but won't creating processors with such high clock frequencies just be negated by the inherent slowness of the bus? One of the things you have to remember when designing hardware with such short clock cycles are the inherent speed limits on signals propagating through it. Light can only travel 1.5 cm in the time afforded by a single cycle from a clock running at 20 GHz. Electrons are much slower. The implication of this are that, given current motherboards, the CPU will stall for a hell of a lot more cycles waiting for a memory read/write.
Caching can only go so far. It seems to me that increases in overall computing power (however you wish to measure it) will not come just through cranking up the clock speed, but will require fundamental architectural changes to the PC as we know it (main storage on the CPU, overall miniaturization, etc).
Silicon dioxide replacements (Score:3)
Of course, new designs and materials will come (Toshiba is starting to use diagonal circuitry, helping efficiency). Silicon is just too cheap and abundant to give up on right now - we'll probably see it for a few decades into the future in things like appliances, calculators, and handheld computers because they're cheap to manufacture in mass quantities and the material itself is one of the most abundant substances on the surfaces of the planet (it's a large component of common sand).
Therefore, I think the prediction of silicon dioxide fading away in just a "few years" is a bit premature. If we've learned anything from the tech industry, old standards tend to stick around for a VERY long time (witness floppy drives, ISA slots, and serial ports).
Re:future speeds (Score:1)
Moore's Law II (Score:5)
What would happen if computing hardware technology reached hard atomic limits?
A new era would begin...programmers would actually have to write efficient code! The end of bloatware as we know it!
Moore's Law II: On average, every 15 months, code would suck 50% less...
Re:Moore's Law II (Score:1)
Re:Caveat (Score:1)
-Jeff
Re:No kidding (Score:1)
Gallium Arsenide is used to make high efficiency solar cells.
-Jeff
Re:No kidding (Score:1)
-Jeff
Re:Silicon Dioxide is just an INSULATOR (Score:1)
P=(1/2)*f*C*V^2
Lower capacitance == lower power
Lower frequency == lower power (we don't want that though)
Lower voltage on the transistor == much lower power.
Why did we go from 5V CMOS technology to 3.3V? Why did we go from 3.3V to 1.6V technology?
I think we should not disregard the voltage that we can run these circuits.
-Jeff
Swinzig's Law (Score:3)
Re:Recent slashdot story.. (Score:1)
Re:Problems with 20 GHz processors (Score:1)
C//
Caveat (Score:1)
only 20 nanometers, or 0.02 microns, in size
Note: When IBM gets done stretching them, they go up to 40nm.
How small is SMALL? (Score:1)
Silicon Dioxide is just an INSULATOR (Score:3)
Some of the silicon dioxide has already been replaced for a couple years with materials called "low-k dielectrics" which basically means it results in lower capacitance (lower capacitance == faster chip) than silicon dioxide. This is only on the metal layers which are relatively far from the transistors. The silicon dioxide mentioned in the article is the insulator used in the actual transistor itself. It is the one that is going to be "atoms thick" and it is one of the fundamental parts of the transistor.
passing fad (Score:1)
If it doesn't make my 100 watt tube head [marshallamps.com] go to 11, what good is it?
Whatcha doooo with those rollin' papers?
Make doooooobieees?
Re:Another Limit: Planck Time (Score:1)
Re:Another Limit: Planck Time (Score:1)
Re:Moore's law-type performace increases can conti (Score:1)
Re:future speeds (Score:1)
They take two separate approaches. DIVA puts a second, small cpu on the core which checks all work performed by the primary cpu. The multithreading paper executes two redundant copies of a program, checking that the results generated between the two agree (on the same processor, using simultaneous multithreading).
Re:Moore's law-type performace increases can conti (Score:1)
As far as FP vs INT... well... I don't know... I mean, if all you care about is FP, then your work is 99% likely to be easily parallizable. Thus, just buy 10 1 gig athlons and be happy... but whatever
:)
Re:Moore's Law II (Score:1)
Re:The Change (Score:1)
Most people can't make out any detail smaller than a centimeter
Haha! Heehee. Sorry. Do you know what a centimeter is? My index fingernail is about a centimeter wide. On my monitor, the word DUCK is about a centimeter wide. I am 186 centimeters tall. The civilized world (read: not afraid to make changes to improve efficiency) uses the metric system now, so I suggest you learn it
:)
Then again, I still tell everyone that I'm 6'1" and a bit..
Recent slashdot story.. (Score:3)
Re:Moore's law-type performace increases can conti (Score:1)
Obligatory AI quote (Score:5)
Just once, I'd like to read an article about a new microprocessor technology that doesn't have some silly quote about what kind of AI feature it will enable.
For decades, hardware has been proving exponentially. For decades, they've been predictiong that the new features will magically enable intelligent software.
All we've got to show for it so far is Clippy the paper clip. A mere 10X speedup won't make Clippy any less annoying.
Hint for futuristic article editors: the human brain has a hardware and software architecture that has absolutely nothing in common with that of an electronic computer.
Re:Obligatory AI quote (Score:2)
I don't know, anything that helps me dismiss the damn thing a couple milliseconds faster is forward progress as far as I'm concerned...
just computers buying and selling (Score:1)
Surely not us consumers and workers. Even now traditional 8 hour workdays are routinely exceeded, using coffeine, pills and stimulating experiences and working conditions to keep workers healthy. Good health is defined by new standards every year so that most productive units would look most healthy. "Healthy people smile a lot, their days are filled with varying tasks and refreshing experiences." and so on..
Squinting to post this (Score:1)
Re:Moore's law-type performace increases can conti (Score:1)
And remember, two cpus running in parellel enjor a greater performance boost (on some tasks) then a single processor with twice the speed of either of the dual processors.
I think you have it backwards. two cpus almost never run at twice the speed of one. Usually, it's good for an extra 50-70 percent speed.
Re:Moore's law-type performace increases can conti (Score:1)
Name one.
System performance is going to be lower on the dual proc version just from multiproc overhead.
Like I've Always Said (Score:1)
And as the growing bloat^H^H^H^H^Hsoftware industry has proven
It won't do nayone any good if you don't know what to do with it.
No matter how fast they make chips... (Score:2)
Uses in DNA super computers? (Score:2)
Why use crappy phosphate-deoxyribose alt-copolyester? Peptide nucleic acids are vastly more robust and give you optional chiral centers for more goodies, like non-linear optical devices.
Hell, make a PNA 17-25 mer cocktail complimentary to a few critical HIV gene sequences and cure that, too, by knockout strategy (the Flavr-Savr HIV therapy). PNAs are uncharged and readily permeate cell membranes, they are totally untouched by nucleases and other catabolisms, and they are cheap to make. Turn off HIV RNA, turn off disease process progression. Boom. None of this downstream small molecule enzyme inhibitor bullshit that makes so much money for the pharm workers.
Original proposal is an interesting problem, and rather a small proportion of the population is up to it. When I started out in the business some 30 years ago, the process of discovery and original proposal awed me. It still does, and my track record has been exemplary. Perhaps the best answer is that you must read everything and be prepared for things to bump around in your head.
Example: My first original research proposal was to synthesize an obscure polycyclic alkaloid (in 32 steps! Silly synthesis is the refuge of a scoundrel) An ocean of blood flowed, and all of it was mine save for one redeeming skeletal inversion which was deemed "adequate." The next year, for my second original proposal, I proposed synthesizing C2 in cryogenic matrix and gas phase. C2 is hot stuff (literally) in flames and comet tails (Schwan lines), and its electronic structure was uncomputable at the time. When you warm the matrix fragments recombine to give acetylene diethers - which had not been synthesized at that time. The diethers dimerize to a squaric acid precursor, which was hot stuff re squarylium dyes for photoconductors. The tar from the reaction was worth at least ten times the cost of starting materials.
Know everything, and see where stuff rubs.
Almost any ten-carbon lump turns into adamantane in aluminum chloride/bromide slush. We can do better (though not cheaper) in ionic solvents like N-methl-N-(n-butyl)imidazolium tetrachloroaluminate with up to another added mole of AlCl3. The media support multiple carbocationic rearrangeents as a benign environment. What happens if you put micronized graphite into the slush and bubble in isobuytlene? Will you edge alkylate and solublize, or make 1-D tert-butylated diamond plates, or will something else happen? Look at all the applications of graphite fluoride and graphite intercalcates, as in high energy density battery systems and high number density low bulk mass hydrogen storage modalities.
Sargeson trapped Co(en)3(3+) as the inspired sepulchrate (formaldehyde plus ammonia), and then the brilliant sarcophogate (formaldehyde plus nitromethane; look down the triangular face of the coordination octahedron). Stop being an inorganiker and start being an organiker. That last gives you "para" nitro groups, which give you amines, which give you redox nylon (and azo linkages; polyisocyanates, polyurethanes, epoxies, acrylamides, and...) Nitrogen chemistry is incredibly rich - conjugated azo linkages, fluorescent heterocycles, stable free radicals, extrusion and caged radical recombination... As Co(en)3(3+) is trivially optically resolved, you also have potential non-linear optical films switchable through redox change. (Information storage, chemical transistors, sensors, clinical diagnostics, electrochromic windows...) It goes on and on... a whole lifetime of research. Nobody has diddled with it.
Look up the synthesis and reactions of of hydroxlyamine-O-sulfonic acid in Volume 1 (!) of Fieser and Fieser. Look at the mysteries of ammonia - inversion, nucleophilicity. Look at the Alpha Effect re hydrazine, hydroxylamine, and hydrogen peroxide. Look at Bredt's rule and all the interesting things it does at bridgeheads. Now, make it all rub against itself: Start with 1,4,7-triazacyclononane, which is easy enough though sloppy to make in bulk. Gently nitrosate it. The nitroso group goes on the first amine, then the adjacent amine (pre-organized to attack re Cram) attacks at the nitroso nitrogen to give you the hydroxylamine. Do the usual hydroxylamine-O-sulfonic acid synthesis and you tether the original nitroso nitrogen to the third amine with the original nitroso's oxygen as the leaving group. What have you got? You have four bridgehead nitrogens rigidly held, none of which can invert. The apical nitrogen is tethered only to other aliphatic nitrogens - which has never been done. It cannot invert and... for all that, it may have no nucleophilicity whatsoever because the Alpha Effect is euchered out by geometry and inductive electron withdrawal is mammoth. You could do it in undergrad lab.
I once watched a bunch of engineers with a very big budget try to excimer laser drill parallel or serial hundreds of 5 micron holes in PMMA intrastromal corneal implants (without the holes to move oxygen from outside and nutrients from inside the cornea dies and sloughs, which is tough on the rabbits). Buncha maroons. 5 microns is a magic number to an organiker, and I won't insult your intelligence with the trivial solution. The next Tuesday I delivered a foot-long bar of oriented two-phase PMMA which was cut and polished to spec, had its holes revealed, and got me into incredible hot water since my employer did not give shit one about the product but was really interested in the long term money budgeted by its parent company.
Take two cyclopentane rings (Framework Molecular Models do this nicely). Put 5 all-cis (vs the ring not olefin configuration, which need only be consistent) alkenes on one cylcopentane. Cap with the other. Now, twist slightly and watch the pi-oribtals. Is that a clever way to make dodecahedrane, or what? The alkenes came from alkynes. The alkynes were assembled with Schrock alkyne metathesis catalyst from the nitriles. Strain being what it is, you might want to have diacetylene linkages (copper-mediated oxidative coupling) and go for a bigger hydrocarbon bubble. Start with all-cis 1,3,5-cyclohexane and trace the diacetylene evolution (no strain here!) Consider 1,3,5-trans-2,4,6 all cis-substituted cyclohexane). Voila! You grow 1-D diamond (note the ring conformation and the special name given to that diamond structural variant).
I could go on for megabytes. All you need do is read the library, hold it all in your head, and wonder "what if..." where stuff rubs together. This is the first (easy) kind of genius. The second (hard) kind of genius is to see it all ab initio. I don't have a handle on that one.
Moore's law-type performace increases can continue (Score:2)
this is just a middle step. (Score:2)
|
https://slashdot.org/story/01/06/10/0230211/intel-claims-smallest-fastest-transistor
|
CC-MAIN-2017-39
|
refinedweb
| 6,317
| 63.8
|
As part of my ongoing career quest to become full-stack, there's several tasks I must complete, such as:
- Storm the castle
- Slay the dragon
- Save the princess
- Learn Ruby on Rails
Thankfully I can go in any order, so I started with Rails!
After finishing the always helpful Ruby on Rails Tutorial, I looked to learn topics it didn't cover. I'd actually touched on one before in my job - the Presenter pattern! Creating and designing my first presenter was a surprising challenge, so I wanted to share my process here for others. Sadly the tutorial on saving the princess will have to wait.
I assume anyone reading this has at least a basic knowledge of Rails tools and functionality, so I'll skip recapping controllers, routes, and all that. If all that's unfamiliar to you, I recommend going through the Rails tutorial first!
What is a Presenter?
A Presenter is an extra layer between a controller and view that better organizes the data being used. Chances are the raw data from your app's database won't just be used as-is:
- Some numbers may need corresponding string or hash values
- Large groups of data may need reorganization or recalculation
- All the above may depend on other info or require extra arguments
Without a presenter, there's two other ways to address this issue that aren't as good.
- Do it all in controllers, but that's not what controllers are for. They control the data, layout, and other actions for rendering the page. Making the data fit for the view falls is another matter, and makes controllers bulky and hard to maintain.
- Do it all with helpers, but similar issues arise. Helpers will get overly-long and complex, and become harder to organize among other helpers with more general-purpose tasks (otherwise called "helper hell").
The common, and most important, issue with both these answers is it mixes too many responsibilities together. A presenter fills the role of restructuring data into what the page needs. That's an important, specific task purpose separate from the other two.
This specific presenter was for a Rails project I'm making for managing a budget. It lets users keep track of expenses (what they spend on) and incomes (what they earn money on). There's several different categories for their budget, and a category contains certain types of expenses or incomes. I made this presenter for when users wanted to see important info from a certain category.
With the background set, let's make the actual presenter!
Setting up the Basics
My first obstacle was presenters aren't like controllers, routes, or views - no Rails magic was included. That gives setup a few extra steps.
First is set up a base presenter, for any functionality I want to be shared among them all. Mine just had one function so all presenters could use the application's helpers (with an
h prefix).
class BasePresenter private def h ApplicationController.helpers end end
Now to set up my category presenter to inherit from this one.
class CategoriesPresenter < BasePresenter end
The lack of rails magic also meant I had to explicitly define the category properties for the presenter. I also had to initialize them with other variables it needed - here they were the start and end date, as users would view this info by month.
class CategoriesPresenter < BasePresenter delegate :category, :name, :description, :expense, :expenses, :length, :budget, to: :@category def initialize(category = nil, start_date = nil, end_date = nil) @category = category @start_date = start_date @end_date = end_date end end
With the setup done, I can access to all category info from the database. Now I can start designing data for the view!
Defining Normal Presenter Values
...Unfortunately, the fun parts will have to wait. Just because all the category values are passed in doesn't mean I can use them - they need to be explicitly defined as functions.
This isn't tough, it's just an extra step that's somewhat tedious:
def id @category.id.to_i end def created_at @category.created_at end def budget @category.budget end
Values I want to use as-they-are just need to defined in the presenter like so.
But even simple functions can be made more useful in a presenter. For example, while my data has all the categories' expenses, it doesn't include their total value. I have a helper to calculate this (since it's a common calculation), so I can use that.
def total h.category_total(expenses) end
Plus the data has all the expenses, but I only want to find ones within the start and end date. So I redefine the expenses to get those within that range and reorganize them by value.
def expenses expenses = @category.expenses.select { |expense| expense.created_at.between?(@start_date, @end_date) }.sort_by &:value expenses.reverse end
Another piece to define: despite each category having "expenses," some may actually be set as a source of income. That's why the "expense" value from the database is a boolean, marking it as an expense or income. The presenter translates that boolean to the needed label.
Plus the view often refers to "expenses" or "incomes" in the plural, so that can be defined here too for convenience.
def type if @category.expense "Expense" else "Income" end end def type_p type.pluralize(type) end
Defining more Interesting Presenter Values
With the easier stuff done, let's get to the more complex presenter functions.
The first two define important links for the category: info about the category on that month, and all the categories on that month. These make it easier to link around pages in the time frame. They require certain info from the date objects being interpolated into a url.
def date_link year = @start_date.strftime("%Y") month = @start_date.strftime("%-m") "#{year}/#{month}/#{@category.id}" end def month_link year = @start_date.strftime("%Y") month = @start_date.strftime("%-m") "/categories/#{year}/#{month}/" end
Looking back, since they need the same variables for the setup, I'd put them together and output a hash.
def link year = @start_date.strftime("%Y") month = @start_date.strftime("%-m") { :date => "#{year}/#{month}/#{@category.id}", :month => "/categories/#{year}/#{month}/" } end
If not this, then have the year and month defined elsewhere and referenced in separate functions. I'm still learning so I'm unsure, but in the future I may output fewer hashes for simplicity.
The last function I wrote also outputs a hash for the category's balance, or how far off total expenses or incomes are from what was expected. This is calculated differently for expenses and incomes - it's better for expenses to be below the budget, and for incomes to go above (earning more than expected).
This function returns both the numerical balance, and uses a helper to return a related string if it's positive or negative. I combined these in one function's hash since I judged they were close enough to group together.
def balance if @category.expense total = @category.budget - h.category_total(expenses) else total = h.category_total(expenses) - @category.budget end { :total => total, :state => h.check_state(total) } end
With that, my presenter was complete!
In Conclusion
I plan to keep using presenters as I learn more Rails, due to the important need they fill. They add needed functionality without it leaking into unwanted areas (like my controllers or helpers), and keep my views closer to "plug variables in the right place" templates. Coding this app without them made it descend into the "helper hell" of having too many complex helpers to keep track of. Had I not added a presenter, I may have stopped out of simple frustration or confusion.
Here's hoping Rails makes the presenter pattern an official part of the framework, so they're less of a hassle. Personally, I almost can't imagine using Rails without them.
Discussion (3)
Over my time using Rails I drifted in and out of using presenters. I don't know why though, they do make things a whole bunch easier and let the controller just get on with its job.
Did you consider writing tests for your presenter in this case?
I did briefly, although I haven't been focusing on testing enough as I should be lately. Is it normal practice to write presenter tests? I just assumed each presenter should have its own tests to ensure all the data is calculated and modified correctly.
I would normally write tests for a presenter if I was writing one, exactly as you put it, to ensure that the calculations are correct.
One other thing I was interested in, you used
delegateto delegate methods on your presenter to the underlying
@categorybut also defined the
id,
created_atand
budgetmethods. Was there a reason for that?
|
https://dev.to/maxwell_dev/my-first-ruby-on-rails-presenter-819
|
CC-MAIN-2021-21
|
refinedweb
| 1,455
| 56.55
|
Let's Refactor My Personal Website and Portfolio using Gatsby, Part Two: Generating the Site and Installing Dependencies
Michael Caveney
Updated on
・3 min read
Welcome to part two of my site refactor! If you missed part one, click here to check it out. Today I'm going to generate the site using the Gatsby CLI, create basic page structure, and install dependencies, so let's dive right in!
The Gatsby CLI and Project Structure
Like many other modern frameworks, Gatsby utilizes a CLI (Command Line Interface) to get many common tasks accomplished quickly. Gatsby installation instructions vary slightly by OS, but the (really quite excellent) Gatsby docs have precise instructions on getting your development environment set up. Once the Gatsby CLI is up and running, you can create a new Gatsby project by running the command
gatsby new [projectname][starter]
in the command line. The "projectname" refers to the name that you give the project, and the "starter" is the starter template you use. A list of starter projects exists here, and if no specific starter is mentioned, the CLI uses the default starter. Check out this section of the Gatsby docs for a more detailed discussion of how to initialize a new project.
If we were to navigate to the newly created folder and open it in a text editor, we'd see a file structure much like this:
A .cache folder, a node_modules folder, and a public folder. I'm lumping these three together because you're
generally not going to have to worry about them or edit their contents manually.
A src folder, which contains additional folders for components, images, and pages. You'll be working with
these a fair bit.
A .gitignore file, which lists the files and folders that do not get saved in a repo when working with Git/Github.
A LICENSE file which contains information about the software license in use here.
A package.json and a package-lock.json file, which contain information about project scripts, dependencies, and the
exact versions of those dependencies.
If you've worked with React, Node, or other JavaScript frameworks or paradigms before, much of this will be familiar. But we get something special with the pages folder!
Pages in Gatsby
One of the more "magical" aspects of Gatsby revolves around how pages work. Any React components listed under the "pages" section are added to the routing of the application automatically. You still have to wire up navigation between those pages, but the routes automatically added is a nice touch.
The app initialized with a "page-2" component that I'm not going to need, so I'll delete that and any references to it in the index.js file.
The pages that I'll need are:
A home page/site index.
An About Me page
A page detailing projects and linking to Github, my writing on DEV, etc.
A contact page.
With that, I'll add about.js, work.js, and contact.js files to the pages directory, and add a basic React component to work as a placeholder, something like this:
import React from 'react'; const About = () => { return ( <div>I'm the About Page!</div> ); } export default About;
Plugins in Gatsby
From the Gatsby.js website:
Gatsby plugins are Node.js packages that implement Gatsby APIs. For larger, more complex sites, plugins let you modularize your site customizations into site-specific plugins.
Plugins exist to help Gatsby reduce boilerplate or complicated custom code when reading from or working with various file types or paradigms. Looking at our
gatsby-config file, we already have added to the project:
- gatsby-plugin-react-helmet: Manages the head of the document, including SEO
- gatsby-source-filesystem: Parses files in a specific directory. This plugin is mainly utilized by other plugins.
- gatsby-tranformer-sharp: Creates nodes out of compatible image files for optimization by the Sharp library.
- gatsby-plugin-sharp: Processes images using the Sharp library
For now, I'm only going to add the gatsby-plugin-emotion family of plugins, to facilitate use of that library.
That's all I have for today! Next time on this blog series, I discuss planning for site/app design and design systems!
How to Improve Writing Skills as a Non-Native Speaker
Let me begin by saying, that writing a new post either on technical or soft skill topics is always a challenge for me. Why? Because I am not a native English speaker.
|
https://dev.to/dylanesque/let-s-refactor-my-personal-website-and-portfolio-using-gatsby-part-two-generating-the-site-and-installing-dependencies-29ee
|
CC-MAIN-2019-47
|
refinedweb
| 743
| 63.49
|
Is there any way to force Eevee to display and render video textures?
Yes! You need a script and to keep the image editor open like in 2.7.
Props to zanqdo:
import bpy def clipReload(scene): bpy.data.images['pasteclipnamere.mp4'].reload() print('Clip Reloaded') bpy.app.handlers.frame_change_pre.append(clipReload)
Put ^this^ in the text editor, change the ‘pasteclipnamere’ to the video texture file’s name, and run the script.
Look here for more:
Edit: fixed the code, apparently indents are not respected by default
Thanks.
It works but its a little buggy for me. Some frames renders darker that it should be. Of course it is not a big problem to render a few frames again and replace them.
For macOS users - go to:
and copy script from there. This avoid quotation marks errors.
I have similar issues. In the viewport it works great but the render turns black or dark randomly.
For everyone else trying the script: make sure you have the correct indentation as seen in the original code, when you follow the link.
Black frames seem to reduce a lot if you render single threaded… change back to cycles and change the setting in performance tab, then on eevee again, rendering the same file has less black frames…
Has anyone found a better workaround to check if the image is actually displaying intead of simply reloading?
Just for the record, this has by this time been fixed.
In the Python language, "indentation is everything." The block-structure of this language is determined by indentation, not punctuation such as {…}. No other language that I am aware of is like this.
|
https://blenderartists.org/t/eevee-and-video-textures/1138037
|
CC-MAIN-2020-50
|
refinedweb
| 275
| 74.49
|
Spyder is a Python IDE that is itself written in Python. Plugins are created by putting a python file in spyder’s ‘spyderplugins/’ directory, which you probably can’t do if you’re using the installed version of Spyder: you’ll instead need the Spyder source code. Spyder’s home repository can be found at bitbucket (), but we have cloned this repository with the intent of modifying it slightly to make it better suit the needs of our particular users; that source can be found at:
In both cases, you can run that source-code version of Spyder by running the ‘bootstrap.py’ python script located in the root directory of the checkout. NOTE: this script checks to make sure Spyder is not already running before executing! This means that you must exit your installed version of Spyder first.
If you want to use Spyder to edit Spyder plugins, you’re going to have to launch boostrap.py with the command-line option “–new-instance” to test your changes. Alternatively, you can use a different Python IDE (such as Eclipse), and launch it from there.
All plugins in Spyder must reside in the spyderplugins/ directory, and take the form ‘p_[pluginname].py’. Let’s take a look at the simplest plugin in the tellurium codebase: p_tellurium_reset.py This is the plugin whose sole purpose in life is to remove or hide any elements we deem would be too confusing to our users, and which renames the application. We can’t change the splash screen from a plugin, because the splash screen has already been displayed before any plugins get loaded. But we can do basically anything else we want.
For now, the one thing this plugin does can be found in the ‘register_plugin’ function:
def register_plugin(self): """Register plugin in Spyder's main window""" DEBUG = bool(os.environ.get('SPYDER_DEBUG', '')) title = "Tellurium (from Spyder %s; Python %s.%s)" % (__version__, sys.version_info[0], sys.version_info[1]) if DEBUG: title += " [DEBUG MODE]" self.main.setWindowTitle(title) icon_name = 'Tellurium_light.ico' if self.main.light else 'Tellurium_filled_small.ico' # Resampling SVG icon only on non-Windows platforms (see Issue 1314): self.main.setWindowIcon(get_icon(icon_name, resample=os.name != 'nt')) self.main.add_dockwidget(self)
Here, the Spyder main window is referenced with ‘self.main’, and its functions ‘setWindowTitle’ and ‘setWindowIcon’ are used to re-skin the application to say “Tellurium’ at the top, and to use the Tellurium icon (which can be found in spyderplugins/images/) for the window. The ‘add_docwidget’ line is required for all plugins, as is defining (even as a stub) all of the other functions in this file. (As of this writing (February 2014), the plugin does not actually remove or hide anything else in the application, but may in the future.)
Other plugins are perhaps more instructive from an actually-doing-things perspective. The one I’ve used as a template a couple times is the ‘pylint’ plugin, a plugin that uses pylint to analyze Python code for errors, inefficiencies, and non-standard uses, and report the results. This plugin can be found at spyderplugins/p_pylint.py, and makes use of spyderplugins/widgets/pylintgui.py and spyderplugins/images/pylint.png. I won’t analyze the code here (as there is a lot I have yet to understand), but I found it very helpful when creating my own plugin: I basically started by copying the whole thing, removing things I didn’t need, and modifying the rest.
A test ‘hello world’ plugin based on the pylint module can be found in the current (2/2014) codebase, though obviously it will be removed for any actual release. It creates a window with a button you can click that will append ‘Hello, world!’ a changeable number of times to an editable text window. Its code can be found in spyderplugins/p_hello.py, and it uses spyderplugins/widgets/hellogui.py and spyderplugins/images/hello.png
The basic features of the plugin include:
A different ‘hello world’ plugin for Spyder can be found at. It takes a slightly different tack on what the plugin should do, but the basics are the same.
|
http://tellurium.analogmachine.org/plugins/writing-ide-plugins/
|
CC-MAIN-2017-22
|
refinedweb
| 686
| 55.84
|
if varianbles are declared within a function, do they die when the function finish?
This is a discussion on do variables die in function within the C++ Programming forums, part of the General Programming Boards category; if varianbles are declared within a function, do they die when the function finish?...
if varianbles are declared within a function, do they die when the function finish?
If you allocate memory for them with new, then the memory is still valid after the function ends and doesn't die until you delete it.
The memory space will still be avialable until you delete it, however any local pointers you have in the function will be destroyed when the function ends, so unless you are saving the pointer somehow (return value or static) then that memory space is effectivaly lost.
ok, i see how it works. i was just working with random numbers and i came up with another question. lkook at my code:
i have a function thats supposed to generate random numbers and reutnr them, but everytime i run the program, i get the same result. why isn't this random?i have a function thats supposed to generate random numbers and reutnr them, but everytime i run the program, i get the same result. why isn't this random?Code:#include <iostream> #include <conio.h> using namespace std; int generate_numbers(int low, int high) { time_t seconds; time (&seconds); return (rand() % (high - low + 1) + low); } int main() { int number[10]; int i; for (i = 0; i < 10; i++) number[i] = generate_numbers(1, 100); for (i = 0; i < 10; i++) cout << number[i] << endl; getch(); return 0; }
I have run experiments on an xp machine.
I ran a program with initialization and declaration of a variable inside a function.
Local scope without being declared as static.
I monitored the memory usage per the system log.
The memory was still being used by the system after the exit of the function.
It didn't release the memory back to the system resource pool until after the program itself was dead. I think the adress that keeps track of the memory is dead after the function ends, but the memory itself is still concidered active in the program until the program itself dies. This could all be system dependent though. Windows does some weird things sometimes.
"Hence to fight and conquer in all your battles is not supreme excellence;
supreme excellence consists in breaking the enemy's resistance without fighting."
Art of War Sun Tzu
Ok are you getting different numbers for each call?
The reason you would get the same set of numbers each time you run the program is because you aren't initalizing the random number generator.
Search the board and you'll find about a million posts about it.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
|
http://cboard.cprogramming.com/cplusplus-programming/51852-do-variables-die-function.html
|
CC-MAIN-2015-40
|
refinedweb
| 488
| 62.27
|
3 replies on
1 page.
Most recent reply:
Aug 30, 2006 11:40 AM
by
Jules Jacobs
In You Shouldn't Compare Rails to Java EE 5, or JavaScript/Ruby to the Java Language, Adam Bien suggests that the technique of favoring convention over configuration is most suited to green field designs—brand new designs that have no requirements to fit with legacy code and infrastructure. The technique of "favoring convention over configuration" was recently popularized by Ruby on Rails, but can be employed in any language in any framework. The technique is given credit as one of the main ways Rails helps make programmers more productive at building web applications. Bien states that in the projects he's worked on, often the database already existed, and therefore, "The 'convention over configuration' advantage was gone." In addition, Bien states that "in the last 11 years, I had only few 'green field' projects."
To what extent do you believe that convention over configuration is most helpful for green field designs? How often have you been able to work on a green field design?
def generate_pi(decimals = 10)
# compute pi
end
compute_pi() => 3.14...
compute_pi(2) => 3.1
def compute_pi(decimals = 10)
# compute pi
end
compute_pi() => 3.14...
compute_pi(2) => 3.1
|
http://www.artima.com/forums/flat.jsp?forum=281&thread=174073
|
CC-MAIN-2014-52
|
refinedweb
| 210
| 59.94
|
Using Clojure With SAP Hybris Commerce
Using Clojure With SAP Hybris Commerce
This quick, simple guide will get you set up using Clojure with SAP Hybris Commerce with a custom extensions for the integration.
Join the DZone community and get the full member experience.Join For Free
Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.
I’ve been working as solution architect for SAP Hybris Commerce solutions for quite some time. In this article, I am going to explain how can we use Clojure with SAP Hybris Commerce.
As you know, SAP Hybris Commerce has already supported to create extensions with Scala and Groovy by providing template extensions. If you want to use Scala for SAP Hybris Commerce, you can easily create an extension with the yscala template, and then SAP Hybris Commerce will compile Scala code for you.
So, we will follow the same method to integrate Clojure with SAP Hybris Commerce. We need to create a template extension, let’s call it yclojure, and also another extension to keep Clojure dependencies and also provide some ant tasks and classpath entries to compile Clojure code for use in SAP Hybris Commerce, clojurenature.
Let’s start with the clojurenature extension to provide Clojure dependencies and our ant macro definition to compile a given Clojure namespace with given classpath entries.
Then we will prepare the yclojure extension to provide us the right directory structure, clojurenature extension as dependency, the initial Clojure namespace, and other properties to make sure our template extension works well with SAP Hybris Commerce.
And finally, we can create a new extension with our yclojure template to write some Clojure code. So, I am going to create a new extension called clojurelib and write some very simple Clojure code to use FlexibleSearchService.
Let’s create a new extension useclojure, add the clojurelib extension as dependency, and also write an unit test to make sure our Clojure code working as expected.
Run the test...
It’s all done. Now we have SAP Hybris Commerce platform with a Clojure extension. You can find clojurenature and the yclojure extension on GitHub.
Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/using-clojure-with-sap-hybris-commerce
|
CC-MAIN-2018-17
|
refinedweb
| 403
| 53.61
|
I'd like to do the equivalent of fitting a model of gpm (gallons per mile = 1/mpg) to wt in the mtcars data set. That seems easy:
data(mtcars)
library(dplyr)
library(tidyr)
library(broom)
library(ggplot2)
library(scales)
mtcars2 <-
mtcars %>%
mutate(gpm = 1 / mpg) %>%
group_by(cyl, am)
lm1 <-
mtcars2 %>%
do(fit = lm(gpm ~ wt, data = .))
p1 <-
qplot(wt, gpm, data = mtcars2) +
facet_grid(cyl ~ am) +
stat_smooth(method='lm',se=FALSE, fullrange = TRUE) +
scale_x_continuous(limits = c(0,NA))
lm1 %>% augment(fit)
newdata <-
mtcars2 %>%
mutate(
wt = wt + cyl/4)
pred1 <-
lm1 %>%
augment(
fit,
newdata = newdata)
> sessionInfo()
R version 3.3.1 (2016-06-21)] scales_0.4.0 ggplot2_2.1.0 broom_0.4.1 tidyr_0.6.0 dplyr_0.5.0
loaded via a namespace (and not attached):
[1] Rcpp_0.12.7 magrittr_1.5 mnormt_1.5-4 munsell_0.4.3
[5] colorspace_1.2-6 lattice_0.20-34 R6_2.1.3 stringr_1.1.0
[9] plyr_1.8.4 tools_3.3.1 parallel_3.3.1 grid_3.3.1
[13] nlme_3.1-128 gtable_0.2.0 psych_1.6.9 DBI_0.5-1
[17] lazyeval_0.2.0 assertthat_0.1 tibble_1.2 reshape2_1.4.1
[21] labeling_0.3 stringi_1.1.1 compiler_3.3.1 foreign_0.8-67
newdata %>%
dplyr::select(cyl, am, wt) %>% # wt holds new predictor values
group_by(cyl, am) %>%
nest() %>%
inner_join(regressions, .) %>%
## looks like yours at this point
mutate(pred = list(augment(fit, newdata = data))) %>% # Error here
unnest(pred)
I've used
map2 from package purrr for this sort of situation.
map2 loops through the elements of two lists simultaneously. The lists must be the same length and be in the same order.
The elements of the lists are used as arguments for some function you want to apply (
augment, in your case). Here your two lists would be a list of models and a list of datasets (one list for each
cyl/
am combination).
Using
map2_df returns the results as a data.frame instead of a list.
library(purrr)
I made the list of data.frames to predict with using
split. The order of the factors to split on determined the list order, so I made sure it was in the same order as
lm1.
test_split = split(newdata, list(newdata$am, newdata$cyl) map2_df(lm1$fit, test_split, ~augment(.x, newdata = .y))
To avoid worrying about order so much, you could
nest the prediction data by groups, join this to
lm1, and return the results of
augment as a list for unnesting.
newdata %>% group_by(cyl, am) %>% nest() %>% inner_join(lm1, .) %>% mutate(pred = list(augment(fit, newdata = data))) %>% unnest(pred)
|
https://codedump.io/share/oOQMmu9oEidV/1/how-can-i-apply-grouped-data-to-grouped-models-using-broom-and-dplyr
|
CC-MAIN-2016-44
|
refinedweb
| 422
| 58.69
|
Thank you for fixing it :-)This time it builds alright. I understand IronPython and DLR will continue to be developed with .NET Framework 2.0 as target. I'd like to ask, though, now that the DLR expression tree has moved into System.Linq.Expressions namespace, what would be the preferred solution to resolving conflict between references to System.Core.dll and Microsoft.Scripting.Core.dll? Apparently these two do conflict now, don't they? The other day I was implementing a toy language on the DLR for fun, but the fact that I can't use LINQ queries from within my language impl is...well, not too fun. Greetings,- RednaxelaFX -----Original Message-----> From: Dave Fugate <dfugate at microsoft.com>> Subject: Re: [IronPython] Missing File in IronPython Change Set 34376?> To: Discussion of IronPython <users at lists.ironpython.com>> > Thanks for spotting this!> It looks like there was a bug with the script we use to port changes over from our internal TFS repository to CodePlex's TFS repository.> It should be fixed now.> > Dave -----Original Message-----> From: Seshadri Pillailokam Vijayaraghavan <seshapv at microsoft.com>> Subject: Re: [IronPython] Missing File in IronPython Change Set 34376?> To: Discussion of IronPython <users at lists.ironpython.com>> > Script _________________________________________________________________ Discover the new Windows Vista -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
|
https://mail.python.org/pipermail/ironpython-users/2008-July/007743.html
|
CC-MAIN-2014-15
|
refinedweb
| 219
| 69.79
|
Search found 3 matches
Search found 3 matches • Page 1 of 1
- Mon Jun 20, 2011 4:34 pm
- Forum: Arduino
- Topic: Uno power source/adapter?
- Replies: 6
- Views: 970
Re: Uno power source/adapter?
Take the board to Radioshack or Fry's. They should have some jacks. Just test fit a couple then solder up a cable. I think they also sell wall adapters if you don't have any spare ones. The UNO board is going to need at least 7V to operate. No more then 9V. 7-9V. Make sure it can supply at minimum 5...
- Sun Jun 19, 2011 12:26 am
- Forum: Code Snippets
- Topic: Sorting Variables
- Replies: 4
- Views: 3081
Re: Sorting Variables
qsort(A,sizeof(A),sizeof(int),compare); Where A is the array that holds the variables and compare is this function. int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } More info here. Its in the stdlib of C so yo...
- Sun Jun 19, 2011 12:07 am
- Forum: Code Snippets
- Topic: WS2801 Propeller Driver
- Replies: 0
- Views: 2316
WS2801 Propeller Driver
Here mult...
Search found 3 matches • Page 1 of 1
|
https://forum.sparkfun.com/search.php?author_id=38912&sr=posts
|
CC-MAIN-2019-09
|
refinedweb
| 195
| 83.86
|
China Top Ten Brand DAYANG motorcycle spare parts thailand fo...
US $738-1300
1 Set (Min. Order)
High Sell Motorcycle Spare Parts Thailand For CG125
US $0.6-1
5000 Sets (Min. Order)
Best quality Green motorcycle spare parts thailand of ...
US $3.65-4.5
500 Pieces (Min. Order)
zongshen motorcycle spare parts thailand with super quality a...
US $0.5-2
50 Pieces (Min. Order)
motorcycle spare parts thailand
US $0.1-10
100 Perches (Min. Order)
Goldrunhui RH-B0141 O.E.M Factory Motorcycle Spare Parts ...
US $1-35
10 Pieces (Min. Order)
Auto led working light,720ml 10w cree led light,motorcycle ...
US $1-20
12 Pieces (Min. Order)
motorcycle spare parts thailand/motorcycles alloy spare ...
US $1-10
1 Piece (Min. Order)
Motorcycle Spare Parts Thailand For CG125
US $1.3-1.6
1000 Sets (Min. Order)
top sale motorcycle spare parts thailand
US $0.01-6
1 Piece (Min. Order)
motorcycle spare parts thailand
US $2-3
50 Pieces (Min. Order)
SCL-2012040370 China Wholesale Custom motorcycle spare parts ...
US $0.01-100
200 Sets (Min. Order)
Motorcycle spare parts thailand made of aluminum with anodize...
US $1-99
1 Piece (Min. Order)
Grade A motorcycle spare parts thailand,clutch plate manufact...
US $0.13-0.2
1000 Pieces (Min. Order)
Motorcycle Spare Parts Thailand, Motorcycle Part, Mini Motocy...
US $0.1-10
20 Pieces (Min. Order)
high quality motorcycle spare parts thailand
US $0.45-2.3
1 Piece (Min. Order)
Durable 100% Raw Material Motorcycle Spare Parts Thailand
US $3-6
300 Kilograms (Min. Order)
LF200CC Thailand Motorcycle Parts Two Wheeler Spare Parts Aut...
US $8.2-10.5
20 Sets (Min. Order)
motorcycle spare parts thailand
US $0.35-1.56
1000 Sets (Min. Order)
import motorcycle spare parts thailand manufacturers in china
US $5.40
100 Pieces (Min. Order)
made in china motorcycle spare parts thailand
US $0.01-8
100 Pieces (Min. Order)
High Quality Motorcycle Parts Steering Column,motorcycle ...
US $3.05-10.99
100 Sets (Min. Order)
New Product Motorcycle, Spare Parts, for Cg125, Thailand ...
US $4.2-5
100 Pieces (Min. Order)
motorcycle spare parts brake with thailand motorcycle parts
US $0.5-1.5
1000 Pieces (Min. Order)
Chinese motorcycle spare parts for motorcycle
US $30-50
400 Sets (Min. Order)
Carbon motorcycle racing parts for Ducati 1098 848
US $30-100
2 Pieces (Min. Order)
high quality low price carbon fiber motorcycle spare parts fr...
US $1-3
50 Pieces (Min. Order)
high quality for motorcycle parts C100
US $1-300
10 Pieces (Min. Order)
future motorcycle parts /shell customized
US $0.10-0.15
5000 Pieces (Min. Order)
New design motorcycle parts cbx250 twister with great price
US $1.5-4
500 Sets (Min. Order)
Thailand motorcycle parts
US $0.5-5
2000 Pieces (Min. Order)
thailand motorcycle parts/motorcycle brakes
US $0.6587-0.9875
1000 Sets (Min. Order)
C125cc motorcycle brake shoe 125cc motorcycle spare parts who...
US $0.992-1.132
500 Pieces (Min. Order)
Excellent parts for motorcycle shineray
US $3.00
50 Sets (Min. Order)
Motorcycle Parts
US $4-10
800 Units (Min. Order)
2015 KARUN motorcycle spare parts thailand Angel Devil Eye U7...
US $1-22
|
http://www.alibaba.com/showroom/motorcycle-spare-parts-thailand.html
|
CC-MAIN-2015-48
|
refinedweb
| 539
| 72.83
|
Is there a way to get view.replace() to use regex as it's replace? I have a plugin which will take multiple find and replace strings from a file and carry them out, view.find() will parse a regex string but view.replace() will just replace it literally, not taking into account things like "\1". I guess it doesn't work because the way it works is I'm selecting all the matches of the pattern and then replacing them with the replacement afterwards, even if it did parse regex it wouldn't know what "\1" referred to.
Don't do this kind of text operation with sublime API, just get the text, modify it and then replace the old text. Basically, what you want is viewtopic.php?f=6&t=10610#p42057 and doing stuff to the text with re module inbetween.
Don't see why regex replace shouldn't be supported by the API.
view.replace() is not a "Find and replace" function, it just a replace a given subset of the view by a given string.IMHO, what we need is a way to call the replace Command with our arguments.
I think you can do what you want with:
View.find_all(pattern, <flags>, <format>, <extractions>) [Region]
Returns all (non-overlapping) regions matching the regex pattern. The optional flags parameter may be sublime.LITERAL, sublime.IGNORECASE, or the two ORed together. If a format string is given, then all matches will be formatted with the formatted string and placed into the extractions list.
This method returns the position of your regexp (as View.find), but in addition you can give it a format and an empty list in the extractions argument.After that you only have to loop through the lists and do the job (not tested):
lstpos = view.find_all(pattern, <flags>, <format>, lstrepl)
for pos, repl in zip(lstpos, lstrepl):
view.replace(edit, pos, repl)
Remember, if you have a static list of regions, you should make modifications from the end of the buffer to the beginning, else you smash your offsets
Oups, forget about this.
So something like:
lstpos = view.find_all(pattern, <flags>, <format>, lstrepl)
for pos, repl in reversed(zip(lstpos, lstrepl)):
view.replace(edit, pos, repl)
The find_all API (in ST3) is not finding the results for me that the regex find from the UI pane does.
The goal is to replace a file with many UNCs into local paths. So:\computer7\C$\testdir\test.batshould get replaced into:C:\testdir\test.bat
If I manually do a find-replace with regex in Sublime, it works:Find: \\\S*\([A-Z])\$Replace With: \1:
However, if I try to find the regex string via the API, I get no results:
import sublime, sublime_plugin
class PathUncToLocalCommand(sublime_plugin.TextCommand):
def run(self, edit):
RegionsResult = self.view.find_all("\\\\\S*\\([A-Z])\$", sublime.IGNORECASE)
print(RegionsResult)
# This is the string to find via regex
# \\computer7\C$\testdir\test.bat
RegionsResult is an empty list and does not contain any results when trying to do the regex search via the API. However a match is found when doing the regex search manually from the find pane.
Your code raise an exception in my ST2, not on your side ?
You must use a raw string (r"") for your regexp, or transform it in a correct Python string (double every ):
RegionsResult = self.view.find_all(r"\\\\\S*\\([A-Z])\$", sublime.IGNORECASE)
I do this kind of stuff in my RegReplace plugin. I don't want to go into all the specifics right now, but you can check out the source if you want. You can create reg replace sequence commands with the RegReplace plugin, or you can dig around and see what I did.
ST2: github.com/facelessuser/RegReplaceST3: github.com/facelessuser/RegReplace/tree/ST3
Anyways, maybe this will solve your issue, or help you solve your issue.*)
Above example successfully replaced:\computer7\C$\testdir\test.batinto:C:\testdir\test.bat*
It's not all that bad. You can embed flags in the sublime style regex:
(?s)ones.*Priorities
so .* will match new lines
.*
Pretty sure it uses the the perl variant of the boost regex lib
|
https://forum.sublimetext.com/t/view-replace-regex/8566/6
|
CC-MAIN-2016-18
|
refinedweb
| 696
| 65.73
|
Blog Map
Today, the development team for the Open XML SDK has announced that they have released the first Community Technology Preview (CTP) of version 2 of the Open XML SDK. Download it at. There is a lot of very cool stuff in this release, including:
This is a big step forward. Version 1 of the SDK provided us with strongly typed access to the parts of a package; however, it didn’t provide any facilities for consuming or producing the XML contained in the parts. This version of the SDK really helps a lot with many aspects of modifying and producing the XML parts. Developers who work with Open XML should incorporate the SDK and associated tools into their toolkit.
Development of this SDK has been, and will continue to be an interactive process with the users of the SDK. You can participate! Sign up in the Open XML SDK Connect site, and receive SDK related news and provide feedback directly to the team. You can find the Connect site here.
Strongly Typed Document Object Model
The most important new feature of this version of the SDK is the strongly typed document object model (DOM). I’ve written a whole pile of code using V1 of the SDK using LINQ to XML, and perhaps the biggest single issue that I encounter is remembering the namespaces and names of elements and attributes in the markup. Due to the less strongly typed nature of LINQ to XML, it is far too easy to write code that compiles, but doesn’t run properly. If you misname an element in a query, your query can erroneously return an empty collection. If you misname an element when generating markup, you will generate an invalid document.. The SDK defines generic methods that take a type parameter so that you can more easily retrieve all Paragraph elements that are child elements of the Body element. In addition, there are a number of places in Open XML where an attribute can have one of several values. The SDK defines enumerations for the properties that represent the attributes; this provides more strongly typed goodness. The API is LINQ friendly, including lazy access, axis methods that parallel the LINQ to XML axes, and annotations so that you can store application specific information on each object.
The easiest way to show the benefits of the new, strongly typed DOM is to present a very small example using LINQ to XML (a weakly typed approach), and the same example using V2 of the SDK.
The following example shows a typical LINQ to XML query to retrieve paragraphs from a word processing document:
var paragraphs = doc.MainDocumentPart .GetXDocument() .Element(w + "document") .Element(w + "body") .Elements(w + "p") .Select ( p => new { ParagraphNode = p, Text = p .Elements() .Where(z => z.Name == w + "r" || z.Name == w + "ins") .Descendants(w + "t") .Select(t => (string)t) .StringConcatenate() } );foreach (var b in paragraphs) Console.WriteLine(b.Text);
The following shows the equivalent LINQ query using the strongly typed DOM:
var build = doc.MainDocumentPart .Document.Body.Elements<Paragraph>() .Select ( p => new { ParagraphNode = p, Text = p .Elements() .Where(z => z is Run || z is InsertedRun) .Select(z => z.Elements<Text>() .Select(t => t.Text) .StringConcatenate()) .StringConcatenate() } );foreach (var b in build) Console.WriteLine(b.Text);
Note that the second version doesn’t use strings to identify the nodes. Instead, you use actual type names. For instance, the following line retrieves all of the child paragraph nodes of the Body element:
var build = doc.MainDocumentPart .Document.Body.Elements<Paragraph>()
In this case, it isn’t possible to misspell “Paragraph”. It is a type name, so would not compile if it were misspelled.
And because we now have strongly typed objects in the DOM, we can write some very cool extension methods that make programming with the DOM much simpler. Also, there is a strongly typed streaming reader and writer. These are topics for another day.
OpenXmlDiff
I’ve blogged about various approaches to comparing two Open XML documents. This is the best approach so far. It is a super tool that should become part of every Open XML developer’s toolkit. The use of it couldn’t be simpler – open two documents, click the compare button, and see the differences:
Open XML Class Explorer
This tool allows you to navigate through the classes in the SDK. Its primary purpose is to allow you to explore the markup and determine the appropriate strongly typed class to use for the markup. This would be super all by itself, but the team has put together something extra! When you click on a class, in addition to seeing the class hierarchy, you also see the actual text of the Ecma 376 specification. This is a very convenient way to explore the specification.
Open XML Document Reflector
If V2 of the SDK only contained the above items, it would be an incredibly impressive release. But, there is more!
The document reflector can really help you to write code to generate documents. In my job as technical evangelist for Open XML, I’ve talked with a large number of customers, and the most common scenario is document generation. Well, this tool really helps!
To use the document reflector, you open a document, and click on a node within the hierarchy of nodes that are presented to you. The document reflector then presents you with C# code to generate that node within the document. You can click on a part, and the document reflector will generate the code to create the part. And if you click on the document node itself, the document reflector presents you with the code to create the entire document. You can then take the code generated by DocumentReflector, parameterize it, and modify it as necessary. This really simplifies the process of creating a program to generate documents.
This version of the toolkit is released with the Community Technology Preview (CTP) license, which means that you can’t deploy solutions using it until it is released with a ‘go-live’ license. However, there is a lot of value in the accompanying tools for developers who must ship using V1 of the SDK.
Finally, because this is a CTP, be aware that the API may change between now and the final release. Sign up for the Open XML SDK Connect site and get all the latest news.
|
http://blogs.msdn.com/b/ericwhite/archive/2008/09.aspx?PageIndex=19
|
CC-MAIN-2014-23
|
refinedweb
| 1,063
| 62.68
|
The Bioconductor build system does not have the MEME Suite installed, therefore these vignettes will not contain any R output. To view the full vignette, visit this article page on the memes website at this link
TomTom is a tool for comparing motifs to a known set of motifs. It takes as input a set of motifs and a database of known motifs to return a ranked list of the significance of the match between the input and known motifs. TomTom can be run using the
runTomTom() function.
runTomTom() can accept a variety of inputs to use as the “known” motif database. The formats are as follows: - a path to a .meme format file (eg
"fly_factor_survey.meme") - a list of universalmotifs - the output object from
runDreme() - a
list() of all the above. If entries are named,
runTomTom() will use those names as the database identifier
memes can be configured to use a default .meme format file as the query database, which it will use if the user does not provide a value to
database when calling
runTomTom(). The following locations will be searched in order:
meme_dboption, defined using
options(meme_db = "path/to/database.meme")
meme_dboption can also be set to an R object, like a universalmotif list.
MEME_DBenvironment variable defined in
.Renviron
MEME_DBvariable will only accept a path to a .meme file
NOTE: if an invalid location is found at one option,
runTomTom() will fall back to the next location if valid (eg if the
meme_db option is set to an invalid file, but the
MEME_DB environment variable is a valid file, the
MEME_DB path will be used.
To use TomTom on existing motifs,
runTomTom() will accept any motifs in
universalmotif format. The
universalmotif package provides several utilities for importing data from various sources.
runTomTom() can also take the output of
runDreme as input. This allows users to easily discover denovo motifs, then match them to as set of known motifs. When run on the output of
runDreme, all
runTomTom() output columns will be appended to the
runDreme() output data.frame, so no information will be lost.
# This is a pre-build dataset packaged with memes # that mirrors running: # options(meme_db = system.file("inst/extdata/db/fly_factor_survey_id.meme", package = "memes")) # example_motif <- create_motif("CCRAAAW") # example_tomtom <- runTomTom(example_motif) data("example_tomtom")
When run using a
universalmotif object as input,
runTomTom returns the following columns:
names(example_tomtom) #> [1] "motif" "name" "altname" #> [4] "family" "organism" "consensus" #> [7] "alphabet" "strand" "icscore" #> [10] "nsites" "bkgsites" "pval" #> [13] "qval" "eval" "type" #> [16] "bkg" "best_match_name" "best_match_altname" #> [19] "best_db_name" "best_match_offset" "best_match_pval" #> [22] "best_match_eval" "best_match_qval" "best_match_strand" #> [25] "best_match_motif" "tomtom"
Columns preappended with
best_ indicate the data corresponding to the best match to the motif listed in
name.
The
tomtom column is a special column which contains a nested
data.frame of the rank-order list of TomTom hits for the motif listed in
name.
names(example_tomtom$tomtom[[1]]) #> [1] "match_name" "match_altname" "match_motif" "db_name" #> [5] "match_offset" "match_pval" "match_eval" "match_qval" #> [9] "match_strand"
The
best_match_motif column contains the universalmotif representation of the best match motif.
/>
The
match_motif column of
tomtom contains the universalmotif format motif from the database corresponding to each match in descending order.
/>
The
drop_best_match() function drops all the
best_match_* columns from the
runTomTom() output.
example_tomtom %>% drop_best_match() %>% names #> [1] "motif" "name" "altname" "family" "organism" "consensus" #> [7] "alphabet" "strand" "icscore" "nsites" "bkgsites" "pval" #> [13] "qval" "eval" "type" "bkg" "tomtom"
To unnest the
tomtom data.frame column, use
tidyr::unnest(). The
drop_best_match() function can be useful when doing this to clean up the unnested data.frame.
unnested <- example_tomtom %>% drop_best_match() %>% tidyr::unnest(tomtom) names(unnested) #> [1] "motif" "name" "altname" "family" #> [5] "organism" "consensus" "alphabet" "strand" #> [9] "icscore" "nsites" "bkgsites" "pval" #> [13] "qval" "eval" "type" "bkg" #> [17] "match_name" "match_altname" "match_motif" "db_name" #> [21] "match_offset" "match_pval" "match_eval" "match_qval" #> [25] "match_strand"
To re-nest the tomtom results, use
nest_tomtom() (Note: that
best_match_ columns will be automatically updated based on the rank-order of the
tomtom data.frame)
unnested %>% nest_tomtom() %>% names #> [1] "name" "altname" "family" #> [4] "organism" "consensus" "alphabet" #> [7] "strand" "icscore" "nsites" #> [10] "bkgsites" "pval" "qval" #> [13] "eval" "type" "bkg" #> [16] "best_match_name" "best_match_altname" "best_match_motif" #> [19] "best_db_name" "best_match_offset" "best_match_pval" #> [22] "best_match_eval" "best_match_qval" "best_match_strand" #> [25] "motif" "tomtom"
While TomTom can be useful for limiting the search-space for potential true motif matches, often times the default “best match” is not the correct assignment. Users should use their domain-specific knowledge in conjunction with the data returned by TomTom to make this judgement (see below for more details). memes provides a few convenience functions for reassigning these values.
First, the
update_best_match() function will update the values of the
best_match* columns to reflect the values stored in the first row of the
tomtom data.frame entry. This means that the rank of the
tomtom data is meaningful, and users should only manipulate it if intending to create side-effects.
If the user can force motifs to contain a certain motif as their best match using the
force_best_match() function.
force_best_match() takes a named vector as input, where the name corresponds to the input motif
name, and the value corresponds to a
match_name found in the
tomtom list data (NOTE: this means that users cannot force the best match to be a motif that TomTom did not return as a potential match).
For example, below the example motif could match either “Eip93F_SANGER_10”, or “Lag1_Cell”.
example_tomtom$tomtom[[1]] %>% head(3) #> match_name match_altname #> 1 Eip93F_SANGER_10 Eip93F #> 2 Lag1_Cell schlank #> 3 pho_SOLEXA_5 pho #> match_motif #> 1 <S4 class 'universalmotif' [package "universalmotif"] with 20 slots> #> 2 <S4 class 'universalmotif' [package "universalmotif"] with 20 slots> #> 3 <S4 class 'universalmotif' [package "universalmotif"] with 20 slots> #> db_name match_offset match_pval match_eval match_qval #> 1 flyFactorSurvey_cleaned 4 8.26e-07 0.000459 0.000919 #> 2 flyFactorSurvey_cleaned 3 1.85e-03 1.030000 0.781000 #> 3 flyFactorSurvey_cleaned 1 2.54e-03 1.410000 0.781000 #> match_strand #> 1 + #> 2 + #> 3 +
The current best match is listed as “Eip93F_SANGER_10”.
example_tomtom %>% dplyr::select(name, best_match_name) #> name best_match_name #> 1 example_motif Eip93F_SANGER_10 #> #> [Note: incomplete universalmotif_df object.]
To force “example_motif” to have the best match as “Lag1_Cell”, do the following:
new_tomtom <- example_tomtom %>% # multiple motifs can be updated at a time by passing additional name-value pairs. force_best_match(c("example_motif" = "Lag1_Cell"))
The
best_match_* columns will be updated to reflect the modifications.
view_tomtom_hits() can be used to compare the hits from tomtom to each input motif. Hits are shown in descending order by rank. By default, all hits are shown, or the user can pass an integer to
top_n to view the top number of motifs. This can be a useful plot for determining which of the matches appear to be the “best” hit.
For example, it appears that indeed “Eip93F_SANGER_10” is the best of the top 3 hits, as most of the matching sequences in the “Lag1_Cell” and “pho_SOLEXA_5” motifs correspond to low information-content regions of the matched motifs.
/>
importTomTomXML() can be used to import a
tomtom.xml file from a previous run on the MEME server or on the commandline. Details for how to save data from the TomTom webserver are below.
To download XML data from the MEME Server, right-click the TomTom XML output link and “Save Target As” or “Save Link As” (see example image below), and save as
<filename>.xml. This file can be read using
importTomTomXML()
/>
memes is a wrapper for a select few tools from the MEME Suite, which were developed by another group. In addition to citing memes, please cite the MEME Suite tools corresponding to the tools you use.
If you use
runTomTom() in your analysis, please cite:
Shobhit Gupta, JA Stamatoyannopolous, Timothy Bailey and William Stafford Noble, “Quantifying similarity between motifs”, Genome Biology, 8(2):R24, 2007. full text
The MEME Suite is free for non-profit use, but for-profit users should purchase a license. See the MEME Suite Copyright Page for details.
sessionInfo() #>] universalmotif_1.12.0 magrittr_2.0.1 memes_1.2.0 #> #> loaded via a namespace (and not attached): #> [1] Rcpp_1.0.7 tidyr_1.1.4 Biostrings_2.62.0 #> [4] ggseqlogo_0.1 assertthat_0.2.1 rprojroot_2.0.2 #> [7] digest_0.6.28 utf8_1.2.2 R6_2.5.1 #> [10] GenomeInfoDb_1.30.0 stats4_4.1.1 evaluate_0.14 #> [13] highr_0.9 ggplot2_3.3.5 pillar_1.6.4 #> [16] zlibbioc_1.40.0 rlang_0.4.12 jquerylib_0.1.4 #> [19] S4Vectors_0.32.0 R.utils_2.11.0 R.oo_1.24.0 #> [22] rmarkdown_2.11 desc_1.4.0 readr_2.0.2 #> [25] stringr_1.4.0 cmdfun_1.0.2 RCurl_1.98-1.5 #> [28] munsell_0.5.0 compiler_4.1.1 xfun_0.27 #> [31] pkgconfig_2.0.3 BiocGenerics_0.40.0 htmltools_0.5.2 #> [34] tidyselect_1.1.1 tibble_3.1.5 GenomeInfoDbData_1.2.7 #> [37] IRanges_2.28.0 matrixStats_0.61.0 fansi_0.5.0 #> [40] crayon_1.4.1 dplyr_1.0.7 tzdb_0.1.2 #> [43] withr_2.4.2 MASS_7.3-54 bitops_1.0-7 #> [46] R.methodsS3_1.8.1 waldo_0.3.1 grid_4.1.1 #> [49] jsonlite_1.7.2 gtable_0.3.0 lifecycle_1.0.1 #> [52] DBI_1.1.1 scales_1.1.1 stringi_1.7.5 #> [55] farver_2.1.0 XVector_0.34.0 testthat_3.1.0 #> [58] bslib_0.3.1 ellipsis_0.3.2 generics_0.1.1 #> [61] vctrs_0.3.8 tools_4.1.1 glue_1.4.2 #> [64] purrr_0.3.4 hms_1.1.1 pkgload_1.2.3 #> [67] fastmap_1.1.0 yaml_2.2.1 colorspace_2.0-2 #> [70] GenomicRanges_1.46.0 knitr_1.36 sass_0.4.0
|
http://bioconductor.org/packages/release/bioc/vignettes/memes/inst/doc/core_tomtom.html
|
CC-MAIN-2021-49
|
refinedweb
| 1,546
| 55.54
|
Java stream order of processing
Streams may or may not have a defined encounter order. Whether or not a stream
has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as
java.util.List or arrays) are intrinsically ordered, whereas others (such as
java.util.HashSet)
are not. Some intermediate operations, such as
sorted(), may impose an encounter order on an otherwise
unordered stream, and others may render an ordered stream unordered, such as
BaseStream].
List<Integer> ints = List.of(1, 2, 3); Stream<Integer> str = ints.stream(); Spliterator<Integer> spl = str.spliterator(); System.out.print(spl.hasCharacteristics(Spliterator.ORDERED));
true
However, if the source has no defined encounter order, then any permutation of the
values
[2, 4, 6] would be a valid result.
HashSet<Integer> ints = new HashSet<>(); ints.add(1); ints.add(2); ints.add(3); Stream<Integer> str = ints.stream(); Spliterator<Integer> spl = str.spliterator(); System.out.print(spl.hasCharacteristics(Spliterator.ORDERED));
false
Finding the first element -
findFirst()
For ordered streams you may wish to find the first element. There is the
findFirst() method for this:
Optional<T> findFirst();
For example, given a list of integers, finds the first number that is divisible by
7:
List<Integer> ints = List.of(1, 6, 22, 21, 35, 36); Optional<Integer> result = ints.stream().filter(i -> i % 7 == 0).findFirst(); result.ifPresentOrElse(System.out::print, () -> System.out.print("No results found"));
Finding an element -
findAny()
The
findAny() method returns an arbitrary element of the current stream.
Optional<T> findAny();
It can be used in conjunction with other stream operations. For example, you may wish to find any manager
from employee list. You can combine the
filter(...) method and
findAny
to express this query:
public class Employee { public static final int MANAGER=100; public int type; public String name; public Employee(int t, String n) { type = t; name = n; } }
Stream<Employee> emps = Stream.of(new Employee(100, "John"), new Employee(100, "Jane"), new Employee(99, "Deb")); Optional<Employee> mgr = emps.filter(a -> a.type == Employee.MANAGER).findAny(); System.out.print(mgr.get().name);
The stream pipeline will be optimized behind the scenes to perform a single pass and finish as soon as a result is found by using short-circuiting.
You may wonder why Java 8.0 introduced both
findFirst() and
findAny(). The reason behind
findAny() is to give a more flexible alternative to
findFirst(). If you are
not interested in getting a specific element, this gives the implementing stream more flexibility in case
it is a parallel stream.
No effort will be made to randomize the element returned, it just does
not give the same guarantees as
findFirst(), and might therefore be faster.
The behavior of
findAny() operation is explicitly nondeterministic; it is free to select
any element in the stream. This is to allow for maximal performance in parallel operations; the cost
is that multiple invocations on the same source may not return the same result. If a stable result is
desired, use
findFirst() instead.
Checking to see if a predicate matches at least one element -
anyMatch(...)
The
anyMatch(...) method can be used to answer the question "Is there an element in the stream
matching the given predicate?" It accepts
Predicate as parameter:
boolean anyMatch(Predicate<? super T> predicate);
For example, you can use it to find out whether company has an employee with name "
Mikalai":
Stream<Employee> emps = Stream.of(new Employee(100, "Minerva"), new Employee(100, "Mikalai"), new Employee(99, "Michael")); boolean b = emps.anyMatch(e -> "Mikalai".equalsIgnoreCase(e.name)); if (b) { System.out.print("There is an employee with name 'Mikalai'"); }
The
anyMatch(...) method returns a
boolean and is therefore a terminal operation.
Checking to see if a predicate matches all elements -
allMatch(...)
The
allMatch(...) method works similarly to
anyMatch(...) but will check to see
if all the elements of the stream match the given predicate:
boolean allMatch(Predicate<? super T> predicate);
For example, you can use it to find out
whether all employee names start with "
Mi":
Stream<Employee> emps = Stream.of(new Employee(100, "Minerva"), new Employee(100, "Mikalai"), new Employee(99, "Michael")); boolean b = emps.allMatch(e -> e.name.startsWith("Mi")); if (b) { System.out.println("All employee names start with 'Mi'"); }
Checking to see if a predicate does not match any element -
noneMatch(...)
The opposite of
allMatch(...) is
noneMatch(...). It ensures that no elements in the
stream match the given predicate:
boolean noneMatch(Predicate<? super T> predicate);
For example, you can use it to find out whether company has an employee with
name "
Gandalf":
Stream<Employee> emps = Stream.of(new Employee(100, "Minerva"), new Employee(100, "Mikalai"), new Employee(99, "Michael")); boolean b = emps.noneMatch(e -> e.name.equals("Gandalf")); if (b) { System.out.print("Gandalf is employed by some other company !"); }
|
http://java.boot.by/ocpjd11-upgrade-guide/ch04s02.html
|
CC-MAIN-2021-21
|
refinedweb
| 796
| 50.02
|
To steal a quote from JWZ,
Some people, when confronted with a problem, think “I know, I’ll use cgo.”
Now they have two problems.
Recently the use of cgo came up on the Gophers’ slack channel and I voiced my concerns that using cgo, especially on a project that is intended to showcase Go inside an organisation was a bad idea. I’ve said this a number of times, and people are probably sick of hearing my spiel, so I figured that I’d write it down and be done with it.
cgo is an amazing technology which allows Go programs to interoperate with C libraries. It’s a tremendously useful feature without which Go would not be in the position it is today. cgo is key to ability to run Go programs on Android and iOS.
However, and to be clear these are my opinions, I am not speaking for anyone else, I think cgo is overused in Go projects. I believe that when faced with reimplementing a large piece of C code in Go, programmers choose instead to use cgo to wrap the library, believing that it is a more tractable problem. I believe this is a false economy.
Obviously, there are some cases where cgo is unavoidable, most notably where you have to interoperate with a graphics driver or windowing system that is only available as a binary blob. But those cases where cgo’s use justifies its trade-offs are fewer and further between than many are prepared to admit.
Here is an incomplete list of trade-offs you make, possibly without realising them, when you base your Go project on a cgo library.
Slower build times
When you
import "C" in your Go package,
go build has to do a lot more work to build your code. Building your package is no longer simply passing a list of all the
.go files in scope to a single invocation of
go tool compile, instead:
- The cgo tool needs to be invoked to generate the C to Go and Go to C thunks and stubs.
- Your system C compiler has to be invoked for every C file in the package.
- The individual compilation units are combined together into a single .o file.
- The resulting .o file take a trip through the system linker for fix-ups against shared objects they reference.
All this work happens every time you compile or test your package, which is constantly, if you’re actively working in that package. The Go tool parallelises some of this work where possible, but your packages’ compile time just grew to include a full rebuild of all that C code.
It’s possible to work around this by pushing the cgo shims out into their own package, avoiding the compile time hit, but now you’ve had to restructure your application to work around a problem that you didn’t have before you started to use cgo.
Oh, and you have to debug C compilation failures on the various platforms your package supports.
Complicated builds
One of the goals of Go was to produce a language who’s build process was self describing; the source of your program contains enough information for a tool to build the project. This is not to say that using a
Makefile to automate your build workflow is bad, but before cgo was introduced into a project, you may not have needed anything but the
go tool to build and test. Afterwards, to set all the environment variables, keep track of shared objects and header files that may be installed in weird places, now you do.
Keep in mind that Go supports platforms that don’t ship with make out of the box, so you’ll have to dedicate some time to coming up with a solution for your Windows users.
Oh, and now your users have to have a C compiler installed, not just a Go compiler. They also have to install the C libraries your project depends on, so you’ll be taking on that support cost as well.
Cross compilation goes out the window
Go’s support for cross compilation is best in class. As of Go 1.5 you can cross compile from any supported platform to any other platform with the official installer available on the Go project website.
By default cgo is disabled when cross compiling. Normally this isn’t a problem if your project is pure Go. When you mix in dependencies on C libraries, you either have to give up the option to cross compile your product, or you have to invest time in finding and maintaining cross compilation C toolchains for all your targets.
Maybe if you work on a product that only communicates with clients over TCP sockets and you intend to run it in a SaaS model it’s reasonable to say that you don’t care about cross compilation. However, if you’re making a product which others will use, possibly integrated into their products, maybe it’s a monitoring solution, maybe it’s a client for your SaaS service, then you’ve locked them out of being able to easily cross compile.
The number of platforms that Go supports continues to grow. Go 1.5 added support for 64 bit ARM and PowerPC. Go 1.6 adds support for 64 bit MIPS, and IBM’s s390 architecture is touted for Go 1.7. RISC-V is in the pipeline. If your product relies on a C library, not only do you have the all problems of cross compilation described above, you also have to make sure the C code you depend on works reliably on the new platforms Go is supporting — and you have to do that with the limited debuggability a C/Go hybrid affords you. Which brings me to my next point.
You lose access to all your tools
Go has great tools; we have the race detector, pprof for profiling code, coverage, fuzz testing, and source code analysis tools. None of those work across the cgo blood/brain barrier.
Conversely excellent tools like valgrind don’t understand Go’s calling conventions or stack layout. On that point, Ian Lance Taylor’s work to integrate clang’s memory sanitiser to debug dangling pointers on the C side will be of benefit for cgo users in Go 1.6.
Combing Go code and C code results in the intersection of both worlds, not the union; the memory safety of C, and the debuggability of a Go program.
Performance will always be an issue
C code and Go code live in two different universes, cgo traverses the boundary between them. This transition is not free and depending on where it exists in your code, the cost could be inconsequential, or substantial.
C doesn’t know anything about Go’s calling convention or growable stacks, so a call down to C code must record all the details of the goroutine stack, switch to the C stack, and run C code which has no knowledge of how it was invoked, or the larger Go runtime in charge of the program.
To be fair, Go doesn’t know anything about C’s world either. This is why the rules for passing data between the two have become more onerous over time as the compiler becomes better at spotting stack data that is no longer considered live, and the garbage collector becomes better at doing the same for the heap.
If there is a fault while in the C universe, the Go code has to recover enough state to at least print a stack trace and exit the program cleanly, rather than barfing up a core file.
Managing this transition across call stacks, especially where signals, threads and callbacks are involved is non trivial, and again Ian Lance Taylor has done a huge amount of work in Go 1.6 to improve the interoperability of signal handling with C.
The take away is that the transition between the C and Go world is non trivial, and it will never be free from overhead.
C calls the shots, not your code
It doesn’t matter which language you’re writing bindings or wrapping C code with; Python, Java with JNI, some language using libFFI, or Go via cgo; it’s C’s world, you’re just living in it.
Go code and C code have to agree on how resources like address space, signal handlers, and thread TLS slots are to be shared — and when I say agree, I actually mean Go has to work around the C code’s assumption. C code that can assume it always runs on one thread, or blithely be unprepared to work in a multi threaded environment at all.
You’re not writing a Go program that uses some logic from a C library, instead you’re writing a Go program that has to coexist with a belligerent piece of C code that is hard to replace, has the upper hand negotiations, and doesn’t care about your problems.
Deployment gets more complicated
Any presentation on Go to a general audience will contain at least one slide with these words:
Single, static binary
This is Go’s ace in the hole that has lead it to become a poster child of the movement away from virtual machines and managed runtimes. Using cgo, you give that up.
Depending on your environment, it’s probably possible to build your Go project into a deb or rpm, and assuming your other dependencies are also packaged, add them as an install dependency and push the problem off the operating system’s package manager. But that’s several significant changes to a build and deploy process that was previously as straight forward as
go build && scp.
It is possible to compile a Go program entirely statically, but it is by no means simple and shows that the ramifications of including cgo in your project will ripple through your entire build and deploy life cycle.
Choose wisely
To be clear, I am not saying that you should not use cgo. But before you make that Faustian bargain, please consider carefully the qualities of Go that you’ll be giving up in return.
|
https://dave.cheney.net/2016/01
|
CC-MAIN-2017-13
|
refinedweb
| 1,710
| 63.73
|
[Angular2] "ons is not defined" using latest Angular-CLI
Hi all,
I am trying to get OnsenUI set up in my new Angular2 project using the latest beta of Angular-CLI which uses Webpack. There was an earlier post about Angular-CLI here, but that is about an older version of the Angular-CLI that still uses SystemJS.
The error I get when I load the page is “ons is not defined”. I have tried adding
window.ons = require('onsenui');
and
window['ons'] = require('onsenui/js/onsenui.js');
in multiple files (app/index.ts, app/main.ts, ./main.ts) but to no avail.
Can someone point me in the right direction? I think it would be good if there is documentation on how to set up OnsenUI using Angular-CLI since that is definitely the easiest way to get an Angular2 project up and running at the moment.
I figured it out. I needed these entries in my angular-cli.json:
"styles": [ "../node_modules/onsenui/css/onsen-css-components.css", "../node_modules/onsenui/css/onsenui.css" ], "scripts": [ "../node_modules/onsenui/js/onsenui.js" ],
Thanks for the post, I agree the docs do need desperately updating in terms of support for Angular2 and the cli.
I followed your steps and I managed to get past the ons is undefined error. I can call onsNotification.alert() and that all works great.
However, I cannot seem to create any components as I am now getting
’ons-page is not a known element’
I seem to have loaded everything apart from the components themselves - where there any other steps you followed apart from:
- npm install -save onsenui angular2-onsenui
- import { OnsenModule } from ‘angular2-onsenui’; (in app.module.ts)
- Listing OnsenModule as an import in app.module.ts
- The steps outlined above
Many Thanks,
Ed
Sorry this was my own stupid fault I should have read the debug properly:
needed to add
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from ‘@angular/core’;
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
],
to app.module.ts
|
https://community.onsen.io/topic/930/angular2-ons-is-not-defined-using-latest-angular-cli
|
CC-MAIN-2019-04
|
refinedweb
| 326
| 55.54
|
Beyond the Java Server Pages (17 messages)
HJ incorporates Java and HTML operators into a single formal grammar. We may consider the language as consisting of three parts – subset of Java, subset of HTML and all the rest. The latter serves for code factorization and reuse as well as for ‘gluing’ Java and HTML. Widgets are the units of code reuse. The HJ code of an application is provided as a set of .page files (one per Web page) and a set of .widget files. A widget may define named attributes and/or named slots (or one anonymous slot). A slot is somewhat similar to the position between opening and closing a ‘library tag’. The code in HJ slots has Java context of the point of call of the widget, so widgets are transparent for Java context (same as HTML elements are by the way). The rest of the .widget file is just ARBITRARY HJ code – no other programming support or configuration is necessary to define a widget. Technology suggests a very natural framework that includes application, page and widget data persistent in the scope of HTTP session. Developer defines such data as members of ‘code-behind’ classes, which may contain handlers of those states called by the framework with a proper dispatching in case of widgets. Compiler resolves the identifiers used in widgets and pages against Java definitions in Java blocks, definitions of widget attributes, in instances of widgets and page state classes. Widgets may send signals to parent and page. FREE FOR NON-COMMERCIAL USE Home: Detailed Language Definition (informal): Running Sample Application: Download: The aim was to develop something more-more convenient than ... you name it. Please tell what you think, report bugs and advice missing features. It is just a beta. No question - ASK QUESTIONS!
- Posted by: Alex Serov
- Posted on: June 10 2009 07:25 EDT
Threaded Messages (17)
- Re: Beyond the Java Server Pages by toto toto on June 10 2009 09:37 EDT
- Comparing with Wicket by Alex Serov on July 26 2009 01:49 EDT
- Re: Comparing with Wicket by Jonathan Locke on August 02 2009 01:29 EDT
- HybridJava versus Wicket by Alex Serov on August 29 2009 04:57 EDT
- the bottom line... by Eelco Hillenius on March 31 2010 08:46 EDT
- ... to pull any logic out of the templates by Alex Serov on July 05 2010 12:37 EDT
- Re: Beyond the Java Server Pages by Alex Serov on November 24 2010 21:37 EST
- Re: Beyond the Java Server Pages by Dushyanth Inguva on June 10 2009 10:18 EDT
- Re: Beyond the Java Server Pages by augustientje bloem on June 10 2009 14:56 EDT
- HJ by Alex Serov on August 05 2009 03:02 EDT
- Re: Beyond the Java Server Pages by jelmer kuperus on June 11 2009 02:11 EDT
- HybridJava version 0.96 available by Alex Serov on September 13 2009 17:26 EDT
- HybridJava version 0.97 released by Alex Serov on November 30 2009 15:40 EST
- HybridJava version 0.98 released by Alex Serov on December 19 2009 02:43 EST
- Principles of HybridJava Framework Component Model by Alex Serov on January 26 2010 03:22 EST
- HybridJava version 1.02 released by Alex Serov on November 25 2010 23:16 EST
- HybridJava version 1.05 released by Alex Serov on October 03 2011 09:30 EDT
Re: Beyond the Java Server Pages[ Go to top ]
I've read the (short) documentation, but I still fail to see how this framework could be better than, say, Wicket, with regards to ease of use, HTML/Java separation, or reusability/componentization. Not to mention that it's not even free/opensource. Did I miss some kind of secret feature that would make me think otherwise ?
- Posted by: toto toto
- Posted on: June 10 2009 09:37 EDT
- in response to Alex Serov
Comparing with Wicket[ Go to top ]
Hi Olivier! Thank you for reading "short documentation". That is ALL the documentation HybridJava has and needs, so thank you for this compliment. I agree that you missed something. You suggest that the problem is in "HTML/Java separation" while we think that JSP was invented for combining HTML and Java in one source. Next you missed that the problem is in generation of dynamic content. Which is not only about filling well known positions in a form with varying data but also about varying structure of page. HybridJava cares about IDs of components even under loops and recursions. What I saw so far in Wicket is all around manual assigning IDs. Did I miss something?
- Posted by: Alex Serov
- Posted on: July 26 2009 01:49 EDT
- in response to toto toto
Re: Comparing with Wicket[ Go to top ]
Yes. But you would have to be looking to find it.
- Posted by: Jonathan Locke
- Posted on: August 02 2009 13:29 EDT
- in response to Alex Serov
HybridJava versus Wicket[ Go to top ]
Hi! Suggesting that the problem to be solved is in "HTML/Java separation" is a fundamental (though common) misunderstanding. The promise of initial JSP was about interlaying (which means combining, not separating) HTML markup and Java within the presentation layer code. Respecting the boundary between the Presentation Layer and the Business Layer is a must, but note that the former has logic of its own too. The JSP way of doing things is in using Java to code presentation logic. To understand Wicket, I got the book “Pro Wicket” by Karthik Gurumurthy. What does this specific technology provide to express the component structure of the application? The book tells “You can liken Wicket development to Swing development” and also “the component hierarchy is specified explicitly through Java code” (p 9). In other words it is done the way it was some 15 years ago with Visual Basic and all the rest desktop UI development tools. There is nothing bad in such an approach, but alas, that is a pre-HTML presentation technology. Technically it is about manually coding endless “new” and “add” operations. Reading further one finds out that the “component hierarchy” (structure) is simultaneously depicted in a form of markup. This duplication of information is a step back even compared to the Visual Basic. See Listings 4.19 to 4.22 pages 129-130 – MyBorder is the most compact example I found. If you code the same example in HybridJava all will look indeed very similar … except that there will be NO listings 4.20 and 4.22 at all. Actually HybridJava has a similar example running over here: By the way, what is the need for MyBorder to be a component if it does have neither state nor beheavior? A simple answer is that the Wicket framework has nothing of lighter weight than a component. HybridJava has. HybridJava approach is that presentation components (in that they have place in the hierarchy) are nothing different from HTML elements and thus markup is sufficient. A clever enough framework may (and HybridJava does) figure out all the rest behind the scenes. In particular HybridJava framework performs all necessary “new” and “add” operations and assigns dynamic IDs. More on IDs: page 216 states “This feature demonstrates Wicket’s excellent support for dynamic templates.” Actually, they probably meant to say that Tabbed Panel example (NOT a feature!) demonstrates something. What it demonstrates in reality is that the Wicket framework has completely failed to solve the dynamic IDs puzzle. This specific example works, but only because in the book’s own words “At any given point in time, only one Panel can be active or visible”. HybridJava has solved the dynamic IDs puzzle. Another thing that the book shadows is the Wicket solution for loops. In the Wicket framework even a plain loop is a component, so the “Wicket way” of coding repetitions in presentation layer is (in ADDITION to markup!) something like: Loop loop = new Loop( new LoopItem( … // Lisp is immortal !!! HybridJava is not that “revolutionary” and sticks to using traditional Java “while” keyword. So what is the bottom line? Compare two things: 1) A compiler from some programming language 2) A printed instruction on how to manually “compile” from a similar language. That is exactly how HybridJava compares to Wicket. PS. HybridJava version 0.95 is available. Examples from the “Pro Wicket” Book: // 4.19 // 4.20 package com.apress.wicketbook.layout; import wicket.markup.html.border.Border; public class MyBorder extends Border { public MyBorder(String id) { super(id); } } // 4.21 Label content goes here Back to Index // 4.22 package com.apress.wicketbook.layout; import wicket.markup.html.WebPage; import wicket.markup.html.basic.Label; import wicket.markup.html.border.Border; import wicket.model.Model; public class MyPage extends WebPage { public MyPage() { Border border = new MyBorder("myborder"); add(border); border.add(new Label("label", new Model(" Wicket Rocks 8-) "))); } }
- Posted by: Alex Serov
- Posted on: August 29 2009 16:57 EDT
- in response to Jonathan Locke
the bottom line...[ Go to top ]
So what is the bottom line?The bottom line is that you only learned about Wicket to find what you supposed were the weak spot and completely didn't get the point of what Wicket aims for. One of it major aims is to pull *any* logic out of the templates. Much follows because of that.
- Posted by: Eelco Hillenius
- Posted on: March 31 2010 20:46 EDT
- in response to Alex Serov
... to pull any logic out of the templates[ Go to top ]
- Posted by: Alex Serov
- Posted on: July 05 2010 12:37 EDT
- in response to Eelco Hillenius
I apologize for late reply. Sorry did not see your notice before. Same is not true regarding "One of it major aims" of Wicket. That is a too known concern to be overlooked. And unfortunately that is a widely misinterpreted concern. The right formula is a clear separation of presentation layer from all the rest. And as long as we seek to have a dynamic presentation layer the latter is doomed to have at least some logic of its own. All who tell you otherwise are kidding you. You understand that nothing essential changes if you use <if syntax instead of plain if. Adding conditional generation into markup language IS adding logic. (Side note - I wonder if cpp was ever used for conditional generation of HTML).
I would not agree that the discussed is the major aim for anybody, but HybridJava address this concern better. The question is how and at what cost. In HybridJava there are no predefined widgets, but you can easily define what you like at no cost. In the Sample Application with the current (1.01) version you can find examples of that. In the Wicket the cost is redundant java programming and redundant instances as each loop is a component there (ha ha ha).
Re: Beyond the Java Server Pages[ Go to top ]
- Posted by: Alex Serov
- Posted on: November 24 2010 21:37 EST
- in response to toto toto
1. To see how this framework could be better please try to program any of examples from our sample application () using Wicket. I doubt that is possible at all. If possible then how much effort will that take and how slow will that work?
2. Verson 1.02 is currently (for promotional period) available for free.
3. The source code run-time of version 1.02 is provided as open source.
Re: Beyond the Java Server Pages[ Go to top ]
He he. You said HJ
- Posted by: Dushyanth Inguva
- Posted on: June 10 2009 10:18 EDT
- in response to Alex Serov
Re: Beyond the Java Server Pages[ Go to top ]
- Posted by: augustientje bloem
- Posted on: June 10 2009 14:56 EDT
- in response to Dushyanth Inguva
He he. You said HJWell, doesn't this technology relieves us from the Hand Job of crafting our JSP pages manually? *lol*
HJ[ Go to top ]
When I submitted the article I defined HJ as HybridJava in the summary. I did not see that summary any more. Sorry for inconvenience.
- Posted by: Alex Serov
- Posted on: August 05 2009 03:02 EDT
- in response to Dushyanth Inguva
Re: Beyond the Java Server Pages[ Go to top ]
i used hybrid server pages with the jt framework great succes!
- Posted by: jelmer kuperus
- Posted on: June 11 2009 02:11 EDT
- in response to Alex Serov
HybridJava version 0.96 available[ Go to top ]
- Posted by: Alex Serov
- Posted on: September 13 2009 17:26 EDT
- in response to Alex Serov
HybridJava version 0.97 released[ Go to top ]
- Posted by: Alex Serov
- Posted on: November 30 2009 15:40 EST
- in response to Alex Serov
HybridJava version 0.98 released[ Go to top ]
This version supports multilingual web development
- Posted by: Alex Serov
- Posted on: December 19 2009 02:43 EST
- in response to Alex Serov
Principles of HybridJava Framework Component Model[ Go to top ]
1. The MVC paradigm Web application components are reusable presentation layer modules that follow the MVC paradigm. So, each component may have its own View, Controller, and may be connected to a relevant part of the Model. 2. The One Touch principle Using a component to build a page or another component must be as simple as using an HTML tag, and must not require any programming or configuration. 3. Independence A page (or a containing component) doesn’t need to know anything about the contained component, and vice versa. 4. Session Scope Persistence The framework has to keep the state of each component until the session expires. This behavior should not depend on the current page shown or on component’s actual visibility on its page. 5. In-page Reusability A component may be used in a page (or containing component) more than once. For each use the framework must support an independent state. 6. Inter-page Sharing A component may be declared as shared between several pages. Then, only one instance should be created by the framework for all the Views of that component. 7. Dispatching of Information Framework should pass information about user actions (in particular about submit) to appropriate component instances. This should not require any additional programming, configuration or assigning of IDs to the components. 8. Inter-Component Communication At the View phase a component/page should be able to pass information to contained components via widget parameters. At the Controller phase the framework API should support communication between a component and containing component/page. QUESTION to the READERS: What is a meaning of the word "component" as it used in the context of JSF, Wicket, Struts and other frameworks. In which of those frameworks the component model is in fact a model of MVC components?
- Posted by: Alex Serov
- Posted on: January 26 2010 03:22 EST
- in response to Alex Serov
HybridJava version 1.02 released[ Go to top ]
- Posted by: Alex Serov
- Posted on: November 25 2010 23:16 EST
- in response to Alex Serov
Now all the run-time code available as Open Source.
HybridJava version 1.05 released[ Go to top ]
- Posted by: Alex Serov
- Posted on: October 03 2011 09:30 EDT
- in response to Alex Serov
With embedded comonent-oriented support for Ajax. And more.
|
http://www.theserverside.com/news/thread.tss?thread_id=54866
|
CC-MAIN-2014-35
|
refinedweb
| 2,546
| 63.7
|
We briefly mentioned the enum in our last lesson, so I felt like now would be a great time to cover it in greater depth. At the same time, we can expand on the topic and introduce Flags (bit masks). Some of this gets a bit deeper into the nerdy side of programming, but I will try to keep everything easy to understand.
The “enum” type
I first introduced the enum in the previous lesson with the “Difficulties” settings:
public enum Difficulties { Easy, Medium, Hard, Count }
This bit of code can be placed outside of a class and it becomes a “global” type which can be used by any of your scripts. You could also place it inside of a class, but then to access it, you need to reference the enum through dot notation.
// This form can be used when Difficulties is not contained in a class // or when it is defined in the current class Difficulties d1 = Difficulties.Easy; // This form is used when Difficulties is defined in a class // other than the current class Demo.Difficulties d2 = Demo.Difficulties.Easy;
The type of the enum is unique to itself, although it has an underlying type (by default an ‘int’). It is possible to change the underlying type in the declaration such as specifying “byte” which you could do if you know you won’t have a large range of values which need to be represented. The form looks pretty similar to class inheritance, where the underlying type is referenced after a colon such as in the following example:
public enum Difficulties : byte { Easy, Medium, Hard, Count }
With an instance of a class, you can assign it to a reference of a “base” type without casting. This is not true with enums – instead you must cast it or else you will see an error: “error CS0266: Cannot implicitly convert type `Demo.Difficulties’ to `byte’. An explicit conversion exists (are you missing a cast?)”
void Start () { // Implicit conversion of an instance to base type is ok MonoBehaviour script = this; // Implicit conversion of an enum to an underlying type is not ok... // byte value = Difficulties.Easy; // ... Use this instead byte value = (byte)Difficulties.Easy; }
The values in our enum begin with the default value of the underlying type (‘0’) and count up, although you can specify any value which the underlying type can contain. Left alone, our Difficulties values would range from 0 to 3. To specify values, use the following form:
public enum Multipliers { Negative = -1, Nullify = 0, Positive = 1 }
Note that because the values auto-increment, I could also have only specified the “Negative” value, and the other entries would have been correctly assigned.
Bits and Bit Shifting
One of the neat uses of enums comes by way of using them as a bit mask. However, before we begin covering that, it may be useful to have a general understanding of what is going on under the hood.
Bits refer to the binary sequence of 0’s and 1’s that together are used to define more complex things. Data-types require a certain number of bits to be fully represented. A ‘byte’ for example, requires 8 bits like the following:
00000000
The numerical value of the previous sample was zero, and as you turn on (set bits to 1 at various locations) you get combinations making the other numbers. Here are a few numbers in order with their associated bit pattern:
00000000 = 0 00000001 = 1 00000010 = 2 00000011 = 3 00000100 = 4
Hopefully you can see the pattern here, where you increment to a one, then move a place over and reset the other bit to 0 to continue incrementing the numerical value.
Some programmers look at this and think, “I could use this sequence of bits like an array of bool” – and without needing the equivalent amount of storage (note that a ‘bool’ requires 8-bits). So basically they are looking at each bit position and saying, is this bit a 0 (false) or 1 (true).
Some simple math can reveal the position of each bit: 2 to the power of the index of the bit you want to set, remember to start counting from zero:
00000001 = 2^0 = 1 00000010 = 2^1 = 2 00000100 = 2^2 = 4 00001000 = 2^3 = 8
But if you don’t want to remember the math, you can use something called bit-shifting. You will use “<<” to shift a bit to the left. We will use this method for declaring the values of enum flags in a moment:
00000001 = 1 << 0 00000010 = 1 << 1 00000100 = 1 << 2 00001000 = 1 << 3
Flags (Bit Mask)
Sometimes you will see an enumeration marked with “Flags” as in the following:
[System.Flags] public enum Colors { None = 0, Red = 1 << 0, Green = 1 << 1, Blue = 1 << 2 }
The ‘Flags’ marker has no effect on the enum itself, or the default values that are assigned to its elements – Note that I still had to manually assign the power of 2 values. Under the hood, this ‘Colors’ enum still has an underlying type of ‘int’ and can hold any value an ‘int’ can hold and can have its elements assigned to any value you like within that range, just as you could have done without using the ‘Flags’ marker. The reason you use the marker is to enable other functionality such as modifying the output of
ToString() which can output the names of the combined flags rather than the numerical equivalent of the underlying type.
Because I defined each element as a power of two, this enum can be treated as a ‘Bit Mask’, which means that you can specify any combination of the elements (and easily turn them on or off at any time), rather than pointing only to a single element at a time.
Several features you will frequently want are shown in code below:
void Start () { // Create a variable to hold our Bit Mask Colors c = Colors.None; // Turn a bit on c |= Colors.Red; // Or directly assign a combination of bits c = Colors.Blue | Colors.Green; // This can also be used in the definition of new elements within the enum type itself // Turn a bit off c &= ~Colors.Blue; // Check whether or not a bit is 'on' if ((c & Colors.Green) == Colors.Green) { // The flag is 'on' } }
Some of this looks a bit hard to read, so I will explain it now. The vertical line ‘|’ is read ‘OR’ which means that you are modifying the sequence of bits to be ‘on’ in any location that either of the other numbers bits had been ‘on’.
So for example, this line
c = Colors.Blue | Colors.Green; looks at the two bit sequences to make a third bit sequence where any bit that was a ‘1’ from either value will be a ‘1’ in the final output:
00000010 - Green 00000100 - Blue -------- // Perform an OR so that a one in any column is passed along 00000110 - Green, Blue
The ‘&’ is read ‘AND’ but is very different from ‘OR’ because it requires that the same bit (index-wise) be enabled on both numbers in order for the final output to also be enabled. Since Green and Blue have different indexes, using ‘AND’ on them would result in zero, or ’Colors.None’.
The ‘~’ is read ‘NOT’ and refers to a bit sequence which is opposite of the current sequence (every 0 becomes a 1 and vice-versa). We used a combination of ‘AND’ and ‘NOT’ to remove a flag, which works like this:
00000110 - Green, Blue // Our starting value has two flags enabled 11111011 - This is ‘NOT’ Blue -------- // Perform an AND on these two sequences leaves only the bits which are both enabled 00000010 - Back to only Green
BitMasks and Unity
Unity can serialize your enum’s just fine, unfortunately, it doesn’t auto provide a mask-selection type inspector by default. You will get a nice named drop down list to select a single entry at a time, but not the ability to select multiple entries as you would with a Camera culling mask as one example. You can however write a custom inspector for your script and expose a property using
EnumMaskField to get the functionality you want.
For example, your script “Demo.cs”:
using UnityEngine; using System.Collections; [System.Flags] public enum Colors { None = 0, Red = 1 << 0, Green = 1 << 1, Blue = 1 << 2, } public class Demo : MonoBehaviour { public Colors color; }
Can be coupled with a special inspector script “DemoInspector.cs” (Note that this script must be located inside a folder called “Editor” to work:
using UnityEngine; using UnityEditor; using System.Collections; [CustomEditor (typeof(Demo))] public class DemoInspector : Editor { public override void OnInspectorGUI () { Demo demo = (Demo)target; demo.color = (Colors)EditorGUILayout.EnumMaskField ( "Colors", demo.color ); } }
Summary
In this lesson I covered enums and their uses, including use as bit-masks. We took an in-depth view of how the bits are represented and covered common use scenarios like turning bits on and off or checking the status of a bit. Some of these features are not as “readable” as other coding options, but they are usually more efficient, so they make sense to use in certain scenarios. Finally, we showed how Unity can use a bit mask in editor by writing a custom editor script.
|
https://theliquidfire.com/2015/03/18/enums-and-flags/
|
CC-MAIN-2021-10
|
refinedweb
| 1,548
| 62.61
|
Pre knowledge
Segment tree
Segment tree is a binary search tree, which is similar to interval tree. It divides an interval into some unit intervals, and each unit interval corresponds to a leaf node in the segment tree.
Using the segment tree, you can quickly find the number of occurrences of a node in several segments. The time complexity is \ (O(log\ n) \).
If you don't know the line segment tree, it is recommended to start with some simple topics, such as Luogu P3372 [template] segment tree 1.
Maximum sub segment sum
The maximum sub segment sum is defined as the sequence \ (a_1,a_2,a_3,\ldots,a_n \) composed of given \ (n \) integers (possibly negative numbers), and the maximum value of the sub segment sum of the sequence such as \ (a_i,a_{i+1},\ldots,a_j \).
dp or recursion are generally used to solve such problems.
meaning of the title
Given a sequence \ (a_1,a_2,\ldots,a_n \), two operations are supported:
Operation 1: find the maximum sub segment sum of interval \ ([l,r] \).
Action 2: change \ (a_x \) to \ (k \).
solution
Firstly, it can be found that the maximum sub segment sum satisfies interval addition, so we can think of using segment tree to maintain.
However, interval addition cannot be directly used in this problem. For example, the maximum sum of sub segments of \ (\ {1, - 1 \} \) is \ (1 \), and the maximum sum of sub segments of \ (\ {- 1,1 \} \) is also \ (1 \), but the maximum sum of sub segments of \ (\ {1, - 1, - 1,1 \} \) is \ (1 \), not directly \ (1 + 1 = 2 \).
We need special maintenance methods.
Through observation, it can be found that for an interval with a length greater than \ (1 \), the maximum sub segments and intervals of its two sons may not be continuous. If you want to add the maximum sub segments and intervals of the two sons, you must make the maximum sub segments and intervals of the left son to the right and the maximum sub segments and intervals of the right son to the left. For example, \ (\ {- 1,1 \} \) and \ (\ {1, - 1 \} \) can use interval addition, The maximum sub segment sum of \ (\ {- 1,1,1, - 1 \} \) is \ (1 + 1 = 2 \).
Therefore, we need to maintain the interval and \ (pre \), the maximum sub segment and \ (ans \), the maximum sub segment and \ (ml \) that must be left, and the maximum sub segment and \ (mr \) that must be right.
The interval sum is relatively simple. You only need to add up the left son and the right son, so you can get:
\(pre_i=pre_{2i}+pre_{2i+1}\)
The largest sub segment that must be left and can be transferred from two states. The first is \ (ML {2I} \), which means that only the left part of the left son is selected, the second is \ (pre {2I} + ml {2I + 1} \), which means that all the left sons are selected, and the right son takes the largest part to the left, so you can get:
\(ml_i=\max(ml_{2i},pre_{2i}+ml_{2i+1})\)
The largest sub segment that must be on the right is the same as:
\(mr_i=\max(mr_{2i+1},pre_{2i+1}+mr_{2i})\)
The maximum sub segment sum is transferred from three states. The first is \ (ANS {2I} \), indicating that only the optimal part of the left son is selected, the second is \ (ANS {2I + 1} \), indicating that only the optimal part of the right son is selected, and the third is \ (MR {2I} + ml {2I + 1} \), indicating that the optimal right part of the left son is taken, plus the optimal left part of the right son, so:
\(ans_i=\max(ans_{2i},ans_{2i+1},mr_{2i}+ml_{2i+1})\)
So the problem was finished.
code
#include<bits/stdc++.h> #define rep(i, a, b) for(int i = a; i <= b; i++) #define il inline using namespace std; int n, m; int a[500005]; int opt, l, r, x, k; #define lc (k << 1) #define rc ((k << 1) | 1) struct tree { int l, r; int pre, ml, mr, ans; }t[2000005]; il void pushup (int k) { t[k].pre = t[lc].pre + t[rc].pre; t[k].ml = max(t[lc].ml, t[lc].pre + t[rc].ml); t[k].mr = max(t[rc].mr, t[rc].pre + t[lc].mr); t[k].ans = max(max(t[lc].ans, t[rc].ans), t[lc].mr + t[rc].ml); return; } il void build (int k, int l, int r) { t[k].l = l, t[k].r = r; if (l == r) { t[k].pre = a[l]; t[k].ml = a[l]; t[k].mr = a[l]; t[k].ans = a[l]; return; } int mid = (l + r) >> 1; build(lc, l, mid); build(rc, mid + 1, r); pushup(k); } il void add (int k, int x, int pre) { if (t[k].l == t[k].r) { t[k].ml = pre; t[k].mr = pre; t[k].pre = pre; t[k].ans = pre; return; } int mid = (t[k].l + t[k].r) >> 1; if (x <= mid) { add(lc, x, pre); } else { add(rc, x, pre); } pushup(k); return; } tree ask (int k, int l, int r) { if (l <= t[k].l && r >= t[k].r) { return t[k]; } int mid = (t[k].l + t[k].r) >> 1; if (r <= mid) { return ask(lc, l, r); } if (l > mid) { return ask(rc, l, r); } tree ls = ask(lc, l, r), rs = ask(rc, l, r), res; res.ml = max(ls.ml, ls.pre + rs.ml); res.mr = max(rs.mr, rs.pre + ls.mr); res.pre = ls.pre + rs.pre; res.ans = max(max(ls.ans, rs.ans), ls.mr + rs.ml); return res; } int main () { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; rep (i, 1, n) { cin >> a[i]; } build(1, 1, n); rep (i, 1, m) { cin >> opt; if (opt == 1) { cin >> l >> r; if (l > r) { swap(l, r); } cout << ask(1, l, r).ans << endl; } if (opt == 2) { cin >> x >> k; add(1, x, k); } } return 0; }
|
https://programmer.group/logu-p4513-segment-tree-maintenance-dynamic-interval-maximum-sub-segment-sum.html
|
CC-MAIN-2022-27
|
refinedweb
| 1,005
| 67.38
|
Red Hat Bugzilla – Bug 157744
rederer import not found
Last modified: 2008-01-23 13:14:55 EST
Description of problem:
I just did a fresh install of FC4T3 and when I invoke system-config-lvm from the
menu nothing happens. Invoking it from the command line yields a traceback with
the following message
Traceback (most recent call last):
File "/usr/sbin/system-config-lvm", line 48, in ?
from renderer import volume_renderer
ImportError: No module named renderer
Version-Release number of selected component (if applicable):
system-config-lvm-0.9.25-1.0
How reproducible:
always
Steps to Reproduce:
1.install fresh system
2.infoke system-config-lvm
3.
Actual results:
traceback
Expected results:
lvm wizard
Additional info:
The file is definitely in the distribution, where it is supposed to be. I have
checked this 6 ways from Sunday!
Well, I played around with this some more.
First of all I remove system-config-lvm and removed
/usr/share/system-config-lvm. I then reinstalled the rpm. Here is what I found
* Invoking this from the Desktom->System Setting->Logical Volume Management
doesn't bring up this tool. The little time icon runs for a while and then it
disappears.
* invoking "system-config-lvm" from the command line results in the renderer not
found message coming up.
* invoking "sudo system-config-lvm" (ie as root) brings the tool up and it seems
to work.
* invoking "system-config-lvm" after running it previously as root will result
in a message "Please restart /usr/sbin/system-config-lvm with root permissions"
* Using the menu to invoke the tool still doesn't work.
Some observations: in other tools the python files *.py are read-execute by
group and others. In system-config-lvm, they are not. When I invoke the tool
as root the *.pyc files get created as read by everyone.
I couldn't figure out why invoking it from the menu doesn't bring up the login
as root prompt that all the other tools provide.
Remember I am using a fresh install of FC4T3 so this is the state of lvm as it
came from rawhide.
Ok I found out what is wrong. The entry in
/usr/share/applications/system-config-lvm.desktop lists the exec path as
/usr/sbin/system-config-lvm instead of /usr/bin/system-config-lvm.
ah - sorry to doubt you! Fixed in 0.9.30-1.0
Fixed in 0.9.30-1.0
QA_READY has been deprecated in favor of ON_QA. Please use ON_QA in the future.
Moving to ON_QA..
|
https://bugzilla.redhat.com/show_bug.cgi?id=157744
|
CC-MAIN-2017-17
|
refinedweb
| 426
| 60.11
|
.
Introduction.
Installing Flask
If you have it installed, it should output the version, as shown in figure 1.
Figure 1 – Checking pip version.
Assuming that you already have pip, to install the Flask module simply send the following pip command on the command line:
pip install flask
After the installation finishes, you should be able to import Flask on Python programs.
The code
The first thing we need to do is importing the Flask class from the flask module we have just installed. You can read more about this class in the module documentation.
from flask import Flask
Next we will create an instance of the Flask class, which we will call app. As argument, the constructor receives the name of the package or module of our application. You can read more about the importance of this parameter in the documentation, on the “About the First Parameter” section.
In our case, since our application is very simple, this parameter doesn’t have impact. Thus, we can pass as argument the value __name__, which is a global variable that holds the current module’s name as a string [1].
app = Flask(__name__)
Next, we need to define a route for our server. A route is a decorator that allows us to bind a URL to a Python function. When a request is made to that route, then the function is executed.
Python decorators are a more advanced concept that we don’t need to worry about for this tutorial. You can read more about them here.
Note that we can declare multiple routes for a server. In our case, since this is an introductory tutorial, we will just use one, called “/hello”.
Routes are a very important concept when developing Flask applications and there are many configurations we can leverage, such as specifying the HTTP methods allowed on a specific route, amongst many other options.
Right after the decorator, we need to declare our function. It will take no arguments and we will call it helloWorldHandler. Nonetheless, you can name it differently if you want.
@app.route('/hello') def helloWorldHandler(): #function code
The implementation of the function will simply consist on returning a “Hello World” message. This message will be returned to clients who make HTTP requests on the “/hello” route of the Flask server.
@app.route('/hello') def helloWorldHandler(): return 'Hello World from Flask running on the PI!'
So far we have jst configured the server route, but the server is still not running. In order for the server to start listening to HTTP incoming requests, we need to call the run method on the Flask object we have instantiated in the beginning of the code.
As arguments of this method, we can specify both the host and the port where the server will be listening to requests. The method arguments are called host and port, respectively.
As host, we will pass the loopback address, which is the 127.0.0.1 IP. This means that the server will only be available locally in our machine. The host is passed as a string.
As port, we will use 8090. This argument is passed as an int.
app.run(host='127.0.0.1', port= 8090)
The final source code can be seen below.
from flask import Flask app = Flask(__name__) @app.route('/hello') def helloWorldHandler(): return 'Hello World from Flask running on the PI!' app.run(host='127.0.0.1', port= 8090)
Testing the code
To test the code, run it on your Python environment of choice. If you are using IDLE, you can check this previous post on how to run Python scripts.
Once you run the code, you should get an output similar to figure 2. Note that the debugging messages indicates that the server is listening on the 127.0.0.1 IP, on port 8090. This is precisely as we have configured on our code.
Figure 2 – Running the code on the Raspberry Pi.
As mentioned before, the server is only working locally on the same machine that is running the server. So, our testing client can only reach the server if it is also running on the Raspberry Pi.
The easiest way to test the server without the need to write code for a client is by using a web browser to make a HTTP GET request on the route we have defined.
So, open a web browser of your choice on the Raspberry Pi and type the following on the address bar:
You can check the expected result on figure 3. As can be seen, you should get the “Hello World” message we have defined in the code.
Figure 3 – Making a request to the Flask server using Chromium.
Related Posts
- Raspberry Pi 3 Raspbian: Running Python scripts on IDLE
- Raspberry Pi 3 Raspbian: Running Python from the command line
- Raspberry Pi 3 Raspbian: Python Hello World with IDLE
- Flask: Hello World
- Flask: Controlling HTTP methods allowed
- Flask: Basic authentication
- Flask: Parsing JSON data
- Python anywhere: Deploying a Flask server on the cloud
- ESP8266: Posting JSON data to a Flask server on the cloud
- LinkIt Smart Duo: Running a Flask server
References
[1]
4 Replies to “Raspberry Pi 3 Raspbian: Running a Flask server”
|
https://techtutorialsx.com/2018/04/25/raspberry-pi-3-raspbian-running-a-flask-server/
|
CC-MAIN-2019-43
|
refinedweb
| 871
| 71.34
|
Life is definitely digital. The genetic code of all living organisms are represented by a long sequence of simple molecules called nucleotides, or bases, which makes up the Deoxyribonucleic acid, better known as DNA. There are only four such nucleotides, and the entire genetic code of a human can be seen as a simple, though 3 billion long, string of the letters A, C, G, and T. Analyzing DNA data to gain increased biological understanding is much about searching in (long) strings for certain string patterns involving the letters A, C, G, and T. This is an integral part of bioinformatics, a scientific discipline addressing the use of computers to search for, explore, and use information about genes, nucleic acids, and proteins.
The instructions to the computer how the analysis is going to be performed are specified using the Python programming language. The forthcoming examples are simple illustrations of the type of problem settings and corresponding Python implementations that are encountered in bioinformatics. However, the leading Python software for bioinformatics applications is BioPython and for real-world problem solving one should rather utilize BioPython instead of home-made solutions. The aim of the sections below is to illustrate the nature of bioinformatics analysis and introduce what is inside packages like BioPython.
We shall start with some very simple examples on DNA analysis that bring together basic building blocks in programming: loops, if tests, and functions. As reader you should be somewhat familiar with these building blocks in general and also know about the specific Python syntax.
Given some string dna containing the letters A, C, G, or T, representing the bases that make up DNA, we ask the question: how many times does a certain base occur in the DNA string? For example, if dna is ATGGCATTA and we ask how many times the base A occur in this string, the answer is 3.
A general Python implementation answering this problem can be done in many ways. Several possible solutions are presented below.
The most straightforward solution is to loop over the letters in the string, test if the current letter equals the desired one, and if so, increase a counter. Looping over the letters is obvious if the letters are stored in a list. This is easily done by converting a string to a list:
>>> list('ATGC') ['A', 'T', 'G', 'C']
Our first solution becomes
def count_v1(dna, base): dna = list(dna) # convert string to list of letters i = 0 # counter for c in dna: if c == base: i += 1 return i
Python allows us to iterate directly over a string without converting it to a list:
>>> for c in 'ATGC': ... print c A T G C
In fact, all built-in objects in Python that contain a set of elements in a particular sequence allow a for loop construction of the type for element in object.
A slight improvement of our solution is therefore to iterate directly over the string:
def count_v2(dna, base): i = 0 # counter for c in dna: if c == base: i += 1 return i dna = 'ATGCGGACCTAT' base = 'C' n = count_v2(dna, base) # printf-style formatting print '%s appears %d times in %s' % (base, n, dna) # or (new) format string syntax print '{base} appears {n} times in {dna}'.format( base=base, n=n, dna=dna)
We have here illustrated two alternative ways of writing out text where the value of variables are to be inserted in “slots” in the string.
It is fundamental for correct programming to understand how to simulate a program by hand, statement by statement. Three tools are effective for helping you reach the required understanding of performing a simulation by hand:
Inserting print statements and examining the variables is the simplest approach to investigating what is going on:
def count_v2_demo(dna, base): print 'dna:', dna print 'base:', base i = 0 # counter for c in dna: print 'c:', c if c == base: print 'True if test' i += 1 return i n = count_v2_demo('ATGCGGACCTAT', 'C')
An efficient way to explore this program is to run it in a debugger where we can step through each statement and see what is printed out. Start ipython in a terminal window and run the program count_v2_demo.py with a debugger: run -d count_v2_demo.py. Use s (for step) to step through each statement, or n (for next) for proceeding to the next statement without stepping through a function that is called.
ipdb> s > /some/disk/user/bioinf/src/count_v2_demo.py(2)count_v2_demo() 1 1 def count_v1_demo(dna, base): ----> 2 print 'dna:', dna 3 print 'base:', base ipdb> s dna: ATGCGGACCTAT > /some/disk/user/bioinf/src/count_v2_demo.py(3)count_v2_demo() 2 print 'dna:', dna ----> 3 print 'base:', base 4 i = 0 # counter
Observe the output of the print statements. One can also print a variable explicitly inside the debugger:
ipdb> print base C
The Online Python Tutor is, at least for small programs, a splendid alternative to debuggers. Go to the web page, erase the sample code and paste in your own code. Press Visual execution, then Forward to execute statements one by one. The status of variables are explained to the right, and the text field below the program shows the output from print statements. An example is shown in Figure Visual execution of a program using the Online Python Tutor.
Misunderstanding of the program flow is one of the most frequent sources of programming errors, so whenever in doubt about any program flow, use one of the three mentioned techniques to establish confidence!
Although it is natural in Python to iterate over the letters in a string (or more generally over elements in a sequence), programmers with experience from other languages (Fortran, C and Java are examples) are used to for loops with an integer counter running over all indices in a string or array:
def count_v3(dna, base): i = 0 # counter for j in range(len(dna)): if dna[j] == base: i += 1 return i
Python indices always start at 0 so the legal indices for our string become 0, 1, ..., len(dna)-1, where len(dna) is the number of letters in the string dna. The range(x) function returns a list of integers 0, 1, ..., x-1, implying that range(len(dna)) generates all the legal indices for dna.
The while loop equivalent to the last function reads
def count_v4(dna, base): i = 0 # counter j = 0 # string index while j < len(dna): if dna[j] == base: i += 1 j += 1 return i
Correct indentation is here crucial: a typical error is to fail indenting the j += 1 line correctly.
The idea now is to create a list m where m[i] is True if dna[i] equals the letter we search for (base). The number of True values in m is then the number of base letters in dna. We can use the sum function to find this number because doing arithmetics with boolean lists automatically interprets True as 1 and False as 0. That is, sum(m) returns the number of True elements in m. A possible function doing this is
def count_v5(dna, base): m = [] # matches for base in dna: m[i]=True if dna[i]==base for c in dna: if c == base: m.append(True) else: m.append(False) return sum(m)
Shorter, more compact code is often a goal if the compactness enhances readability. The four-line if test in the previous function can be condensed to one line using the inline if construction: if condition value1 else value2.
def count_v6(dna, base): m = [] # matches for base in dna: m[i]=True if dna[i]==base for c in dna: m.append(True if c == base else False) return sum(m)
The inline if test is in fact redundant in the previous function because the value of the condition c == base can be used directly: it has the value True or False. This saves some typing and adds clarity, at least to Python programmers with some experience:
def count_v7(dna, base): m = [] # matches for base in dna: m[i]=True if dna[i]==base for c in dna: m.append(c == base) return sum(m)
Building a list with the aid of a for loop can often be condensed to a single line by using list comprehensions: [expr for e in sequence], where expr is some expression normally involving the iteration variable e. In our last example, we can introduce a list comprehension
def count_v8(dna, base): m = [c == base for c in dna] return sum(m)
Here it is tempting to get rid of the m variable and reduce the function body to a single line:
def count_v9(dna, base): return sum([c == base for c in dna])
The DNA string is usually huge - 3 billion letters for the human species. Making a boolean array with True and False values therefore increases the memory usage by a factor of two in our sample functions count_v5 to count_v9. Summing without actually storing an extra list is desirable. Fortunately, sum([x for x in s]) can be replaced by sum(x for x in s), where the latter sums the elements in s as x visits the elements of s one by one. Removing the brackets therefore avoids first making a list before applying sum to that list. This is a minor modification of the count_v9 function:
def count_v10(dna, base): return sum(c == base for c in dna)
Below we shall measure the impact of the various program constructs on the CPU time.
Instead of making a boolean list with elements expressing whether a letter matches the given base or not, we may collect all the indices of the matches. This can be done by adding an if test to the list comprehension:
def count_v11(dna, base): return len([i for i in range(len(dna)) if dna[i] == base])
The Online Python Tutor is really helpful to reach an understanding of this compact code. Alternatively, you may play with the constructions in an interactive Python shell:
>>>>>>> indices = [i for i in range(len(dna)) if dna[i] == base] >>> indices [0, 1, 7] >>> print dna[0], dna[1], dna[7] # check A A A
Observe that the element i in the list comprehension is only made for those i where dna[i] == base.
Very often when you set out to do a task in Python, there is already functionality for the task in the object itself, in the Python libraries, or in third-party libraries found on the Internet. Counting how many times a letter (or substring) base appears in a string dna is obviously a very common task so Python supports it by the syntax dna.count(base):
def count_v12(dna, base): return dna.count(base) def compare_efficiency():
Now we have 11 different versions of how to count the occurrences of a letter in a string. Which one of these implementations is the fastest? To answer the question we need some test data, which should be a huge string dna.
The simplest way of generating a long string is to repeat a character a large number of times:
N = 1000000 dna = 'A'*N
The resulting string is just 'AAA...A, of length N, which is fine for testing the efficiency of Python functions. Nevertheless, it is more exciting to work with a DNA string with letters from the whole alphabet A, C, G, and T. To make a DNA string with a random composition of the letters we can first make a list of random letters and then join all those letters to a string:
import random alphabet = list('ATGC') dna = [random.choice(alphabet) for i in range(N)] dna = ''.join(dna) # join the list elements to a string
The random.choice(x) function selects an element in the list x at random.
Note that N is very often a large number. In Python version 2.x, range(N) generates a list of N integers. We can avoid the list by using xrange which generates an integer at a time and not the whole list. In Python version 3.x, the range function is actually the xrange function in version 2.x. Using xrange, combining the statements, and wrapping the construction of a random DNA string in a function, gives
import random def generate_string(N, alphabet='ACGT'): return ''.join([random.choice(alphabet) for i in xrange(N)]) dna = generate_string(600000)
The call generate_string(10) may generate something like AATGGCAGAA.
Our next goal is to see how much time the various count_v* functions spend on counting letters in a huge string, which is to be generated as shown above. Measuring the time spent in a program can be done by the time module:
import time ... t0 = time.clock() # do stuff t1 = time.clock() cpu_time = t1 - t0
The time.clock() function returns the CPU time spent in the program since its start. If the interest is in the total time, also including reading and writing files, time.time() is the appropriate function to call.
Running through all our functions made so far and recording timings can be done by
import time functions = [count_v1, count_v2, count_v3, count_v4, count_v5, count_v6, count_v7, count_v8, count_v9, count_v10, count_v11, count_v12] timings = [] # timings[i] holds CPU time for functions[i] for function in functions: t0 = time.clock() function(dna, 'A') t1 = time.clock() cpu_time = t1 - t0 timings.append(cpu_time)
In Python, functions are ordinary objects so making a list of functions is no more special than making a list of strings or numbers.
We can now iterate over timings and functions simultaneously via zip to make a nice printout of the results:
for cpu_time, function in zip(timings, functions): print '{f:<9s}: {cpu:.2f} s'.format( f=function.func_name, cpu=cpu_time)
Timings on a MacBook Air 11 running Ubuntu show that the functions using list.append require almost the double of the time of the functions that work with list comprehensions. Even faster is the simple iteration over the string. However, the built-in count functionality of strings (dna.count(base)) runs over 30 times faster than the best of our handwritten Python functions! The reason is that the for loop needed to count in dna.count(base) is actually implemented in C and runs very much faster than loops in Python.
A clear lesson learned is: google around before you start out to implement what seems to be a quite common task. Others have probably already done it for you, and most likely is their solution much better than what you can (easily) come up with.
We end this section with showing how to make tests that verify our 12 counting functions. To this end, we make a new function that first computes a certainly correct answer to a counting problem and then calls all the count_* functions, stored in the list functions, to check that each call has the correct result:
def test_count_all(): dna = 'ATTTGCGGTCCAAA' exact = dna.count('A') for f in functions: if f(dna, 'A') != exact: print f.__name__, 'failed'
Here, we believe in dna.count('A') as the correct answer.
We might take this test function one step further and adopt the conventions in the pytest and nose testing frameworks for Python code.
These conventions say that the test function should
- have a name starting with test_;
- have no arguments;
- let a boolean variable, say success, be True if a test passes and be False if the test fails;
- create a message about what failed, stored in some string, say msg;
- use the construction assert success, msg, which will abort the program and write out the error message msg if success is False.
The pytest and nose test frameworks can search for all Python files in a folder tree, run all test_*() functions, and report how many of the tests that failed, if we adopt the conventions above. Our revised test function becomes
def test_count_all(): dna = 'ATTTGCGGTCCAAA' expected = dna.count('A') functions = [count_v1, count_v2, count_v3, count_v4, count_v5, count_v6, count_v7, count_v8, count_v9, count_v10, count_v11, count_v12] for f in functions: success = f(dna, 'A') == expected msg = '%s failed' % f.__name__ assert success, msg
It is worth notifying that the name of a function f, as a string object, is given by f.__name__, and we make use of this information to construct an informative message in case a test fails.
It is a good habit to write such test functions since the execution of all tests in all files can be fully automated. Every time you to a change in some file you can with minimum effort rerun all tests.
The entire suite of functions presented above, including the timings and tests, can be found in the file count.py.
Your genetic code is essentially the same from you are born until you die, and the same in your blood and your brain. Which genes that are turned on and off make the difference between the cells. This regulation of genes is orchestrated by an immensely complex mechanism, which we have only started to understand. A central part of this mechanism consists of molecules called transcription factors that float around in the cell and attach to DNA, and in doing so turn nearby genes on or off. These molecules bind preferentially to specific DNA sequences, and this binding preference pattern can be represented by a table of frequencies of given symbols at each position of the pattern. More precisely, each row in the table corresponds to the bases A, C, G, and T, while column j reflects how many times the base appears in position j in the DNA sequence.
For example, if our set of DNA sequences are TAG, GGT, and GGG, the table becomes
From this table we can read that base A appears once in index 1 in the DNA strings, base C does not appear at all, base G appears twice in all positions, and base T appears once in the beginning and end of the strings.
In the following we shall present different data structures to hold such a table and different ways of computing them. The table is known as a frequency matrix in bioinformatics and this is the term used here too.
Since we know that there are only four rows in the frequency matrix, an obvious data structure would be four lists, each holding a row. A function computing these lists may look like
We need to initialize the lists with the right length and a zero for each element, since each list element is to be used as a counter. Creating a list of length n with object x in all positions is done by [x]*n. Finding the proper length is here carried out by inspecting the length of the first element in dna_list, the list of all DNA strings to be counted, assuming that all elements in this list have the same length.
In the for loop we apply the enumerate function, which is used to extract both the element value and the element index when iterating over a sequence. For example,
>>> for index, base in enumerate(['t', 'e', 's', 't']): ... print index, base ... 0 t 1 e 2 s 3 t
Here is a test,
dna_list = ['GGTAG', 'GGTAC', 'GGTGC'] A, C, G, T = freq_lists(dna_list) print A print C print G print T
with output
[0, 0, 0, 2, 0] [0, 0, 0, 0, 2] [3, 3, 0, 1, 1] [0, 0, 3, 0, 0]
The frequency matrix can also be represented as a nested list M such that M[i][j] is the frequency of base i in position j in the set of DNA strings. Here i is an integer, where 0 corresponds to A, 1 to T, 2 to G, and 3 to C. The frequency is the number of times base i appears in position j in a set of DNA strings. Sometimes this number is divided by the number of DNA strings in the set so that the frequency is between 0 and 1. Note that all the DNA strings must have the same length.
The simplest way to make a nested list is to insert the A, C, G, and T lists into another list:
>>> frequency_matrix = [A, C, G, T] >>> frequency_matrix[2][3] 2 >>> G[3] # same element 2
Alternatively, we can illustrate how to compute this type of nested list directly:
def freq_list_of_lists_v1(dna_list): # Create empty frequency_matrix[i][j] = 0 # i=0,1,2,3 corresponds to A,T,G,C # j=0,...,length of dna_list[0] frequency_matrix = [[0 for v in dna_list[0]] for x in 'ACGT'] for dna in dna_list: for index, base in enumerate(dna): if base == 'A': frequency_matrix[0][index] +=1 elif base == 'C': frequency_matrix[1][index] +=1 elif base == 'G': frequency_matrix[2][index] +=1 elif base == 'T': frequency_matrix[3][index] +=1 return frequency_matrix
As in the case with individual lists we need to initialize all elements in the nested list to zero.
A call and printout,
dna_list = ['GGTAG', 'GGTAC', 'GGTGC'] frequency_matrix = freq_list_of_lists_v1(dna_list) print frequency_matrix
results in
[[0, 0, 0, 2, 0], [0, 0, 0, 0, 2], [3, 3, 0, 1, 1], [0, 0, 3, 0, 0]]
The series of if tests in the Python function freq_list_of_lists_v1 are somewhat cumbersome, especially if we want to extend the code to other bioinformatics problems where the alphabet is larger. What we want is a mapping from base, which is a character, to the corresponding index 0, 1, 2, or 3. A Python dictionary may represent such mappings:
>>> base2index = {'A': 0, 'C': 1, 'G': 2, 'T': 3} >>> base2index['G'] 2
With the base2index dictionary we do not need the series of if tests and the alphabet 'ATGC' could be much larger without affecting the length of the code:
def freq_list_of_lists_v2(dna_list): frequency_matrix = [[0 for v in dna_list[0]] for x in 'ACGT'] base2index = {'A': 0, 'C': 1, 'G': 2, 'T': 3} for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base2index[base]][index] += 1 return frequency_matrix
As long as each sublist in a list of lists has the same length, a list of lists can be replaced by a Numerical Python (numpy) array. Processing of such arrays is often much more efficient than processing of the nested list data structure. To initialize a two-dimensional numpy array we need to know its size, here 4 times len(dna_list[0]). Only the first line in the function freq_list_of_lists_v2 needs to be changed in order to utilize a numpy array:
import numpy as np def freq_numpy(dna_list): frequency_matrix = np.zeros((4, len(dna_list[0])), dtype=np.int) base2index = {'A': 0, 'C': 1, 'G': 2, 'T': 3} for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base2index[base]][index] += 1 return frequency_matrix
The resulting frequency_matrix object can be indexed as [b][i] or [b,i], with integers b and i. Typically, b will be something line base2index['C'].
Instead of going from a character to an integer index via base2index, we may prefer to index frequency_matrix by the base name and the position index directly, like in ['C'][14]. This is the most natural syntax for a user of the frequency matrix. The relevant Python data structure is then a dictionary of lists. That is, frequency_matrix is a dictionary with keys 'A', 'C', 'G', and 'T'. The value for each key is a list. Let us now also extend the flexibility such that dna_list can have DNA strings of different lengths. The lists in frequency_list will have lengths equal to the longest DNA string. A relevant function is
def freq_dict_of_lists_v1(dna_list): n = max([len(dna) for dna in dna_list]) frequency_matrix = { 'A': [0]*n, 'C': [0]*n, 'G': [0]*n, 'T': [0]*n, } for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base][index] += 1 return frequency_matrix
Running the test code
frequency_matrix = freq_dict_of_lists_v1(dna_list) import pprint # for nice printout of nested data structures pprint.pprint(frequency_matrix)
results in the output
{'A': [0, 0, 0, 2, 0], 'C': [0, 0, 0, 0, 2], 'G': [3, 3, 0, 1, 1], 'T': [0, 0, 3, 0, 0]}
The initialization of frequency_matrix in the above code can be made more compact by using a dictionary comprehension:
dict = {key: value for key in some_sequence}
In our example we set
frequency_matrix = {base: [0]*n for base in 'ACGT'}
Adopting this construction in the freq_dict_of_lists_v1 function leads to a slightly more compact version:
def freq_dict_of_lists_v2(dna_list): n = max([len(dna) for dna in dna_list]) frequency_matrix = {base: [0]*n for base in 'ACGT'} for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base][index] += 1 return frequency_matrix
As an additional comment on computing the maximum length of the DNA strings can be made as there are several alternative ways of doing this. The classical use of max is to apply it to a list as done above:
n = max([len(dna) for dna in dna_list])
However, for very long lists it is possible to avoid the memory demands of storing the result of the list comprehension, i.e., the list of lengths. Instead max can work with the lengths as they are computed:
n = max(len(dna) for dna in dna_list)
It is also possible to write
n = max(dna_list, key=len)
Here, len is applied to each element in dna_list, and the maximum of the resulting values is returned.
The dictionary of lists data structure can alternatively be replaced by a dictionary of dictionaries object, often just called a dict of dicts object. That is, frequency_matrix[base] is a dictionary with key i and value equal to the added number of occurrences of base in dna[i] for all dna strings in the list dna_list. The indexing frequency_matrix['C'][i] and the values are exactly as in the last example; the only difference is whether frequency_matrix['C'] is a list or dictionary.
Our function working with frequency_matrix as a dict of dicts is written as
def freq_dict_of_dicts_v1(dna_list): n = max([len(dna) for dna in dna_list]) frequency_matrix = {base: {index: 0 for index in range(n)} for base in 'ACGT'} for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base][index] += 1 return frequency_matrix
The manual initialization of each subdictionary to zero,
frequency_matrix = {base: {index: 0 for index in range(n)} for base in 'ACGT'}
can be simplified by using a dictionary with default values for any key. The construction defaultdict(lambda: obj) makes a dictionary with obj as default value. This construction simplifies the previous function a bit:
from collections import defaultdict def freq_dict_of_dicts_v2(dna_list): n = max([len(dna) for dna in dna_list]) frequency_matrix = {base: defaultdict(lambda: 0) for base in 'ACGT'} for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base][index] += 1 return frequency_matrix
Remark. Dictionary comprehensions were new in Python 2.7 and 3.1, but can be simulated in earlier versions by making (key, value) tuples via list comprehensions. A dictionary comprehension
d = {key: value for key in sequence}
is then constructed as
d = dict([(key, value) for key in sequence])
The frequency_matrix dict of lists for can easily be changed to a dict of numpy arrays: just replace the initialization [0]*n by np.zeros(n, dtype=np.int). The indexing remains the same:
def freq_dict_of_arrays_v1(dna_list): n = max([len(dna) for dna in dna_list]) frequency_matrix = {base: np.zeros(n, dtype=np.int) for base in 'ACGT'} for dna in dna_list: for index, base in enumerate(dna): frequency_matrix[base][index] += 1 return frequency_matrix
Having frequency_matrix[base] as a numpy array instead of a list does not give any immediate advantage, as the storage and CPU time is about the same. The loop over the dna string and the associated indexing is what consumes all the CPU time. However, the numpy arrays provide a potential for increasing efficiency through vectorization, i.e., replacing the element-wise operations on dna and frequency_matrix[base] by operations on the entire arrays at once.
Let us use the interactive Python shell to explore the possibilities of vectorization. We first convert the string to a numpy array of characters:
>>>>> dna = np.array(dna, dtype='c') >>> dna array(['A', 'C', 'A', 'T'], dtype='|S1')
For a given base, say A, we can in one vectorized operation find which locations in dna that contain A:
>>> b = dna == 'A' >>> b array([ True, False, True, False], dtype=bool)
By converting b to an integer array i we can update the frequency counts for all indices by adding i to frequency_matrix['A']:
>>> i = np.asarray(b, dtype=np.int) >>> i array([1, 0, 1, 0]) >>> frequency_matrix['A'] = frequency_matrix['A'] + i
This recipe can be repeated for all bases:
for dna in dna_list: dna = np.array(dna, dtype='c') for base in 'ACGT': b = dna == base i = np.asarray(b, dtype=np.int) frequency_matrix[base] = frequency_matrix[base] + i
It turns out that we do not need to convert the boolean array b to an integer array i, because doing arithmetics with b directly is possible: False is interpreted as 0 and True as 1 in arithmetic operations. We can also use the += operator to update all elements of frequency_matrix[base] directly, without first computing the sum of two arrays frequency_matrix[base] + i and then assigning this result to frequency_matrix[base]. Collecting all these ideas in one function yields the code
def freq_dict_of_arrays_v2(dna_list): n = max([len(dna) for dna in dna_list]) frequency_matrix = {base: np.zeros(n, dtype=np.int) for base in 'ACGT'} for dna in dna_list: dna = np.array(dna, dtype='c') for base in 'ACCT': frequency_matrix[base] += dna == base return frequency_matrix
This vectorized function runs almost 10 times as fast as the (scalar) counterpart freq_list_of_arrays_v1!
Having built a frequency matrix out of a collection of DNA strings, it is time to use it for analysis. The short DNA strings that a frequency matrix is built out of, is typically a set of substrings of a larger DNA sequence, which shares some common purpose. An example of this is to have a set of substrings that serves as a kind of anchors/magnets at which given molecules attach to DNA and perform biological functions (like turning genes on or off). With the frequency matrix constructed from a limited set of known anchor locations (substrings), we can now scan for other similar substrings that have the potential to perform the same function. The simplest way to do this is to first determine the most typical substring according to the frequency matrix, i.e., the substring having the most frequent nucleotide at each position. This is referred to as the consensus string of the frequency matrix. We can then look for occurrences of the consensus substring in a larger DNA sequence, and consider these occurrences as likely candidates for serving the same function (e.g., as anchor locations for molecules).
For instance, given three substrings ACT, CCA and AGA, the frequency matrix would be (list of lists, with rows corresponding to A, C, G, and T):
[[2, 0, 2] [1, 2, 0] [0, 1, 0] [0, 0, 1]]
We see that for position 0, which corresponds to the left-most column in the table, the symbol A has the highest frequency (2). The maximum frequencies for the other positions are seen to be C for position 1, and A for position 2. The consensus string is therefore ACA. Note that the consensus string does not need to be equal to any of the substrings that formed the basis of the frequency matrix (this is indeed the case for the above example).
Let frequency_matrix be a list of lists. For each position i we run through the rows in the frequency matrix and keep track of the maximum frequency value and the corresponding letter. If two or more letters have the same frequency value we use a dash to indicate that this position in the consensus string is undetermined.
The following function computes the consensus string:
def find_consensus_v1(frequency_matrix): base2index = {'A': 0, 'C': 1, 'G': 2, 'T': 3} consensus = '' dna_length = len(frequency_matrix[0]) for i in range(dna_length): # loop over positions in string max_freq = -1 # holds the max freq. for this i max_freq_base = None # holds the corresponding base for base in 'ATGC': if frequency_matrix[base2index[base]][i] > max_freq: max_freq = frequency_matrix[base2index[base]][i] max_freq_base = base elif frequency_matrix[base2index[base]][i] == max_freq: max_freq_base = '-' # more than one base as max consensus += max_freq_base # add new base with max freq return consensus
Since this code requires frequency_matrix to be a list of lists we should insert a test and raise an exception if the type is wrong:
def find_consensus_v1(frequency_matrix): if isinstance(frequency_matrix, list) and \ isinstance(frequency_matrix[0], list): pass # right type else: raise TypeError('frequency_matrix must be list of lists') ...
How must the find_consensus_v1 function be altered if frequency_matrix is a dict of dicts?
- The base2index dict is no longer needed.
- Access of sublist, frequency_matrix[0], to test for type and length of the strings, must be replaced by frequency_matrix['A'].
The updated function becomes
def find_consensus_v3(frequency_matrix): if isinstance(frequency_matrix, dict) and \ isinstance(frequency_matrix['A'], dict): pass # right type else: raise TypeError('frequency_matrix must be dict of dicts') consensus = '' dna_length = len(frequency_matrix['A']) for i in range(dna_length): # loop over positions in string max_freq = -1 # holds the max freq. for this i max_freq_base = None # holds the corresponding base for base in 'ACGT': if frequency_matrix[base][i] > max_freq: max_freq = frequency_matrix[base][i] max_freq_base = base elif frequency_matrix[base][i] == max_freq: max_freq_base = '-' # more than one base as max consensus += max_freq_base # add new base with max freq return consensus
Here is a test:
frequency_matrix = freq_dict_of_dicts_v1(dna_list) pprint.pprint(frequency_matrix) print find_consensus_v3(frequency_matrix)
with output
{'A': {0: 0, 1: 0, 2: 0, 3: 2, 4: 0}, 'C': {0: 0, 1: 0, 2: 0, 3: 0, 4: 2}, 'G': {0: 3, 1: 3, 2: 0, 3: 1, 4: 1}, 'T': {0: 0, 1: 0, 2: 3, 3: 0, 4: 0}} Consensus string: GGTAC
Let us try find_consensus_v3 with the dict of defaultdicts as input (freq_dicts_of_dicts_v2). The code runs fine, but the output string is just G! The reason is that dna_length is 1, and therefore that the length of the A dict in frequency_matrix is 1. Printing out frequency_matrix yields
{'A': defaultdict(X, {3: 2}), 'C': defaultdict(X, {4: 2}), 'G': defaultdict(X, {0: 3, 1: 3, 3: 1, 4: 1}), 'T': defaultdict(X, {2: 3})}
where our X is a short form for text like
`<function <lambda> at 0xfaede8>`
We see that the length of a defaultdict will only count the nonzero entries. Hence, to use a defaultdict our function must get the length of the DNA string to build as an extra argument:
def find_consensus_v4(frequency_matrix, dna_length): ...
Exercise 3: Allow different types for a function argument suggests to make a unified find_consensus function which works with all of the different representations of frequency_matrix that we have used.
The functions making and using the frequency matrix are found in the file freq.py.
Dot plots are commonly used to visualize the similarity between two protein or nucleic acid sequences. They compare two sequences, say d1 and d2, by organizing d1 along the x-axis and d2 along the y-axis of a plot. When d1[i] == d2[j] we mark this by drawing a dot at location i,j in the plot. An example is
The origin is in the upper left corner, which means that the first string has its indices running to the right 0, 1, 2, and so forth, while the second string has its indices running down, row by row.
In the forthcoming examples, a dot is represented by 1. No presence at a given location is represented by 0. A dot plot can be manually read to find common patterns between two sequences that has undergone several insertions and deletions, and it serves as a conceptual basis for algorithms that align two sequences in order to find evolutionary origin or shared functional parts. Such alignment of biological sequences is a particular variant of finding the edit distance between strings, which is a general technique, also used for, e.g., spell correction in search engines.
The dot plot data structure must mimic a table. The “x” direction is along rows, while the “y” direction is along columns. First we need to initialize the whole data structure with zeros. Then, for each for each position in the “x string” we run through all positions in the “y string” and mark those where the characters match with 1. The algorithm will be clear when presented with specific Python code.
Since the plot is essentially a table, a list of lists is therefore a natural data structure. The following function creates the list of lists:
def dotplot_list_of_lists(dna_x, dna_y): dotplot_matrix = [['0' for x in dna_x] for y in dna_y] for x_index, x_value in enumerate(dna_x): for y_index, y_value in enumerate(dna_y): if x_value == y_value: dotplot_matrix[y_index][x_index] = '1' return dotplot_matrix
To view the dot plot we need to print out the list of lists. Here is a possible way:
dna_x = 'TAATGCCTGAAT' dna_y = 'CTCTATGCC' M = dotplot_list_of_lists(dna_x, dna_x) for row in M: for column in row: print column, print
The output becomes
One can, alternatively, translate the list of lists to a multi-line string containing the whole plot as a string object. This implies joining all the characters in each row and then joining all the rows:
rows = [' '.join(row) for row in dotplot_matrix] plot = '\n'.join(rows) # or combined plot = '\n'.join([' '.join(row) for row in dotplot_matrix])
The construction 'd'.join(l) joints all the string elements of the list l and inserts d as delimiter: 'x'.join(['A','B','C']) becomes 'AxBxC'. We use a space as delimiter among the characters in a row since this gives a nice layout when printing the string. All rows are joined with newline as delimiter such that the rows appear on separate lines when printing the string. To really understand what is going on, a more comprehensive code could be made so that each step can be examined:
def make_string_expanded(dotplot_matrix): rows = [] for row in dotplot_matrix: row_string = ' '.join(row) rows.append(row_string) plot = '\n'.join(rows) return plot M2 = [['1', '1', '0', '1'], ['1', '1', '1', '1'], ['0', '0', '1', '0'], ['0', '0', '0', '1']] s = make_string_expanded(M2)
Unless the join operation as used here is well understood, it is highly recommended to paste the above code into the Online Python Tutor, step through the code, and watch how variables change their content. Figure Illustration of how join operations work (using the Online Python Tutor) shows a snapshot of this type of code investigation.
A Numerical Python array, with integer elements that equal 0 or 1, is well suited as data structure to hold a dot plot.
def dotplot_numpy(dna_x, dna_y): dotplot_matrix = np.zeros((len(dna_y), len(dna_x)), np.int) for x_index, x_value in enumerate(dna_x): for y_index, y_value in enumerate(dna_y): if x_value == y_value: dotplot_matrix[y_index,x_index] = 1 return dotplot_matrix print dotplot_numpy(dna_x, dna_y)
The two dot plot functions are available in the file dotplot.py.
DNA consists of four molecules called nucleotides, or bases, and can be represented as a string of the letters A, C, G, and T. But this does not mean that all four nucleotides need to be similarly frequent. Are some nucleotides more frequent than others, say in yeast, as represented by the first chromosome of yeast? Also, DNA is really not a single thread, but two threads wound together. This wounding is based on an A from one thread binding to a T of the other thread, and C binding to G (that is, A will only bind with T, not with C or G). Could this fact force groups of the four symbol frequencies to be equal? The answer is that the A-T and G-C binding does not in principle force certain frequencies to be equal, but in practice they usually become so because of evolutionary factors related to this pairing.
Our first programming task now is to compute the frequencies of the bases A, C, G, and T. That is, the number of times each base occurs in the DNA string, divided by the length of the string. For example, if the DNA string is ACGGAAA, the length is 7, A appears 4 times with frequency 4/7, C appears once with frequency 1/7, G appears twice with frequency 2/7, and T does not appear so the frequency is 0.
From a coding perspective we may create a function for counting how many times A, C, G, and T appears in the string and then another function for computing the frequencies. In both cases we want dictionaries such that we can index with the character and get the count or the frequency out. Counting is done by
def get_base_counts(dna): counts = {'A': 0, 'T': 0, 'G': 0, 'C': 0} for base in dna: counts[base] += 1 return counts
This function can then be used to compute the base frequencies:
def get_base_frequencies_v1(dna): counts = get_base_counts(dna) return {base: count*1.0/len(dna) for base, count in counts.items()}
Since we learned at the end of the section Efficiency Assessment that dna.count(base) was much faster than the various manual implementations of counting, we can write a faster and simpler function for computing all the base frequencies:
def get_base_frequencies_v2(dna): return {base: dna.count(base)/float(len(dna)) for base in 'ATGC'}
A little test,
dna = 'ACCAGAGT' frequencies = get_base_frequencies_v2(dna) def format_frequencies(frequencies): return ', '.join(['%s: %.2f' % (base, frequencies[base]) for base in frequencies]) print "Base frequencies of sequence '%s':\n%s" % \ (dna, format_frequencies(frequencies))
gives the result
Base frequencies of sequence 'ACCAGAGT': A: 0.38, C: 0.25, T: 0.12, G: 0.25
The format_frequencies function was made for nice printout of the frequencies with 2 decimals. The one-line code is an effective combination of a dictionary, list comprehension, and the join functionality. The latter is used to get a comma correctly inserted between the items in the result. Lazy programmers would probably just do a print frequencies and live with the curly braces in the output and (in general) 16 disturbing decimals.
We can try the frequency computation on real data. The file
contains the DNA for yeast. We can download this file from the Internet by
urllib.urlretrieve(url, filename=name_of_local_file)
where url is the Internet address of the file and name_of_local_file is a string containing the name of the file on the computer where the file is downloaded. To avoid repeated downloads when the program is run multiple times, we insert a test on whether the local file exists or not. The call os.path.isfile(f) returns True if a file with name f exists in the current working folder.
The appropriate download code then becomes
import urllib, os urlbase = '' yeast_file = 'yeast_chr1.txt' if not os.path.isfile(yeast_file): url = urlbase + yeast_file urllib.urlretrieve(url, filename=yeast_file)
A copy of the file on the Internet is now in the current working folder under the name yeast_chr1.txt.
The yeast_chr1.txt files contains the DNA string split over many lines. We therefore need to read the lines in this file, strip each line to remove the trailing newline, and join all the stripped lines to recover the DNA string:
def read_dnafile_v1(filename): lines = open(filename, 'r').readlines() # Remove newlines in each line (line.strip()) and join dna = ''.join([line.strip() for line in lines]) return dna
As usual, an alternative programming solution can be devised:
def read_dnafile_v2(filename): dna = '' for line in open(filename, 'r'): dna += line.strip() return dna dna = read_dnafile_v2(yeast_file) yeast_freq = get_base_frequencies_v2(dna) print "Base frequencies of yeast DNA (length %d):\n%s" % \ (len(dna), format_frequencies(yeast_freq))
The output becomes
Base frequencies of yeast DNA (length 230208): A: 0.30, C: 0.19, T: 0.30, G: 0.20
The varying frequency of different nucleotides in DNA is referred to as nucleotide bias. The nucleotide bias varies between organisms, and have a range of biological implications. For many organisms the nucleotide bias has been highly optimized through evolution and reflects characteristics of the organisms and their environments, for instance the typical temperature the organism is adapted to. The interested reader can, e.g., find more details in this article.
The functions computing base frequencies are available in the file basefreq.py.
An important usage of DNA is for cells to store information on their arsenal of proteins. Briefly, a gene is, in essence, a region of the DNA, consisting of several coding parts (called exons), interspersed by non-coding parts (called introns). The coding parts are concatenated to form a string called mRNA, where also occurrences of the letter T in the coding parts are substituted by a U. A triplet of mRNA letters code for a specific amino acid, which are the building blocks of proteins. Consecutive triplets of letters in mRNA define a specific sequence of amino acids, which amounts to a certain protein.
Here is an example of using the mapping from DNA to proteins to create the Lactase protein (LPH), using the DNA sequence of the Lactase gene (LCT) as underlying code. An important functional property of LPH is in digesting Lactose, which is found most notably in milk. Lack of the functionality of LPH leads to digestive problems referred to as lactose intolerance. Most mammals and humans lose their expression of LCT and therefore their ability to digest milk when they stop receiving breast milk.
The file
contains a mapping of genetic codes to amino acids. The file format looks like
UUU F Phe Phenylalanine UUC F Phe Phenylalanine UUA L Leu Leucine UUG L Leu Leucine CUU L Leu Leucine CUC L Leu Leucine CUA L Leu Leucine CUG L Leu Leucine AUU I Ile Isoleucine AUC I Ile Isoleucine AUA I Ile Isoleucine AUG M Met Methionine (Start)
The first column is the genetic code (triplet in mRNA), while the other columns represent various ways of expressing the corresponding amino acid: a 1-letter symbol, a 3-letter name, and the full name.
Downloading the genetic_code.tsv file can be done by this robust function:
def download(urlbase, filename): if not os.path.isfile(filename): url = urlbase + filename try: urllib.urlretrieve(url, filename=filename) except IOError as e: raise IOError('No Internet connection') # Check if downloaded file is an HTML file, which # is what github.com returns if the URL is not existing f = open(filename, 'r') if 'DOCTYPE html' in f.readline(): raise IOError('URL %s does not exist' % url)
We want to make a dictionary of this file that maps the code (first column) on to the 1-letter name (second column):
def read_genetic_code_v1(filename): infile = open(filename, 'r') genetic_code = {} for line in infile: columns = line.split() genetic_code[columns[0]] = columns[1] return genetic_code
Downloading the file, reading it, and making the dictionary are done by
urlbase = '' genetic_code_file = 'genetic_code.tsv' download(urlbase, genetic_code_file) code = read_genetic_code_v1(genetic_code_file)
Not surprisingly, the read_genetic_code_v1 can be made much shorter by collecting the first two columns as list of 2-lists and then converting the 2-lists to key-value pairs in a dictionary:
def read_genetic_code_v2(filename): return dict([line.split()[0:2] for line in open(filename, 'r')])
Creating a mapping of the code onto all the three variants of the amino acid name is also of interest. For example, we would like to make look ups like ['CUU']['3-letter'] or ['CUU']['amino acid']. This requires a dictionary of dictionaries:
def read_genetic_code_v3(filename): genetic_code = {} for line in open(filename, 'r'): columns = line.split() genetic_code[columns[0]] = {} genetic_code[columns[0]]['1-letter'] = columns[1] genetic_code[columns[0]]['3-letter'] = columns[2] genetic_code[columns[0]]['amino acid'] = columns[3] return genetic_code
An alternative way of writing the last function is
def read_genetic_code_v4(filename): genetic_code = {} for line in open(filename, 'r'): c = line.split() genetic_code[c[0]] = { '1-letter': c[1], '3-letter': c[2], 'amino acid': c[3]} return genetic_code
To form mRNA, we need to grab the exon regions (the coding parts) of the lactase gene. These regions are substrings of the lactase gene DNA string, corresponding to the start and end positions of the exon regions. Then we must replace T by U, and combine all the substrings to build the mRNA string.
Two straightforward subtasks are to load the lactase gene and its exon positions into variables. The file lactase_gene.txt, at the same Internet location as the other files, stores the lactase gene. The file has the same format as yeast_chr1.txt. Using the download function and the previously shown read_dnafile_v1, we can easily load the data in the file into the string lactase_gene.
The exon regions are described in a file lactase_exon.tsv, also found at the same Internet site as the other files. The file is easily transferred to your computer by calling download. The file format is very simple in that each line holds the start and end positions of an exon region:
0 651 3990 4070 7504 7588 13177 13280 15082 15161
We want to have this information available in a list of (start, end) tuples. The following function does the job:
def read_exon_regions_v1(filename): positions = [] infile = open(filename, 'r') for line in infile: start, end = line.split() start, end = int(start), int(end) positions.append((start, end)) infile.close() return positions
Readers favoring compact code will appreciate this alternative version of the function:
def read_exon_regions_v2(filename): return [tuple(int(x) for x in line.split()) for line in open(filename, 'r')] lactase_exon_regions = read_exon_regions_v2(lactase_exon_file)
For simplicity’s sake, we shall consider mRNA as the concatenation of exons, although in reality, additional base pairs are added to each end. Having the lactase gene as a string and the exon regions as a list of (start, end) tuples, it is straightforward to extract the regions as substrings, replace T by U, and add all the substrings together:
def create_mRNA(gene, exon_regions): mrna = '' for start, end in exon_regions: mrna += gene[start:end].replace('T','U') return mrna mrna = create_mRNA(lactase_gene, lactase_exon_regions)
We would like to store the mRNA string in a file, using the same format as lactase_gene.txt and yeast_chr1.txt, i.e., the string is split on multiple lines with, e.g., 70 characters per line. An appropriate function doing this is
def tofile_with_line_sep_v1(text, filename, chars_per_line=70): outfile = open(filename, 'w') for i in xrange(0, len(text), chars_per_line): start = i end = start + chars_per_line outfile.write(text[start:end] + '\n') outfile.close()
It might be convenient to have a separate folder for files that we create. Python has good support for testing if a folder exists, and if not, make a folder:
output_folder = 'output' if not os.path.isdir(output_folder): os.mkdir(output_folder) filename = os.path.join(output_folder, 'lactase_mrna.txt') tofile_with_line_sep_v1(mrna, filename)
Python’s term for folder is directory, which explains why isdir is the function name for testing on a folder existence. Observe especially that the combination of a folder and a filename is done via os.path.join rather than just inserting a forward slash, or backward slash on Windows: os.path.join will insert the right slash, forward or backward, depending on the current operating system.
Occasionally, the output folder is nested, say
output_folder = os.path.join('output', 'lactase')
In that case, os.mkdir(output_folder) may fail because the intermediate folder output is missing. Making a folder and also all missing intermediate folders is done by os.makedirs. We can write a more general file writing function that takes a folder name and file name as input and writes the file. Let us also add some flexibility in the file format: one can either write a fixed number of characters per line, or have the string on just one long line. The latter version is specified through chars_per_line='inf' (for infinite number of characters per line). The flexible file writing function then becomes
def tofile_with_line_sep_v2(text, foldername, filename, chars_per_line=70): if not os.path.isdir(foldername): os.makedirs(foldername) filename = os.path.join(foldername, filename) outfile = open(filename, 'w') if chars_per_line == 'inf': outfile.write(text) else: for i in xrange(0, len(text), chars_per_line): start = i end = start + chars_per_line outfile.write(text[start:end] + '\n') outfile.close()
To create the protein, we replace the triplets of the mRNA strings by the corresponding 1-letter name as specified in the genetic_code.tsv file.
def create_protein(mrna, genetic_code): protein = '' for i in xrange(len(mrna)/3): start = i * 3 end = start + 3 protein += genetic_code[mrna[start:end]] return protein genetic_code = read_genetic_code_v1('genetic_code.tsv') protein = create_protein(mrna, genetic_code) tofile_with_line_sep_v2(protein, 'output',
Unfortunately, this first try to simulate the translation process is incorrect. The problem is that the translation always begins with the amino acid Methionine, code AUG, and ends when one of the stop codons is met. We must thus check for the correct start and stop criteria. A fix is
def create_protein_fixed(mrna, genetic_code): protein_fixed = '' trans_start_pos = mrna.find('AUG') for i in range(len(mrna[trans_start_pos:])/3): start = trans_start_pos + i*3 end = start + 3 amino = genetic_code[mrna[start:end]] if amino == 'X': break protein_fixed += amino return protein_fixed protein = create_protein_fixed(mrna, genetic_code) tofile_with_line_sep_v2(protein, 'output', 'lactase_protein_fixed.txt', 70) print '10 last amino acids of the correct lactase protein: ', \ protein[-10:] print 'Lenght of the correct protein: ', len(protein)
The output, needed below for comparison, becomes
10 last amino acids of the correct lactase protein: QQELSPVSSF Lenght of the correct protein: 1927
One type of lactose intolerance is called Congenital lactase deficiency. This is a rare genetic disorder that causes lactose intolerance from birth, and is particularly common in Finland. The disease is caused by a mutation of the base in position 30049 (0-based) of the lactase gene, a mutation from T to A. Our goal is to check what happens to the protein if this base is mutated. This is a simple task using the previously developed tools:
def congential_lactase_deficiency( lactase_gene, genetic_code, lactase_exon_regions, output_folder=os.curdir, mrna_file=None, protein_file=None): pos = 30049 mutated_gene = lactase_gene[:pos] + 'A' + lactase_gene[pos+1:] mutated_mrna = create_mRNA(mutated_gene, lactase_exon_regions) if mrna_file is not None: tofile_with_line_sep_v2( mutated_mrna, output_folder, mrna_file) mutated_protein = create_protein_fixed( mutated_mrna, genetic_code) if protein_file: tofile_with_line_sep_v2( mutated_protein, output_folder, protein_file) return mutated_protein mutated_protein = congential_lactase_deficiency( lactase_gene, genetic_code, lactase_exon_regions, output_folder='output', mrna_file='mutated_lactase_mrna.txt', protein_file='mutated_lactase_protein.txt') print '10 last amino acids of the mutated lactase protein:', \ mutated_protein[-10:] print 'Lenght of the mutated lactase protein:', \ len(mutated_protein)
The output, to be compared with the non-mutated gene above, is now
10 last amino acids of the mutated lactase protein: GFIWSAASAA Lenght of the mutated lactase protein: 1389
As we can see, the translation stops prematurely, creating a much smaller protein, which will not have the required characteristics of the lactase protein.
A couple of mutations in a region for LCT located in front of LCT (actually in the introns of another gene) is the reason for the common lactose intolerance. That is, the one that sets in for adults only. These mutations control the expression of the LCT gene, i.e., whether that the gene is turned on or off. Interestingly, different mutations have evolved in different regions of the world, e.g., Africa and Northern Europe. This is an example of convergent evolution: the acquisition of the same biological trait in unrelated lineages. The prevalence of lactose intolerance varies widely, from around 5% in northern Europe, to close to 100% in south-east Asia.
The functions analyzing the lactase gene are found in the file genes2proteins.py.
Mutation of genes
is easily modeled by replacing the letter in a randomly chosen position of the DNA by a randomly chosen letter from the alphabet A, C, G, and T. Python’s random module can be used to generate random numbers. Selecting a random position means generating a random index in the DNA string, and the function random.randint(a, b) generates random integers between a and b (both included). Generating a random letter is easiest done by having a list of the actual letters and using random.choice(list) to pick an arbitrary element from list. A function for replacing the letter in a randomly selected position (index) by a random letter among A, C, G, and T is most straightforwardly implemented by converting the DNA string to a list of letters, since changing a character in a Python string is impossible without constructing a new string. However, an element in a list can be changed in-place:
import random def mutate_v1(dna): dna_list = list(dna) mutation_site = random.randint(0, len(dna_list) - 1) dna_list[mutation_site] = random.choice(list('ATCG')) return ''.join(dna_list)
Using get_base_frequencies_v2 and format_frequencies from the section Finding Base Frequencies, we can easily mutate a gene a number of times and see how the frequencies of the bases A, C, G, and T change:
dna = 'ACGGAGATTTCGGTATGCAT' print 'Starting DNA:', dna print format_frequencies(get_base_frequencies_v2(dna)) nmutations = 10000 for i in range(nmutations): dna = mutate_v1(dna) print 'DNA after %d mutations:' % nmutations, dna print format_frequencies(get_base_frequencies_v2(dna))
Here is the output from a run:
Starting DNA: ACGGAGATTTCGGTATGCAT A: 0.25, C: 0.15, T: 0.30, G: 0.30 DNA after 10000 mutations: AACCAATCCGACGAGGAGTG A: 0.35, C: 0.25, T: 0.10, G: 0.30
The efficiency of the mutate_v1 function with its surrounding loop can be significantly increased up by performing all the mutations at once using numpy arrays. This speed-up is of interest for long dna strings and many mutations. The idea is to draw all the mutation sites at once, and also all the new bases at these sites at once. The np.random module provides functions for drawing several random numbers at a time, but only integers and real numbers can be drawn, not characters from the alphabet A, C, G, and T. We therefore have to simulate these four characters by the numbers (say) 0, 1, 2, and 3. Afterwards we can translate the integers to letters by some clever vectorized indexing.
Drawing N mutation sites is a matter of drawing N random integers among the legal indices:
import numpy as np mutation_sites = np.random.random_integers(0, len(dna)-1, size=N)
Drawing N bases, represented as the integers 0-3, is similarly done by
new_bases_i = np.random.random_integers(0, 3, N)
Converting say the integers 1 to the base symbol C is done by picking out the indices (in a boolean array) where new_bases_i equals 1, and inserting the character 'C' in a companion array of characters:
new_bases_c = np.zeros(N, dtype='c') indices = new_bases_i == 1 new_bases_c[indices] = 'C'
We must do this integer-to-letter conversion for all four integers/letters. Thereafter, new_bases_c must be inserted in dna for all the indices corresponding to the randomly drawn mutation sites,
dna[mutation_sites] = new_bases_c
The final step is to convert the numpy array of characters dna back to a standard string by first converting dna to a list and then joining the list elements: ''.join(dna.tolist()).
The complete vectorized functions can now be expressed as follows:
import numpy as np # Use integers in random numpy arrays and map these # to characters according to i2c = {0: 'A', 1: 'C', 2: 'G', 3: 'T'} def mutate_v2(dna, N): dna = np.array(dna, dtype='c') # array of characters mutation_sites = np.random.random_integers( 0, len(dna) - 1, size=N) # Must draw bases as integers new_bases_i = np.random.random_integers(0, 3, size=N) # Translate integers to characters new_bases_c = np.zeros(N, dtype='c') for i in i2c: new_bases_c[new_bases_i == i] = i2c[i] dna[mutation_sites] = new_bases_c return ''.join(dna.tolist())
It is of interest to time mutate_v2 versus mutate_v1. For this purpose we need a long test string. A straightforward generation of random letters is
def generate_string_v1(N, alphabet='ACGT'): return ''.join([random.choice(alphabet) for i in xrange(N)])
A vectorized version of this function can also be made, using the ideas explored above for the mutate_v2 function:
def generate_string_v2(N, alphabet='ACGT'): # Draw random integers 0,1,2,3 to represent bases dna_i = np.random.random_integers(0, 3, N) # Translate integers to characters dna = np.zeros(N, dtype='c') for i in i2c: dna[dna_i == i] = i2c[i] return ''.join(dna.tolist())
The time_mutate function in the file mutate.py performs timing of the generation of test strings and the mutations. To generate a DNA string of length 100,000 the vectorized function is about 8 times faster. When performing 10,000 mutations on this string, the vectorized version is almost 3000 times faster! These numbers stay approximately the same also for larger strings and more mutations. Hence, this case study on vectorization is a striking example on the fact that a straightforward and convenient function like mutate_v1 might occasionally be very slow for large-scale computations.
The observed rate at which mutations occur at a given position in the genome is not independent of the type of nucleotide (base) at that position, as was assumed in the previous simple mutation model. We should therefore take into account that the rate of transition depends on the base.
There are a number of reasons why the observed mutation rates vary between different nucleotides. One reason is that there are different mechanisms generating transitions from one base to another. Another reason is that there are extensive repair process in living cells, and the efficiency of this repair mechanism varies for different nucleotides.
Mutation of nucleotides may be modeled using distinct probabilities for the transitions from each nucleotide to every other nucleotide. For example, the probability of replacing A by C may be prescribed as (say) 0.2. In total we need \(4\times 4\) probabilities since each nucleotide can transform into itself (no change) or three others. The sum of all four transition probabilities for a given nucleotide must sum up to one. Such statistical evolution, based on probabilities for transitioning from one state to another, is known as a Markov process or Markov chain.
First we need to set up the probability matrix, i.e., the \(4\times4\) table of probabilities where each row corresponds to the transition of A, C, G, or T into A, C, G, or T. Say the probability transition from A to A is 0.2, from A to C is 0.1, from A to G is 0.3, and from A to T is 0.4.
Rather than just prescribing some arbitrary transition probabilities for test purposes, we can use random numbers for these probabilities. To this end, we generate three random numbers to divide the interval \([0,1]\) into four intervals corresponding to the four possible transitions. The lengths of the intervals give the transition probabilities, and their sum is ensured to be 1. The interval limits, 0, 1, and three random numbers must be sorted in ascending order to form the intervals. We use the function random.random() to generate random numbers in \([0,1)\):
slice_points = sorted( [0] + [random.random() for i in range(3)] + [1]) transition_probabilities = [slice_points[i+1] - slice_points[i] for i in range(4)]
The transition probabilities are handy to have available as a dictionary:
markov_chain['A'] = {'A': ..., 'C': ..., 'G': ..., 'T': ...}
which can be computed by
markov_chain['A'] = {base: p for base, p in zip('ACGT', transition_probabilities)}
To select a transition, we need to draw a random letter (A, C, G, or T) according to the probabilities markov_chain[b] where b is the base at the current position. Actually, this is a very common operation, namely drawing a random value from a discrete probability distribution (markov_chain[b]). The natural approach is therefore write a general function for drawing from any discrete probability distribution given as a dictionary:
def draw(discrete_probdist): """ Draw random value from discrete probability distribution represented as a dict: P(x=value) = discrete_probdist[value]. """ # Method: # limit = 0 r = random.random() for value in discrete_probdist: limit += discrete_probdist[value] if r < limit: return value
Basically, the algorithm divides \([0,1]\) into intervals of lengths equal to the probabilities of the various outcomes and checks which interval is hit by a random variable in \([0,1]\). The corresponding value is the random choice.
A complete function creating all the transition probabilities and storing them in a dictionary of dictionaries takes the form
def create_markov_chain(): markov_chain = {} for from_base in 'ATGC': # Generate random transition probabilities by dividing # [0,1] into four intervals of random length slice_points = sorted( [0] + [random.random()for i in range(3)] + [1]) transition_probabilities = \ [slice_points[i+1] - slice_points[i] for i in range(4)] markov_chain[from_base] = {base: p for base, p in zip('ATGC', transition_probabilities)} return markov_chain mc = create_markov_chain() print mc print mc['A']['T'] # probability of transition from A to T
It is natural to develop a function for checking that the generated probabilities are consistent. The transition from a particular base into one of the four bases happens with probability 1, which means that the probabilities in a row must sum up to 1:
def check_transition_probabilities(markov_chain): for from_base in 'ATGC': s = sum(markov_chain[from_base][to_base] for to_base in 'ATGC') if abs(s - 1) > 1E-15: raise ValueError('Wrong sum: %s for "%s"' % \ (s, from_base))
Another test is to check that draw actually draws random values in accordance with the underlying probabilities. To this end, we draw a large number of values, N, count the frequencies of the various values, divide by N and compare the empirical normalized frequencies with the probabilities:
def check_draw_approx(discrete_probdist, N=1000000): """ See if draw results in frequencies approx equal to the probability distribution. """ frequencies = {value: 0 for value in discrete_probdist} for i in range(N): value = draw(discrete_probdist) frequencies[value] += 1 for value in frequencies: frequencies[value] /= float(N) print ', '.join(['%s: %.4f (exact %.4f)' % \ (v, frequencies[v], discrete_probdist[v]) for v in frequencies])
This test is only approximate, but does bring evidence to the correctness of the implementation of the draw function.
A vectorized version of draw can also be made. We refer to the source code file mutate.py for details (the function is relatively complicated).
Now we have all the tools needed to run the Markov chain of transitions for a randomly selected position in a DNA sequence:
def mutate_via_markov_chain(dna, markov_chain): dna_list = list(dna) mutation_site = random.randint(0, len(dna_list) - 1) from_base = dna[mutation_site] to_base = draw(markov_chain[from_base]) dna_list[mutation_site] = to_base return ''.join(dna_list)
Exercise 6: Speed up Markov chain mutation suggests some efficiency enhancements of simulating mutations via these functions.
Here is a simulation of mutations using the method based on Markov chains:
dna = 'TTACGGAGATTTCGGTATGCAT' print 'Starting DNA:', dna print format_frequencies(get_base_frequencies_v2(dna)) mc = create_markov_chain() import pprint print 'Transition probabilities:\n', pprint.pformat(mc) nmutations = 10000 for i in range(nmutations): dna = mutate_via_markov_chain(dna, mc) print 'DNA after %d mutations (Markov chain):' % nmutations, dna print format_frequencies(get_base_frequencies_v2(dna))
The output will differ each time the program is run unless random.seed(i) is called in the beginning of the program for some integer i. This call makes the sequence of random numbers the same every time the program is run and is very useful for debugging. An example on the output may look like
Starting DNA: TTACGGAGATTTCGGTATGCAT A: 0.23, C: 0.14, T: 0.36, G: 0.27 Transition probabilities: {'A': {'A': 0.4288890546751146, 'C': 0.4219086988655296, 'G': 0.00668870644455688, 'T': 0.14251354001479888}, 'C': {'A': 0.24999667668640035, 'C': 0.04718309085408834, 'G': 0.6250440975238185, 'T': 0.0777761349356928}, 'G': {'A': 0.16022955651881965, 'C': 0.34652746609882423, 'G': 0.1328031742612512, 'T': 0.3604398031211049}, 'T': {'A': 0.20609823213950174, 'C': 0.17641112746655452, 'G': 0.010267621176125452, 'T': 0.6072230192178183}} DNA after 10000 mutations (Markov chain): GGTTTAAGTCAGCTATGATTCT A: 0.23, C: 0.14, T: 0.41, G: 0.23
Note that the mutated DNA should contain more nucleotides of the type where the total probability of transitioning into that particular nucleotide is largest. The total probability of transitioning into a particular base can be computed by a bit a probability algebra. Let \(X\) be the initial base at some position in the DNA and let \(Y\) be the new base after mutation at this position. The probability that \(P(Y=b)\), where \(b\) is some base (A, C, G, or T), is built up of four mutually exclusive events:
A joint event can be expressed by the (conditional) transition probabilities, e.g.,
leading to
The probabilities \(P(Y=b|X=i)\) correspond to a column in the transition probability matrix. If each of the initial events \(P(X=i)\) are equally probable, \(P(X=i)=1/4\), and \(P(Y=b)\) is then the sum of the probabilities in the column corresponding to \(b\), divided by 4. We can now compute \(P(Y=b)\) for \(b\) as A, C, G, and T:
def transition_into_bases(markov_chain): return {to_base: sum(markov_chain[from_base][to_base] for from_base in 'ATGC')/4.0 for to_base in 'ATGC'} print transition_into_bases(mc)
The \(P(X=b)\) probabilities corresponding to the example run above reads
{'A': 0.26, 'C': 0.25, 'T': 0.30, 'G': 0.19}
Transition into T (\(P(Y=T)\)) has greatest probability (0.3) and this is also confirmed by the greatest frequency (0.41).
The various functions performing mutations are located in the file mutate.py.
We shall here exemplify the use of classes for performing DNA analysis as explained in the previous text. Basically, we create a class Gene to represent a DNA sequence (string) and a class Region to represent a subsequence (substring), typically an exon or intron.
The class for representing a region of a DNA string is quite simple:
class Region(object): def __init__(self, dna, start, end): self._region = dna[start:end] def get_region(self): return self._region def __len__(self): return len(self._region) def __eq__(self, other): """Check if two Region instances are equal.""" return self._region == other._region def __add__(self, other): """Add Region instances: self + other""" return self._region + other._region def __iadd__(self, other): """Increment Region instance: self += other""" self._region += other._region return self
Besides storing the substring and giving access to it through get_region, we have also included the possibility to
- say len(r) if r is a Region instance
- check if two Region instances are equal
- write r1 + r2 for two instances r1 and r2 of type Region
- perform r1 += r2
The latter two operations are convenient for making one large string out of all exon or intron regions.
The class for gene will be longer and more complex than class Region. We already have a bunch of functions performing various types of analysis. The idea of the Gene class is that these functions are methods in the class operating on the DNA string and the exon regions stored in the class. Rather than recoding all the functions as methods in the class we shall just let the class “wrap” the functions. That is, the class methods call up the functions we already have. This approach has two advantages: users can either choose the function-based or the class-based interface, and the programmer can reuse all the ready-made functions when implementing the class-based interface.
The selection of functions include
- generate_string for generating a random string from some alphabet
- download and read_dnafile (version read_dnafile_v1) for downloading data from the Internet and reading from file
- read_exon_regions (version read_exon_regions_v2) for reading exon regions from file
- tofile_with_line_sep (version tofile_with_line_sep_v2) for writing strings to file
- read_genetic_code (version read_genetic_code_v2) for loading the mapping from triplet codes to 1-letter symbols for amino acids
- get_base_frequencies (version get_base_frequencies_v2) for finding frequencies of each base
- format_frequencies for formatting base frequencies with two decimals
- create_mRNA for computing an mRNA string from DNA and exon regions
- mutate for mutating a base at a random position
- create_markov_chain, transition, and mutate_via_markov_chain for mutating a base at a random position according to randomly generated transition probabilities
- create_protein_fixed for proper creation of a protein sequence (string)
The set of plain functions for DNA analysis is found in the file dna_functions.py, while dna_classes.py contains the implementations of classes Gene and Region.
Class Gene is supposed to hold the DNA sequence and the associated exon regions. A simple constructor expects the exon regions to be specified as a list of (start, end) tuples indicating the start and end of each region:
class Gene(object): def __init__(self, dna, exon_regions): self._dna = dna self._exon_regions = exon_regions self._exons = [] for start, end in exon_regions: self._exons.append(Region(dna, start, end)) # Compute the introns (regions between the exons) self._introns = [] prev_end = 0 for start, end in exon_regions: self._introns.append(Region(dna, prev_end, start)) prev_end = end self._introns.append(Region(dna, end, len(dna)))
The methods in class Gene are trivial to implement when we already have the functionality in stand-alone functions. Here are a few examples on methods:
from dna_functions import * class Gene(object): ... def write(self, filename, chars_per_line=70): """Write DNA sequence to file with name filename.""" tofile_with_line_sep(self._dna, filename, chars_per_line) def count(self, base): """Return no of occurrences of base in DNA.""" return self._dna.count(base) def get_base_frequencies(self): """Return dict of base frequencies in DNA.""" return get_base_frequencies(self._dna) def format_base_frequencies(self): """Return base frequencies formatted with two decimals.""" return format_frequencies(self.get_base_frequencies())
The constructor can be made more flexible. First, the exon regions may not be known so we should allow None as value and in fact use that as default value. Second, exon regions at the start and/or end of the DNA string will lead to empty intron Region objects so a proper test on nonzero length of the introns must be inserted. Third, the data for the DNA string and the exon regions can either be passed as arguments or downloaded and read from file. Two different initializations of Gene objects are therefore
g1 = Gene(dna, exon_regions) # user has read data from file g2 = Gene((urlbase, dna_file), (urlbase, exon_file)) # download
One can pass None for urlbase if the files are already at the computer. The flexible constructor has, not surprisingly, much longer code than the first version. The implementation illustrates well how the concept of overloaded constructors in other languages, like C++ and Java, are dealt with in Python (overloaded constructors take different types of arguments to initialize an instance):
class Gene(object): def __init__(self, dna, exon_regions): """ dna: string or (urlbase,filename) tuple exon_regions: None, list of (start,end) tuples or (urlbase,filename) tuple In case of (urlbase,filename) tuple the file is downloaded and read. """ if isinstance(dna, (list,tuple)) and \ len(dna) == 2 and isinstance(dna[0], str) and \ isinstance(dna[1], str): download(urlbase=dna[0], filename=dna[1]) dna = read_dnafile(dna[1]) elif isinstance(dna, str): pass # ok type (the other possibility) else: raise TypeError( 'dna=%s %s is not string or (urlbase,filename) '\ 'tuple' % (dna, type(dna))) self._dna = dna er = exon_regions if er is None: self._exons = None self._introns = None else: if isinstance(er, (list,tuple)) and \ len(er) == 2 and isinstance(er[0], str) and \ isinstance(er[1], str): download(urlbase=er[0], filename=er[1]) exon_regions = read_exon_regions(er[1]) elif isinstance(er, (list,tuple)) and \ isinstance(er[0], (list,tuple)) and \ isinstance(er[0][0], int) and \ isinstance(er[0][1], int): pass # ok type (the other possibility) else: raise TypeError( 'exon_regions=%s %s is not list of (int,int) ' 'or (urlbase,filename) tuple' % (er, type(era))) self._exon_regions = exon_regions self._exons = [] for start, end in exon_regions: self._exons.append(Region(dna, start, end)) # Compute the introns (regions between the exons) self._introns = [] prev_end = 0 for start, end in exon_regions: if start - prev_end > 0: self._introns.append( Region(dna, prev_end, start)) prev_end = end if len(dna) - end > 0: self._introns.append(Region(dna, end, len(dna)))
Note that we perform quite detailed testing of the object type of the data structures supplied as the dna and exon_regions arguments. This can well be done to ensure safe use also when there is only one allowed type per argument.
A create_mRNA method, returning the mRNA as a string, can be coded as
def create_mRNA(self): """Return string for mRNA.""" if self._exons is not None: return create_mRNA(self._dna, self._exon_regions) else: raise ValueError( 'Cannot create mRNA for gene with no exon regions')
Also here we rely on calling an already implemented function, but include some testing whether asking for mRNA is appropriate.
Methods for creating a mutated gene are also included:
def mutate_pos(self, pos, base): """Return Gene with a mutation to base at position pos.""" dna = self._dna[:pos] + base + self._dna[pos+1:] return Gene(dna, self._exon_regions) def mutate_random(self, n=1): """ Return Gene with n mutations at a random position. All mutations are equally probable. """ mutated_dna = self._dna for i in range(n): mutated_dna = mutate(mutated_dna) return Gene(mutated_dna, self._exon_regions) def mutate_via_markov_chain(markov_chain): """ Return Gene with a mutation at a random position. Mutation into new base based on transition probabilities in the markov_chain dict of dicts. """ mutated_dna = mutate_via_markov_chain( self._dna, markov_chain) return Gene(mutated_dna, self._exon_regions)
Some “get” methods that give access to the fundamental attributes of the class can be included:
def get_dna(self): return self._dna def get_exons(self): return self._exons def get_introns(self): return self._introns
Alternatively, one could access the attributes directly: gene._dna, gene._exons, etc. In that case we should remove the leading underscore as this underscore signals that these attributes are considered “protected”, i.e., not to be directly accessed by the user. The “protection” in “get” functions is more mental than actual since we anyway give the data structures in the hands of the user and she can do whatever she wants (even delete them).
Special methods for the length of a gene, adding genes, checking if two genes are identical, and printing of compact gene information are relevant to add:
def __len__(self): return len(self._dna) def __add__(self, other): """self + other: append other to self (DNA string).""" if self._exons is None and other._exons is None: return Gene(self._dna + other._dna, None) else: raise ValueError( 'cannot do Gene + Gene with exon regions') def __iadd__(self, other): """self += other: append other to self (DNA string).""" if self._exons is None and other._exons is None: self._dna += other._dna return self else: raise ValueError( 'cannot do Gene += Gene with exon regions') def __eq__(self, other): """Check if two Gene instances are equal.""" return self._dna == other._dna and \ self._exons == other._exons def __str__(self): """Pretty print (condensed info).""" s = 'Gene: ' + self._dna[:6] + '...' + self._dna[-6:] + \ ', length=%d' % len(self._dna) if self._exons is not None: s += ', %d exon regions' % len(self._exons) return s
Here is an interactive session demonstrating how we can work with class Gene objects:
>>> from dna_classes import Gene >>> g1 = Gene('ATCCGTAATTGCGCA', [(2,4), (6,9)]) >>> print g1 Gene: ATCCGT...TGCGCA, length=15, 2 exon regions >>> g2 = g1.mutate_random(10) >>> print g2 Gene: ATCCGT...TGTGCT, length=15, 2 exon regions >>> g1 == g2 False >>> g1 += g2 # expect exception Traceback (most recent call last): ... ValueError: cannot do Gene += Gene with exon regions >>> g1b = Gene(g1.get_dna(), None) >>> g2b = Gene(g2.get_dna(), None) >>> print g1b Gene: ATCCGT...TGCGCA, length=15 >>> g3 = g1b + g2b >>> g3.format_base_frequencies() 'A: 0.17, C: 0.23, T: 0.33, G: 0.27' Traceback (most recent call last): ... ValueError: cannot do Gene += Gene with exon regions
There are two fundamental types of genes: the most common type that codes for proteins (indirectly via mRNA) and the type that only codes for RNA (without being further processed to proteins). The product of a gene, mRNA or protein, depends on the type of gene we have. It is then natural to create two subclasses for the two types of gene and have a method get_product which returns the product of that type of gene.
The get_product method can be declared in class Gene:
def get_product(self): raise NotImplementedError( 'Subclass %s must implement get_product' % \ self.__class__.__name__)
The exception here will be triggered by an instance (self) of any subclass that just inherits get_product from class Gene without implementing a subclass version of this method.
The two subclasses of Gene may take this simple form:
class RNACodingGene(Gene): def get_product(self): return self.create_mRNA() class ProteinCodingGene(Gene): def __init__(self, dna, exon_positions): Gene.__init__(self, dna, exon_positions) urlbase = '' genetic_code_file = 'genetic_code.tsv' download(urlbase, genetic_code_file) code = read_genetic_code(genetic_code_file) self.genetic_code = code def get_product(self): return create_protein_fixed(self.create_mRNA(), self.genetic_code)
A demonstration of how to load the lactase gene and create the lactase protein is done with
def test_lactase_gene(): urlbase = '' lactase_gene_file = 'lactase_gene.txt' lactase_exon_file = 'lactase_exon.tsv' lactase_gene = ProteinCodingGene( (urlbase, lactase_gene_file), (urlbase, lactase_exon_file)) protein = lactase_gene.get_product() tofile_with_line_sep(protein, 'output', 'lactase_protein.txt')
Now, envision that the Lactase gene would instead have been an RNA-coding gene. The only necessary changes would have been to exchange ProteinCodingGene by RNACodingGene in the assignment to lactase_gene, and one would get out a final RNA product instead of a protein.
Acknowledgments. The authors want to thank Sveinung Gundersen, Ksenia Khelik, Halfdan Rydbeck, and Kai Trengereid for contributing to the examples and their implementations.
Write a function count_pairs(dna, pair) that returns the number of occurrences of a pair of characters (pair) in a DNA string (dna). For example, calling the function with dna as 'ACTGCTATCCATT' and pair as 'AT' will return 2. Filename: count_pairs.py.
This is an extension of Exercise 1: Find pairs of characters: count how many times a certain string appears in another string. For example, the function returns 3 when called with the DNA string 'ACGTTACGGAACG' and the substring 'ACG'.
Hint. For each match of the first character of the substring in the main string, check if the next n characters in the main string matches the substring, where n is the length of the substring. Use slices like s[3:9] to pick out a substring of s.
Filename: count_substr.py.
Consider the family of find_consensus_v* functions from the section Analyzing the Frequency Matrix. The different versions work on different representations of the frequency matrix. Make a unified find_consensus function that accepts different data structures for the frequency_matrix. Test on the type of data structure and perform the necessary actions. Filename: find_consensus.py.
Consider the function get_base_counts(dna) from the section Finding Base Frequencies, which counts how many times A, C, G, and T appears in the string dna:
def get_base_counts(dna): counts = {'A': 0, 'T': 0, 'G': 0, 'C': 0} for base in dna: counts[base] += 1 return counts
Unfortunately, this function crashes if other letters appear in dna. Write an enhanced function get_base_counts2 which solves this problem. Test it on a string like 'ADLSTTLLD'. Filename: get_base_counts2.py.
Consider the lactase gene as described in the sections Translating Genes into Proteins and Some Humans Can Drink Milk, While Others Cannot. What is the proportion of base A inside and outside exons of the lactase gene?
Hint. Write a function get_exons, which returns all the substrings of the exon regions concatenated. Also write a function get_introns, which returns all the substrings between the exon regions concatenated. The function get_base_frequencies from the section Finding Base Frequencies can then be used to analyze the frequencies of bases A, C, G, and T in the two strings.
Filename: prop_A_exons.py.
The functions transition and mutate_via_markov_chain from the section Random Mutations of Genes were made for being easy to read and understand. Upon closer inspection, we realize that the transition function constructs the interval_limits every time a random transition is to be computed, and we want to run a large number of transitions. By merging the two functions, pre-computing interval limits for each from_base, and adding a loop over N mutations, one can reduce the computation of interval limits to a minimum. Perform such an efficiency enhancement. Measure the CPU time of this new function versus the mutate_via_markov_chain function for 1 million mutations. Filename: markov_chain_mutation2.py.
Modify the constructor in class Gene from the section Classes for DNA Analysis such that giving no arguments to the constructor makes the class call up the generate_string method (from the dna_functions module) which generates a random DNA sequence. Filename: dna_classes2.py.
|
http://hplgit.github.io/bioinf-py/doc/pub/html/main_bioinf.html
|
CC-MAIN-2020-05
|
refinedweb
| 13,975
| 51.68
|
I'm using ST3 as an external editor to display error logs from another application (katana) with syntax highlighting. So katana launches sublime via a wrapper script that includes sublime_text --wait pathToErrorLog.txt. My package includes the .tmLanguage with highlighting rules and .tmTheme for custom color scheme, and an EventListener subclass that uses on_load() to watch for katana log files being opened.
sublime_text --wait pathToErrorLog.txt
This works perfectly when a ST3 instance happens to be already running. However, if ST3 is being newly launched via the above command, on_load() doesn't get called after the log is loaded. Also tried on_load_async(), same problem. Should I be using a different callback? I'm wondering if maybe plugins have not finished loading and registering callbacks by the time this first buffer is loaded. Thanks!
class PxOpenKatanaRenderLog (sublime_plugin.EventListener):
def on_load (self, view):
filePath = view.file_name()
fileName = os.path.basename (filePath)
if fileName.startswith ('katanaRenderLog'):
view.run_command ('px_katana_strip_progress_warnings')
view.run_command ('px_katana_pretty_print_render_log')
view.settings().set ('syntax', 'Packages/Katana/KatanaRenderLog.tmLanguage')
view.settings().set ('color_scheme', 'Packages/Katana/KatanaRenderLog.tmTheme')
view.settings().set ('line_numbers', False)
view.settings().set ('fade_fold_buttons', False)
view.set_scratch (True)
Thanks for that link. Very helpful.
|
https://forum.sublimetext.com/t/on-load-eventlistener-not-called-on-first-launch/29105
|
CC-MAIN-2018-22
|
refinedweb
| 194
| 55.61
|
When using mutables in Python you have to be careful:
>>> a = {'value': 1} >>> b = a >>> a['value'] = 2 >>> b {'value': 2}
So, you use the
copy module from the standard library:
>>> import copy >>> a = {'value': 1} >>> b = copy.copy(a) >>> a['value'] = 2 >>> b {'value': 1}
That's nice but it's limited. It doesn't deal with the nested mutables as you can see here:
>>> a = {'value': {'name': 'Something'}} >>> b = copy.copy(a) >>> a['value']['name'] = 'else' >>> b {'value': {'name': 'else'}}
That's when you need the
copy.deepcopy function:
>>> a = {'value': {'name': 'Something'}} >>> b = copy.deepcopy(a) >>> a['value']['name'] = 'else' >>> b {'value': {'name': 'Something'}}
Now, suppose we have a custom class that overrides the
dict type. That's a very common thing to do. Let's demonstrate:
>>> class ORM(dict): ... pass ... >>> a = ORM(>> b {'name': 'Value'}
And again, if you have a nested mutable object you need
copy.deepcopy:
>>> class ORM(dict): ... pass ... >>> a = ORM(data={'name': 'Something'}) >>> b = copy.deepcopy(a) >>> a['data']['name'] = 'else' >>> b {'data': {'name': 'Something'}}
But oftentimes you'll want to make your
dict subclass behave like a regular class so you can access data with dot notation. Like this:
>>> class ORM(dict): ... def __getattr__(self, key): ... return self[key] ... >>> a = ORM(data={'name': 'Something'}) >>> a.data['name'] 'Something'
Now here's a problem. If you do that, you loose the ability to use
copy.deepcopy since the class has now been slightly "abused".
>>> a = ORM(data={'name': 'Something'}) >>> a.data['name'] 'Something' >>> b = copy.deepcopy(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python/2.7.2/lib/python2.7/copy.py", line 172, in deepcopy copier = getattr(x, "__deepcopy__", None) File "<stdin>", line 3, in __getattr__ KeyError: '__deepcopy__'
Hmm... now you're in trouble and to get yourself out of it you have to define a
__deepcopy__ method as well. Let's just do it:
>>> class ORM(dict): ... def __getattr__(self, key): ... return self[key] ... def __deepcopy__(self, memo): ... return ORM(copy.deepcopy(dict(self))) ... >>> a = ORM(data={'name': 'Something'}) >>> a.data['name'] 'Something' >>> b = copy.deepcopy(a) >>> a.data['name'] = 'else' >>> b {'data': {'name': 'Something'}}
Yeah!!! Now we get what we want. Messing around with the
__getattr__ like this is, as far as I know, the only time you have to go in and write your own
__deepcopy__ method.
I'm sure hardcore Python language experts can point out lots of intricacies about
__deepcopy__ but since I only learned about this today, having it here might help someone else too.
Follow @peterbe on Twitter
There are many `__special__` names that cause problems of this kind when you accidentally provide them by overriding `__getattr__`. I've found it best to always do
def __getattr__(self, name):
if name.startswith('__'):
raise AttributeError(name)
...
Actually, your custom getattr raises KeyError for missing attributes, which is a strange thing to get from an expression that looks like `obj.attrname`. I would suggest catching KeyError and raising AttributeError. This would actually have avoided your original `__deepcopy__` error too.
(Note: I've replaced initial spaces with non-breaking spaces so this blog won't mangle the indentation. If you actually copy & paste this code, expect interesting SyntaxErrors ;)
Excellent! Thanks!
The reason you need to add __deepcopy__ is that your __getattr__ is buggy. Try changing it to this instead:
def __getattr__(self, key):
if key in self:
return self[key]
raise AttributeError(key)
You could have just changed the __getattr__ method to look up names starting with two underscores as attributes instead of as dict keys. Shadowing the names of all the special methods which start and end with two underscores is probably a bad idea.
I would have posted example code but I can't figure out how to prevent the comment form submission from stripping all the whitespace at the start of the line. :(
How about not breaking all the magic methods in the first place?
class Foo(dict):
····def __getattr__(self, attr):
········if attr.startswith('__'):
············raise AttributeError(attr)
········return self[attr]
Thanks! I like that.
This is why I keep blogging and expose my weaknesses because people like you come in and nudge me in the right direction.
the class that originally inspired this posting was the configman/socorro DotDict class. It is a class meant to be a derivative of dict. It was originally written like this:
....class DotDict(dict):
........__getattr__ = dict.__getitem__
........__setattr__ = dict.__setitem__
........__delattr__ = dict.__delitem__
This gave the result of a mapping that happened to have a convenient dot notation for accessing the values. Essentially, it hijacks the attribute notation for use in accessing items. This is fraught with peril as the deep copy conundrum demonstrates. Overriding the __getattr__ and __setattr__ functions always seems cause trouble and confusion.
While the original implementation was expedient, I suggest that we may want to look at the problem from the other direction. Let's override the __getitem__ and __setitem__ methods instead. That seems to be less perilous if not a bit more verbose:
....class DotDict(collections.MutableMapping):
........def __init__(self, initializer=None):
............if isinstance(initializer, collections.Mapping):
................self.__dict__.update(initializer)
............elif initializer is not None:
................raise TypeError('can only initialize with a Mapping')
........def __getitem__(self, key):
............return self.__dict__[key]
........def __setitem__(self, key, value):
............self.__dict__[key] = value
........def __delitem__(self, key):
............del self.__dict__[key]
........def __iter__(self):
............return ((k, v) for k, v in self.__dict__.iteritems()
....................if not k.startswith('_'))
........def __len__(self):
............return len(self.__dict__)
With this implementation, there is no interference with other magic methods. Deep copy works fine without having to override it with a local implementation.
This implementation will raise an AttributeError rather than a KeyError if a key is not found. This is somewhat of an irreconcilable difference. For use in configman/socorro, we're more interested in following the collections.Mapping interface, so we ought to have a KeyError rather than an AttributeError. Adding this method ought to fix that up:
........def __getattr__(self, key):
............try:
................return super(DotDict, self).__getattr__(key)
............except AttributeError:
................if not key.startswith('_'):
....................raise KeyError(key)
................raise
pastebin of my code from the previous posting:
ok, I withdraw that __getattr__ method. It superficially gave me the result that I wanted, but for the wrong reason. super(DotDict) doesn't have a __getattr__, so an AttributeError is raised.
__getattr__ is only called when the normal mechanism for finding an attribute have failed. So this is already the degenerate case. We ought to just be raising the KeyError in there without trying to first call some theoretical super implementation of __gettattr__.
As an aside, the whole idea at this point that things beginning with '_' are to be treated as special is suspect. By the time we get to a call of __getattr__ magic methods have already been resolved. So in your mind, delete my special handling of '_' in a key name.
|
https://www.peterbe.com/plog/must__deepcopy__
|
CC-MAIN-2019-09
|
refinedweb
| 1,160
| 59.6
|
#include <nsIFrame.h>
Frames can have multiple child lists: the default unnamed child list (referred to as the principal child list, and additional named child lists. There is an ordering of frames within a child list, but there is no order defined between frames in different child lists of the same parent frame.
Frames are NOT reference counted. Use the Destroy() member function to destroy a frame. The lifetime of the frame hierarchy is bounded by the lifetime of the presentation shell which owns the frames.
nsIFrame is a private Gecko interface. If you are not Gecko then you should not use it. If you're not in layout, then you won't be able to link to many of the functions defined here. Too bad.
If you're not in layout but you must call functions in here, at least restrict yourself to calling virtual methods, which won't hurt you as badly.
Definition at line 461 of file nsIFrame.h.
|
http://xulrunner.sourcearchive.com/documentation/1.9.0.5/classnsIFrame.html
|
CC-MAIN-2018-22
|
refinedweb
| 162
| 81.02
|
I was reading Effective Java by Joshua Bloch.
In Item 17: "Use interfaces only to define types", I came across the explanation where it is not advised to use Interfaces for storing constants. I am putting the explanation below.
"Worse, it represents a commitment: if in a future release the class is modified so that it
no longer needs to use the constants, it still must implement the interface to ensure binary
compatibility."
What does binary compatibility mean here?
Can someone guide me with an example in Java to show that code is binary compatible.
In short, binary compatibility means that when you change your class, you do not need to recompile classes that use it. For example, you removed or renamed a public or protected method from this class
public class Logger implements Constants { public Logger getLogger(String name) { return LogManager.getLogger(name); } }
from your log-1.jar library and released a new version as log-2.jar. When users of your log-1.jar download the new version it will break their apps when they will try to use the missing getLogger(String name) method.
And if you remove Constants interface (Item 17) this will break binary compatibility either, due to the same reason.
But you can remove / rename a private or package private member of this class without breaking the binary compatibility, because external apps cannot (or should not) use it.
|
https://codedump.io/share/d6lgkbbplbkS/1/what-is-binary-compatibility
|
CC-MAIN-2018-17
|
refinedweb
| 234
| 55.24
|
鸕鶿鸕鶿
Extensible Free Monad Effects
Do one thing and do it well micro birds library series
libraryDependencies += "us.oyanglul" %% "luci" % <version>"
Table of Contents
- 鸕鶿
The ProblemThe Problem
When you want to mix in some native effects into your Free Monad DSL, some effects won't work
for instance, we have two effects IO and StateT, and we would like to do some math using StateT
Here is the Program
import Free.{liftInject => free} type Program[A] = EitherK[IO, StateT[IO, Int, ?], A] type ProgramF[A] = Free[Program, A] def program : Program[Int] = for { initState <- free[Program](StateT.get[IO, Int]) _ <- free[Program](IO(println(s"init state is $initState"))) _ <- free[Program](StateT.modify[IO, Int](_ + 1)) res <- free[Program](StateT.modify[IO, Int](_ + 1)) } yield res
and Interpreters
def ioInterp = FunctionK.id[IO] def stateTInterp(initState: Int) = Lambda[StateT[IO, Int, ?] ~> IO[(Int, ?)]] { _.run(initState)}
If we run the program
program foldMap (ioInterp or stateTInterp(0))
Guess what, it doesn't work, the result will be 1 not 2
because we run the state for each effect separately in the stateTInterp
One of the option is to use FreeT
But with FreeT:
- you can only mixin 1 effect, what if I have multiple effects that I want them to be stateful across the whole program.
- all other effects need to be lift to FreeT as well. It might have huge impact to our existing code base that is Free already.
The Ultimate SolutionThe Ultimate Solution
is using both meow-mtl and ReaderT/Kleisli, then we can easily integrate mtl into Free Monad Effects
- instead of using interpreter
Program ~> IO, we can use
Program ~> Kleisli[IO, ProgramContext, ?], and we have a better name for it - Compiler
- init state of stateful effects can then be injected into program via ProgramContext when actually running
Kleisli[IO, ProgramContext, ?]
Some Effects out of the boxSome Effects out of the box
- Id
- WriterT
- ReaderT/Kleisli
- StateT
- EitherT
- Http4sClient
- Doobie ConnectionIO
- fs2
It's very similar but just one more step to run the Kleisli
- create Program dsl
- compile Program into a Kleisli
- run Kleisli in a context
Step 1: Create DSLStep 1: Create DSL
e.g. our
Program has lot of effects... WriterT, Http4sClient, ReaderT, IO, StateT and Doobie's ConnectionIO
few of them need to be stateful across all over the program like WriterT, StateT
type Program[A] = Eff7[ Http4sClient[IO, ?], WriterT[IO, Chain[String], ?], ReaderT[IO, Config, ?], IO, ConnectionIO, StateT[IO, Int, ?], Either[Throwable, ?], A ] type ProgramF[A] = Free[Program, A]
EffX is predefined alias of type to construct multiple kind in
EitherK
Now lets start using these effects to do our work
val program = for { config <- free[Program](Kleisli.ask[IO, Config]) _ <- free[Program]( GetStatus[IO](GET(Uri.uri("")))) _ <- free[Program](StateT.modify[IO, Int](1 + _)) _ <- free[Program](StateT.modify[IO, Int](1 + _)) state <- free[Program](StateT.get[IO, Int]) _ <- free[Program]( WriterT.tell[IO, Chain[String]]( Chain.one("config: " + config.token))) resOrError <- free[Program](sql"""select true""".query[Boolean].unique) _ <- free[Program]( resOrError.handleError(e => println(s"handle db error $e"))) _ <- free[Program](IO(println(s"im IO...state: $state"))) } yield ()
Step 2: Compile the ProgramStep 2: Compile the Program
if we compile our program, we should get a binary
ProgramBin
import us.oyanglul.luci.compilers.io._ val binary = compile(program)
imagine that you have a binary of command line tool, when you run it you would probably need to provide some
--args
same here, if you want to run
ProgramBin, which is basically just a Kleisli, we need to provide args with is
ProgramContext
Step 3: Run ProgramStep 3: Run Program
run the program with real
--args
val args = (httpclient :: logRef.tellInstance :: config :: Unit :: transactor :: stateRef.stateInstance :: Unit :: HNil).map(coflatten) binary.run(args)
for stateful
WriterT and
StateT here, we can get
FunctorTell and
MonadState instances from
Ref[IO, ?] and inject them into program via
ProgramContext
each one corespond to program's effect's context
- binary for
Http4sClient[IO, ?]needs
Client[IO]to run
- binary for
WriterT[IO, Chain[String], ?]needs
FuntorTell[IO, Chain[String]], presented by meow-mtl
.tellInstance
- binary for
ReaderT[IO, Config, ?]needs
Configto run
- binary for
IOneeds nothing so
Unit
- binary for
ConnectionIOneeds
Transactor[IO]
- binary for
StateT[IO, Int, ?]needs
MonadState[IO, Int]to run, which presented here by meow-mtl from
.stateInstance
- binary for
Either[Throwable, ?]needs nothing so
Unit
Create Your Own EffectCreate Your Own Effect
creating an new compilable effect is pretty simple in 2 steps
Step 1: Create Data TypeStep 1: Create Data Type
This is nothing different from creating a effect data type for Free Monad
For instance we need a
s3 putObject Effect
import com.amazonaws.services.s3.model.PutObjectResult sealed trait S3[A] case class PutObject(bucketName: String, fileName: String, content: String) extends S3[PutObjectResult]
Step 2: Create CompilerStep 2: Create Compiler
To create a compiler for new data type s3, we'll need to create instance for type class Compiler
trait Compiler[F[_], E[_]] { type Env <: HList val compile: F ~> Kleisli[E, Env, ?] }
We need a type of
Env where the program needs to be compile. e.g. S3 need a AWS S3 Client
trait S3Compiler[E[_]] { implicit def s3Compiler(implicit F: Applicative[E]) = new Compiler[S3, E] { type Env = AmazonS3 :: HNil val compile = Lambda[S3 ~> Kleisli[E, Env, ?]] (_ match { case PutObject(bucketName, fileName, content) => Kleisli(env => F.pure(env.head.putObject(bucketName, fileName, content))) }) } }
There were few point to be noted here:
- be mindful that the
Envneeds to be a shapeless
HList, thus, here it's
AmazonS3 :: HNilnot
AmazonS3
- the compiler is generic on
E[_], but with restriction that E has to have instance for
Applicativeso we can use
.pure
- Kleisli will get env of type
AmazonS3 :: HNil, it's just like list but more acurate on it's content, you can get
headsafely since we know that there must be an item of type
AmazonS3in head.
Step 3 Use the effectStep 3 Use the effect
to be honest you don't need to make S3Compiler so generic since you may be the only person who using it. But it's a good practic to make every thing as genric as possible.
any way to use the generic effect, you can create a specific object just for IO(or Task of your choice)
object s3IoCompiler extends S3Compiler[IO]
and then import it to where you need to compile
import s3IoCompiler._
Or, simply extends it on the object or class you intent to compile your program
object Main extends S3Compiler[IO] with All{ ... val binary = compile(program) ... }
|
https://index.scala-lang.org/jcouyang/luci/luci/0.3.2?target=_2.12
|
CC-MAIN-2020-50
|
refinedweb
| 1,111
| 52.8
|
Threaded View
Answered: Use XmlReader/AutoBeans to parse XML that has attributes in the element?
Answered: Use XmlReader/AutoBeans to parse XML that has attributes in the element?
Can the XmlReader in conjunction with AutoBeans process an XML message that has attributes within the root node element?
The GXT example (which works just fine) uses relatively simple XML:
<record>
<name>SampleName</name>
</record>
However, what if the root node has attributes or namespace declarations in it?
<record xmlns:
<ab:name>SampleName</ab:name>
<ab:Email>sampleemail@email.com</ab:Email>
</record>
When I attempt to parse this kind of XML it seems that the XmlReader thinks it can't find a matching node, event if I use a PropertyName declaration (e.g. @PropertyName("record")).
Any suggestions would be greatly appreciated.
Just answered your SO post, but it is worth posting again here for others who hit this:
GXT's XmlReader sits on top of the build in XML parser that exists in the browser itself. It uses the com.google.gwt.xml.XML module in GWT to gain relatively consistent access to the XML nodes across all browsers, rather than building its own XML parser. By using the built-in implementation in the browser, GXT gets access to the native parser - and it turns out browsers are very good at parsing XML, since that's what they do all day, loading webpages.
Then, GXT has its own query engine to find nodes, in a query language that uses a combination of XPath and CSS3. This mix is to allow it to work well for looking for nodes in the html itself, as well as looking for nodes in xml documents. This is designed to be consisten
However, browsers have inconsistent support (I'm looking at you, IE) for namespaces, and so the XML module in GWT doesn't know how to talk about namespaces, and the DomQuery engine doesnt really either. Additionally, the : operator, which in XML means 'namespace', is used to mean 'psuedo-selector' in CSS, so the query language would be a little vague if it supported this directly: The string foo:bar could either mean "All elements with name foo that match psuedo-selector bar", or "All elements with name bar in the namespace foo".
So enough with the problem: whats the solution? At present, there isn't a good one for namespaced elements in IE6/IE7/IE8 - one part inconsistencies in the browsers and one part lack of ugly workaround in GXT means that you can't read out the elements directly. For all other browsers, to select elements like namespace:eltname, just use @PropertyName("eltname").
One other note: Due to the fact that attributes don't have psuedo-selectors, you can select them - @PropertyName("namespace:attrname") will correctly read out values in the attribute in <element namespace:.
* Add a specific operator for namespace (probably either the 'namespace-uri()' xpath method, or the | css namespace operator), or
* Make a specific XmlReader implementation for document traversal, so we don't need to deal with CSS
The first solution would either mean that you could read with XmlReader but not write with XmlWriter, or that we would use the mostly unknown | operator for namespaces - both of these seem to add maintainability problems, so I'm hesitant to consider them. The second solution would be a breaking change in the API, so would need to come at a minor release, and would require more work, so would need more time until it is ready.
|
http://www.sencha.com/forum/showthread.php?249236-Use-XmlReader-AutoBeans-to-parse-XML-that-has-attributes-in-the-element&p=912361&mode=threaded
|
CC-MAIN-2014-42
|
refinedweb
| 585
| 53.65
|
rudi 18 Posted January 12, 2013 (edited) Hi everybody, and a (late) Happy New Year!Reading up the help files I'm not sure, if I got the steps to open / use / disconnect / shutdown the TCP services correctly, server and client side.This is a basic draft, please correct me, if I missed something important, tx.Server side:expandcollapse popupTCPStartup() ; general startup of TCP services $MainSocket = TCPListen(@IPAddress1, 12345) ; create a listening socket TCP:12345 If $MainSocket = -1 Then Exit ; what causes this to fail? (beside 1=wrong IP, 2=wrong socket) Socket already in use? missing OS rights? Firewall restrictions? ;Help file: Wait for and Accept a connection ; this loops, until a client connects to this server? ; After the loop was left (first connection was made from a client), what will happen to a 2nd (3rd, ... ) connection attempt of ; another client (or the same client), when "server side" this loop isn't "watching" for incoming connections? Do $ConnectedSocket = TCPAccept($MainSocket) Until $ConnectedSocket <> -1 ; $ConnectedSocket is now representing a handle for exactly *ONE* client connect caught within the do ... until loop above ; Get IP of client connecting $szIP_Accepted = SocketToIP($ConnectedSocket) ; this is just informational. "Knowing" the client's IP address isn't required, is it? While $recv = TCPRecv($ConnectedSocket, 2048) ; reads data sent from the client currently connected ; If the receive failed with @error then the socket has disconnected ; Question: "...has disconnected", does that mean, that the client has closed the socket, or might this be a network error as well? If @error Then ExitLoop If $recv <> "" Then ; data were received, process them else ; no data were received: Will the socket stay open infinitely, when no data travel the socket connection? endif Wend ; the While ... wend is exited, if $TCPRecv() returned -1: ; What is this check of $ConnectedSocket good for? If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket) TCPShutdown() ; stop autoit script's TCP servicesClient side:TCPStartup() $ConnectedSocket = TCPConnect($Server_IP, 12345) ; connect to the listening port TCP:12345, "waiting" at the server above ; for the client socket number a random, available high port nuber is choosen automatically? if @error then exit ; 1=wrong ip, 2= wrong port. Connection refused?? (WSAECONNRESET = 10054 ??) Port closed? ; Now the client is connected to the server, and data can be send using the socket (?) $SendThis="some data to be send to the server" do TCPSend($ConnectedSocket, $SendThis) $Err=@error if $Err then ; do some error handling. What might show up here? Connection reset by peer, eg? What else to take care of? exitloop endif ; process more data to be send, if done, set $done=true until $done ; the helpfile example ends here for tcpsend() function (?) ; same like server side, this one, to do a "clean socket disconnet", that makes the server "recognize", that the client "has disconnected" ? If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket) TCPShutdown() ; will close down the Autoit used TCP services. ; Will a TCPShutdown() without TCPCloseSocket() make the server recognize the "client disconnected" situation?Regards, Rudi. Edited January 12, 2013 by rudi Earth is flat, pigs can fly, and Nuclear Power is SAFE! Share this post Link to post Share on other sites
|
https://www.autoitscript.com/forum/topic/147425-autoit-tcp-functions-how-to-use-correctly-order/
|
CC-MAIN-2018-43
|
refinedweb
| 517
| 54.93
|
Content
All Articles
Python News
Numerically Python
Python & XML
Community
Database
Distributed
Education
Getting Started
Graphics
Internet
OS
Programming
Scientific
Tools
Tutorials
User Interfaces
ONLamp Subjects
Linux
Apache
MySQL
Perl
PHP
Python
BSD
Cooking with Python, Part 2
Pages: 1, 2
Credit: David Eppstein, Tim Peters, Alex Martelli, Wim
Stolker, Kazuo Moriwaka, Hallvard Furuseth, Pierre Denis, Tobias
Klausmann, David Lees, Raymond Hettinger
You need to compute an unbounded
sequence of all primes, or the list of all primes that are less than
a certain threshold.
To compute an unbounded sequence, a generator is the natural Pythonic
approach, and the Sieve of Eratosthenes, using a dictionary as the
supporting data structure, is the natural algorithm to use:
import itertools
def eratosthenes( ):
'''Yields the sequence of prime numbers via the Sieve of Eratosthenes.'''
D = { } # map each composite integer to its first-found prime factor
for q in itertools.count(2): # q gets 2, 3, 4, 5, ... ad infinitum
p = D.pop(q, None)
if p is None:
# q not a key in D, so q is prime, therefore, yield it
yield q
# mark q squared as not-prime (with q as first-found prime factor)
D[q*q] = q
else:
# let x <- smallest (N*p)+q which wasn't yet known to be composite
# we just learned x is composite, with p first-found prime factor,
# since p is the first-found prime factor of q -- find and mark it
x = p + q
while x in D:
x += p
D[x] = p
To compute all primes up to a predefined threshold, rather than an
unbounded sequence, it's reasonable to wonder if
it's possible to use a faster way than good old
Eratosthenes, even in the smart variant shown as the
"Solution". Here is a function that
uses a few speed-favoring tricks, such as a hard-coded tuple of the
first few primes:
def primes_less_than(N):
# make `primes' a list of known primes < N
primes = [x for x in (2, 3, 5, 7, 11, 13) if x < N]
if N <= 17: return primes
# candidate primes are all odd numbers less than N and over 15,
# not divisible by the first few known primes, in descending order
candidates = [x for x in xrange((N-2)|1, 15, -2)
if x % 3 and x % 5 and x % 7 and x % 11 and x % 13]
# make `top' the biggest number that we must check for compositeness
top = int(N ** 0.5)
while (top+1)*(top+1) <= N:
top += 1
# main loop, weeding out non-primes among the remaining candidates
while True:
# get the smallest candidate: it must be a prime
p = candidates.pop( )
primes.append(p)
if p > top:
break
# remove all candidates which are divisible by the newfound prime
candidates = filter(p._ _rmod_ _, candidates)
# all remaining candidates are prime, add them (in ascending order)
candidates.reverse( )
primes.extend(candidates)
return primes
On a typical small task such as looping over all primes up to 8,192,
eratosthenes (on an oldish 1.2 GHz Athlon PC, with
Python 2.4) takes 22 milliseconds, while
primes_less_than takes 9.7; so, the slight
trickery and limitations of primes_less_than can
pay for themselves quite handsomely if generating such primes is a
bottleneck in your program. Be aware, however, that
eratosthenes scales better. If you need all primes
up to 199,999, eratosthenes will deliver them in
0.88 seconds, while primes_less_than takes 0.65.
eratosthenes
primes_less_than
Since primes_less_than's little
speed-up tricks can help, it's natural to wonder
whether a perhaps simpler trick can be retrofitted into
eratosthenes as well. For example, we might simply
avoid wasting work on a lot of even numbers,
concentrating on odd numbers only, beyond the initial
2. In other words:
2
def erat2( ):
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
And indeed, erat2 takes 16 milliseconds, versus
eratosthenes' 22, to get primes
up to 8,192; 0.49 seconds, versus
eratosthenes' 0.88, to get primes
up to 199,999. In other words, erat2 scales just
as well as eratosthenes and is always
approximately 25% faster. Incidentally, if you're
wondering whether it might be even faster to program at a slightly
lower level, with q = 3 to start, a while
True as the loop header, and a q += 2 at
the end of the loop, don't worry—the slightly
higher-level approach using
itertools'
count and islice functions is
repeatedly approximately 4% faster. Other languages may impose a
performance penalty for programming with higher abstraction, Python
rewards you for doing
If you're into one liners, you might want to study
the following:
def primes_oneliner(N):
aux = { }
return [aux.setdefault(p, p) for p in range(2, N)
if 0 not in [p%d for d in aux if p>=d+d]]
Be aware that one liners, even clever ones, are generally anything
but speed demons! primes_oneliner takes 2.9 seconds
to complete the same small task (computing primes up to 8,192) which,
eratosthenes does in 22 milliseconds, and
primes_less_than in 9.7--so,
you're slowing things down by 130 to 300 times just
for the fun of using a clever, opaque one liner, which is clearly not
a sensible tradeoff. Clever one liners can be instructive but should
almost never be used in production code, not just because
they're terse and make maintenance harder than
straightforward coding (which is by far the main reason), but also
because of the speed penalties they may entail.
While prime numbers, and number theory more generally, used to be
considered purely theoretical problems, nowadays they have plenty of
practical applications, starting with cryptography.
To explore both number theory and its applications, the best book is
probably Kenneth Rosen, Elementary Number Theory and Its
Applications (Addison-Wesley); for more
information about prime numbers.
Related Reading
Python Cookbook
By Alex Martelli, Anna Martelli Ravenscroft, David Ascher
Return to Python DevCenter.
Sponsored by:
© 2015, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
|
http://archive.oreilly.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2
|
CC-MAIN-2015-40
|
refinedweb
| 1,052
| 54.05
|
Applies to: C166 C Compiler
I have C166 compiler v1.13. Why is it impossible to use return(0); in a function which is declared as:
void function_name (void)
The reason for the error/warning message is because a void function, by definition, does not return a value. When you include the return (0) statement, you are saying that the function returns a value of 0. This presents the compiler with a contradicting declaration and return. So, the compiler generates an error.
Use return; instead of return(0); to exit a void function.
Article last edited on: 2004-06-07 09:46:32
Did you find this article helpful? Yes No
How can we improve this article?
|
http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka9099.html
|
CC-MAIN-2017-22
|
refinedweb
| 117
| 57.67
|
C Programming/Memory management
In C, you have already considered creating variables for use in the program. You have created some arrays for use, but you may have already noticed some limitations:
- the size of the array must be known beforehand
- the size of the array cannot be changed in the duration of your program
Dynamic memory allocation in C is a way of circumventing these problems.
Contents
Malloc[edit]
#include <stdlib.h> void *calloc(size_t nmemb, size_t size); void free(void *ptr); void *malloc(size_t size); void *realloc(void *ptr, size_t size);
The C function
malloc is the means of implementing dynamic memory allocation. It is defined in stdlib.h or malloc.h, depending on what operating system you may be using. Malloc.h contains only the definitions for the memory allocation functions and not the rest of the other functions defined in stdlib.h. Usually you will not need to be so specific in your program, and if both are supported, you should use <stdlib.h>, since that is ANSI C, and what we will use here.
The corresponding call to release allocated memory back to the operating system is
free.
When dynamically allocated memory is no longer needed,
free should be called to release it back to the memory pool. Overwriting a pointer that points to dynamically allocated memory can result in that data becoming inaccessible. If this happens frequently, eventually the operating system will no longer be able to allocate more memory for the process. Once the process exits, the operating system is able to free all dynamically allocated memory associated with the process.
Let's look at how dynamic memory allocation can be used for arrays.
Normally when we wish to create an array we use a declaration such as
int array[10];
Recall
array can be considered a pointer which we use as an array. We specify the length of this array is 10
ints. After
array[0], nine other integers have space to be stored consecutively.
Sometimes it is not known at the time the program is written how much memory will be needed for some data. In this case we would want to dynamically allocate required memory after the program has started executing. To do this we only need to declare a pointer, and invoke
malloc when we wish to make space for the elements in our array, or, we can tell
malloc to make space when we first initialize the array. Either way is acceptable and useful.
We also need to know how much an int takes up in memory in order to make room for it; fortunately this is not difficult, we can use C's builtin
sizeof operator. For example, if
sizeof(int) yields 4, then one
int takes up 4 bytes. Naturally,
2*sizeof(int) is how much memory we need for 2
ints, and so on.
So how do we
malloc an array of ten
ints like before? If we wish to declare and make room in one hit, we can simply say
int *array = malloc(10*sizeof(int));
We only need to declare the pointer;
malloc gives us some space to store the 10
ints, and returns the pointer to the first element, which is assigned to that pointer.
Important note!
malloc does not initialize the array; this means that the array may contain random or unexpected values! Like creating arrays without dynamic allocation, the programmer must initialize the array with sensible values before using it. Make sure you do so, too. (See later the function
memset for a simple method.)
It is not necessary to immediately call
malloc after declaring a pointer for the allocated memory. Often a number of statements exist between the declaration and the call to
malloc, as follows:
int *array = NULL; printf("Hello World!!!"); /* more statements */ array = malloc(10*sizeof(int)); /* delayed allocation */ /* use the array */
Error checking[edit]
When we want to use
malloc, we have to be mindful that the pool of memory available to the programmer is finite. As such, we can conceivably run out of memory! In this case,
malloc will return
NULL. In order to stop the program crashing from having no more memory to use, one should always check that malloc has not returned
NULL before attempting to use the memory; we can do this by
int *pt = malloc(3 * sizeof(int)); if(pt == NULL) { fprintf(stderr, "Out of memory, exiting\n"); exit(1); }
Of course, suddenly quitting as in the above example is not always appropriate, and depends on the problem you are trying to solve and the architecture you are programming for. For example, if the program is a small, non critical application that's running on a desktop quitting may be appropriate. However if the program is some type of editor running on a desktop, you may want to give the operator the option of saving their tediously entered information instead of just exiting the program. A memory allocation failure in an embedded processor, such as might be in a washing machine, could cause an automatic reset of the machine. For this reason, many embedded systems designers avoid dynamic memory allocation altogether.
The
calloc function[edit]
The
calloc function allocates space for an array of items and initilizes the memory to zeros. The call
mArray = calloc( count, sizeof(struct V)) allocates
count objects, each of whose size is sufficient to contain an instance of the structure
struct V. The space is initialized to all bits zero. The function returns either a pointer to the allocated memory or, if the allocation fails,
NULL.
The
realloc function[edit]
void * realloc ( void * ptr, size_t size );
The
realloc function changes the size of the object pointed to by
ptr to the size specified by
size. The contents of the object shall be unchanged up to the lesser of the new and old sizes. If the new size is larger, the value of the newly allocated portion of the object is indeterminate. If
ptr is a null pointer, the
realloc function behaves like the
malloc function for the specified size. Otherwise, if
ptr does not match a pointer earlier returned by the
calloc,
malloc, or
realloc function, or if the space has been deallocated by a call to the
free or
realloc function, the behavior is undefined. If the space cannot be allocated, the object pointed to by
ptr is unchanged. If
size is zero and
ptr is not a null pointer, the object pointed to is freed. The
realloc function returns either a null pointer or a pointer to the possibly moved allocated object.
The
free function[edit]
Memory that has been allocated using
malloc,
realloc, or
calloc must be released back to the system memory pool once it is no longer needed. This is done to avoid perpetually allocating more and more memory, which could result in an eventual memory allocation failure. Memory that is not released with
free is however released when the current program terminates on most operating systems. Calls to
free are as in the following example.
int *myStuff = malloc( 20 * sizeof(int)); if (myStuff != NULL) { /* more statements here */ /* time to release myStuff */ free( myStuff ); }
free with recursive data structures[edit]
It should be noted that
free is neither intelligent nor recursive. The following code that depends on the recursive application of free to the internal variables of a struct does not work.
typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; // Later: ... BSTNode* temp = (BSTNode*) calloc(1, sizeof(BSTNode)); temp->left = (BSTNode*) calloc(1, sizeof(BSTNode)); // Later: ... free(temp); // WRONG! don't do this!
The statement "
free(temp);" will not free
temp->left, causing a memory leak. The correct way to free the allocated memory is as follows.
free(temp->left); free(temp->right); free(temp);
Because C does not have a garbage collector, C programmers are responsible for making sure there is a
free() exactly once for each time there is a
malloc(). If a tree has been allocated one node at a time, then it needs to be freed one node at a time.
Don't free undefined pointers[edit]
Furthermore, using
free when the pointer in question was never allocated in the first place often crashes or leads to mysterious bugs further along.
To avoid this problem, always initialize pointers when they are declared. Either use
malloc at the point they are declared (as in most examples in this chapter), or set them to
NULL when they are declared (as in the "delayed allocation" example in this chapter). [1]
Write constructor/destructor functions[edit] */
|
https://en.wikibooks.org/wiki/C_Programming/Memory_management
|
CC-MAIN-2017-34
|
refinedweb
| 1,429
| 52.19
|
01 February 2010 23:20 [Source: ICIS news]
HOUSTON (ICIS news)--US major Dow Chemical may have lined up a private-equity firm to buy its styrene group, Styron, producers and traders said on Monday, the day before the company's fourth-quarter earnings announcement.
A producer said it was unlikely that any company would want to buy the assets to restart them, however, given the overcapacity of ?xml:namespace>
Among the names market players said were on a short list of possible buyers were Apollo Management, Bain Capital, BlackRock, the Lotte Group, TPG Capital and the Rhone Group.
An earlier report said that the Lotte Group was one of eight bidders.
Apollo, Bain and TPG declined to comment. Lotte and
Dow Chemical did not immediately return calls seeking comment.
Earlier Dow had said that it expected to close on the Styron sale in the first quarter.
Market participants said Dow may discuss Styron during Tuesday's earnings announcement.
Dow chief executive Andrew Liveris estimated Styron’s value at $1bn-2bn (€720m-1.44bn) in August.
Styron includes.
(
|
http://www.icis.com/Articles/2010/02/01/9330719/market-talk-rises-on-possible-buyer-for-dows-styron.html
|
CC-MAIN-2015-11
|
refinedweb
| 178
| 54.52
|
hi all,
i need to get all the data in the list (which is posted in the form) and store it, separating each list item with comma's. Its really clear in the code...this is what ive tried so far..it doesnt compile and it seems to complain about this line of code photos = form["photolist"]...thanks for any help
html form--->add.html
<form name="listadd" method=post action=addDo.cgi> <select name="photolist" size="9" style="width: 500; height: 50"></select> <input type="submit"> </form>
python cgi script--->addDo.cgi
import cgitb; cgitb.enable() import cgi import sys form = cgi.FieldStorage() photos = form["photolist"] i=0 for photo in photos: i = i + 1 finalPhoto = finalPhoto + "," + photo[i]
|
https://www.daniweb.com/programming/software-development/threads/22312/get-posted-form-data-in-python
|
CC-MAIN-2018-17
|
refinedweb
| 120
| 70.09
|
Padre::DB::Session - Padre::DB class for the session table
my @sessions = Padre::DB::Session->select;
This class allows storing in Padre's database the session that Padre knows. This is useful in order to quickly restore a given set of files.
This is the primary table, you also need to check
Padre::DB::SessionFiles.
my $session = last_padre_session()
Return a
Padre::DB::Session object pointing to last Padre session. If none exists, a new one will be created and returned.
my @files = $session->files
Return a list of files (
Padre::DB::SessionFile objects) referenced by current
$session.
# Returns 'Padre::DB' my $namespace = Padre::DB::Session- 'session' print Padre::DB::Session->table;
While you should not need the name of table for any simple operations, from time to time you may need it programatically. If you do need it, you can use the
table method to get the table name.
my $object = Padre::DB::Session-::Session object, or throws an exception if the object does not exist.
#.
Padre::DB::Session-::Session->select ) { print $_->id . "\n"; }
You can filter the list via SQL in the same way you can with
Padre::DB::Session- session order by id', sub { print $_->[0] . "\n"; } );
# How many objects are in the table my $rows = Padre::DB::Session->count; # How many objects my $small = Padre::DB::Session->count( 'where id > ?', 1000, );
The
count method executes a
SELECT COUNT(*)::Session session table Padre::DB::Session-->id ) { print "Object has been inserted\n"; } else { print "Object has not been inserted\n"; }
Returns true, or throws an exception on error.
REMAINING ACCESSORS TO BE COMPLETED
The session table was originally created with the following SQL command.
CREATE TABLE session ( id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(255) UNIQUE NOT NULL, description VARCHAR(255), last_update DATE )
Padre::DB::Session.
|
http://search.cpan.org/~plaven/Padre-1.00/lib/Padre/DB/Session.pm
|
CC-MAIN-2017-43
|
refinedweb
| 301
| 54.32
|
Search: Search took 0.03 seconds.
- 8 Oct 2010 2:01 AM
Inside the drag start of panel 1 , I don't know How can I get the element ( source and component var are equals to ContentPanel)
- 8 Oct 2010 1:56 AM
Thank you for your quickly answer.
How can I cancel the drag interaction of the panel 1 ?
Maybe, It's means that the drag source of Html know the dragsource of panel ?
- 8 Oct 2010 1:09 AM
Hi,
I have a problem with draggable elements :
I have a panel draggable which contains a Html element draggable too.
This 2 elements can be drag into a second panel with a drop target.
When...
- 6 Oct 2010 12:58 AM
- Replies
- 1
- Views
- 2,070
Hi everybody,
I would like to know if GXT training exist ? (In France)
Thank you
- 29 Jul 2010 12:57 AM
Thank you!
You are right, I forgot to search before post my question ... sorry
- 28 Jul 2010 8:44 AM
Thank you
Must We have the commercial Licence to get it ?
- 28 Jul 2010 8:40 AM
Hi,
Do you know the release date of Ext GWT 2.2 ?
Thank you
- 18 Jun 2010 7:01 AM
- Replies
- 1
- Views
- 1,011
Hi,
I would like to know if some advanced functionnalities for Data Grid exists in GXT (in the free version or in the commercial version):
- Column draggable
- Filter on column (Filter field...
- 3 Jun 2010 11:46 PM
No answer .......
- 31 May 2010 8:40 AM
- Replies
- 4
- Views
- 1,909
I found the origin of the problem
My panel doesn't contain classic component but my own component which extend composite (of GWT librairie)
My component :
public class ComplexField extends...
- 31 May 2010 5:50 AM
- Replies
- 4
- Views
- 1,909
All children of the panel in order to have a "blank" panel ...
- 31 May 2010 5:46 AM
- Replies
- 4
- Views
- 1,909
Hi,
I would like to knwo how can I remove a component from a panel:
I try this :
ContentPanel cp = (ContentPanel) this.getWidget();
cp.removeAll();
cp.layout();
- 14 May 2010 4:26 AM
Anyone can help me please ?
- 12 May 2010 1:25 PM
I try with the example provided on the web site. I just had a doubleClick Listener:
RootPanel root = RootPanel.get();
root.setSize("1200px", "800px");
LayoutContainer global =...
- 12 May 2010 8:08 AM
Hi,
I have a problem with LiveGrid and double click listener.
In the begining of my test, I had a Grid based on a grouping store with a grouping view. I attached a DoubleClick Listener. When I...
- 11 May 2010 1:19 AM
Thank you for your answer.
I Hope that this problem disappear with your version
- 11 May 2010 1:11 AM
Thank you for your answer
What is your version of GXT please ?
- 11 May 2010 12:44 AM
Hi,
About versions used :
FireFox 3.6
GWT 2.0.3
GXT 2.1.1
Thank you
- 10 May 2010 2:30 AM
Anyone can help me ?
We are in a testing phase of GXT before making a company choice and browsers compatibility problem is for us a very serious problem.
- 10 May 2010 2:20 AM
- Replies
- 2
- Views
- 893
Hi Sven,
I build a testcase:
EntryPoint :
private final EKIPServiceAsync service = GWT
.create(EKIPService.class);
- 10 May 2010 12:56 AM
- Replies
- 2
- Views
- 893
Hi,
I use ComboBox which are filled by a service calling. But, on IE6, I Have a Javascript error when I click on the comboBox for the first Time:
'shim' has a Null Value or isn't an object
...
- 9 May 2010 11:34 PM
Hi,
I Have a problem with the window component on Firefox. Its works perfectly on IE6 and Chrome
My problem is when I build my own window compenent with some textfield, numberfield,... : If I...
- 23 Apr 2010 4:34 AM
- Replies
- 1
- Views
- 1,359
Solved !
textField = new TextField<String>();
textField.addListener(Events.Change, new Listener<BaseEvent>() {
@Override
public void handleEvent(BaseEvent...
- 23 Apr 2010 2:57 AM
- Replies
- 1
- Views
- 1,359
Hi,
I try to make a personnal composite for currency field with one label
I create a Java Class extended Composite.
I try to use a afteredit listener for formatting text in the field. But,...
- 22 Apr 2010 1:52 AM
Jump to post Thread: Build UI dynamic after RPC call by Kirua007
- Replies
- 2
- Views
- 1,183
It's works.:))
Thank you.
Results 1 to 25 of 34
|
https://www.sencha.com/forum/search.php?s=fb6bc6ba3bdd7a4b8cdb861c11e06b62&searchid=13303257
|
CC-MAIN-2015-48
|
refinedweb
| 755
| 80.01
|
Hello every one. I just got XP and I installed Visual Studio 6.0 on my computer. When I opened Visual C++ 6.0 I wanted to compile a free-bug error code. Then I checked it with a regular simple code like the "Hello World" program. It didnt't work. It said an error. Why?? It was a simple code that every code should have compiled. Well, if need here is the code I put:
And here comes the error from Visual C++ 6.0 :And here comes the error from Visual C++ 6.0 :Code:#include <iostream> using namespace std; int main() { cout<<"Hello World!"<<endl; return 0; }
Please can anyone help me?? I don't want a good compiler wasted along with a lot of money. Thankyou!Please can anyone help me?? I don't want a good compiler wasted along with a lot of money. Thankyou!Code:--------------------Configuration: Code - Win32 Debug------------------- Compiling... Code.cpp Linking... libcpd.lib(wiostrea.obj) : fatal error LNK1143: invalid or corrupt file: no symbol for comdat section 0x105 Error executing link.exe. Code.exe - 1 error(s), 0 warning(s)
|
http://cboard.cprogramming.com/cplusplus-programming/65907-problem-visual-cplusplus-6-0-a.html
|
CC-MAIN-2014-35
|
refinedweb
| 188
| 79.56
|
.
These functions are declared in the header file `gsl_odeiv.h'._system
datatype.
int (* function) (double t, const double y[], double dydt[], void * params)
int (* jacobian) (double t, const double y[], double * dfdy, double dfdt[], void * params);
J(i,j) = dfdy[i * dimension + j]where
dimensionis the dimension of the system. Some of the simpler solver algorithms do not make use of the Jacobian matrix, so it is not always strictly necessary to provide it (the
jacobianelement of the struct can be replaced by a null pointer for those algorithms). However, it is useful to provide the Jacobian to allow the solver algorithms to be interchanged -- the best algorithms make use of the Jacobian.
size_t dimension;
void * params
The lowest level components are the stepping functions which advance a solution from time t to t+h for a fixed step-size h and estimate the resulting local error.
printf ("step method is '%s'\n", gsl_odeiv_step_name (s));
would print something like
step method is 'rk4'.
The following algorithms are available,
The control function examines the proposed change to the solution and its error estimate'_i|)
and comparing it with the observed error E_i = |yerr_i|. If the observed error E exceeds the desired error level D by more than 10% for any component then the method reduces the step-size by an appropriate factor,
h_new = h_old * S * (D/E)^(1/q)
where q is the consistency order of method (e.g. q=4 for 4(5) embedded RK), and S is a safety factor of 0.9. The ratio D/E is taken to be the maximum of the ratios D_i/E_i.
If the observed error E is less than 50% of the desired error level D for the maximum ratio D_i/E_i then the algorithm takes the opportunity to increase the step-size to bring the error in line with the desired level,
h_new = h_old * S * (E/D)^(1/(q+1))
This encompasses all the standard error scaling methods.
gsl_odeiv_control_standard_newbut with an absolute error which is scaled for each component by the array scale_abs. The formula for D_i for this control object is,
D_i = eps_abs * s_i + eps_rel * (a_y |y_i| + a_dydt h |y'_control_name (c));
would print something like
control method is 'standard'
The highest level of the system is the evolution function which combines the results of a stepping function and control function to reliably advance the solution forward over an interval (t_0, t_1). If the control function signals that the step-size should be decreased the evolution function backs out of the current step and tries the proposed smaller step-size. This process is continued until an acceptable step-size is found.
The following program solves the second-order nonlinear Van der Pol oscillator equation,
x"(t) + \mu x'(t) (x(t)^2 - 1) + x(t) = 0
This can be converted into a first order system suitable for use with the routines described in this chapter by introducing a separate variable for the velocity, y = x'(t),
x' = y y' = -x + \mu y (1-x^2)
The program begins by defining functions for these derivatives and their Jacobian,
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv) {; }
The main loop of the program evolves the solution from (y, y') = (1, 0) at t=0 to t=100. The step-size h is automatically adjusted by the controller to maintain an absolute accuracy of 10^{-6} in the function values y.
To obtain the values at regular intervals, rather than the variable spacings chosen by the control function, the main loop can be modified to advance the solution from one point to the next. For example, the following main loop prints the solution at the fixed points t = 0, 1, 2, \dots, 100,
for (i = 1; i <= 100; i++) { double ti = i * t1 / 100.0; while (t < ti) { gsl_odeiv_evolve_apply (e, c, s, &sys, &t, ti, &h, y); } printf ("%.5e %.5e %.5e\n", t, y[0], y[1]); }
It is also possible to work with a non-adaptive integrator, using only
the stepping function itself. The following program uses the
rk4
fourth-order Runge-Kutta stepping function with a fixed stepsize of
0.01,
int main (void) { const gsl_odeiv_step_type * T = gsl_odeiv_step_rk4; gsl_odeiv_step * s = gsl_odeiv_step_alloc (T, 2); double mu = 10; gsl_odeiv_system sys = {func, jac, 2, &mu}; double t = 0.0, t1 = 100.0; double h = 1e-2; double y[2] = { 1.0, 0.0 }, y_err[2]; double dfdy[4], dydt_in[2], dydt_out[2]; /* initialise dydt_in */ GSL_ODEIV_JA_EVAL(&sys, t, y, dfdy, dydt_in); while (t < t1) { int status = gsl_odeiv_step_apply (s, t, h, y, y_err, dydt_in, dydt_out, &sys); if (status != GSL_SUCCESS) break; dydt_in[0] = dydt_out[0]; dydt_in[1] = dydt_out[1]; t += h; printf ("%.5e %.5e %.5e\n", t, y[0], y[1]); } gsl_odeiv_step_free (s); return 0; }
The derivatives and jacobian must be initialised for the starting point t=0 before the first step is taken. Subsequent steps use the output derivatives dydt_out as inputs to the next step by copying their values into dydt_in.
Many of the basic Runge-Kutta formulas can be found in the Handbook of Mathematical Functions,
The implicit Bulirsch-Stoer algorithm
bsimp is described in the
following paper,
Go to the first, previous, next, last section, table of contents.
|
http://linux.math.tifr.res.in/programming-doc/gsl/gsl-ref_25.html
|
CC-MAIN-2017-39
|
refinedweb
| 871
| 55.58
|
Now that you hopefully have the required supplies (Raspberry Pi, male-female jumper wires, bread-board, resistor and LED light), you're ready to tackle a basic example of using GPIO (General Purpose Input Output).
Because we're using multiple devices here, it may be a bit confusing with how we're communicating with the Raspberry Pi at times. There are many options here, though you will be required to eventually be comfortable with using SSH (Secure Shell)/the terminal or at the very least a remote desktop application like XRDP. Click on either if you're confused.
XRDP is a remote-desktop application that you can use with your Raspberry Pi and the remote desktop functionality of operating systems like Windows.
SSH, or Secure Shell, is a method for connecting to a device's "terminal." SSH is a protocol, and the terminal is the command prompt equivalent of a linux machine. This is known as interacting with the machine "headless," meaning without a GUI. There are many basic commands to learn for this, but I will just put a few below:
# make a directory: mkdir newdirname # change directory: cd whatdir # list items in dir ls #create or open a file: nano filename # Root dir symbol, you can use this to cd to the root dir quickly with something like: cd ~ ~
You can either interact with the terminal remotely with the Raspberry Pi using something like XRDP (remote desktop), which still gives you the GUI, or you can also use SSH. A popular program for SSH is called Putty. You use this to connect remotely to the Raspberry Pi. To do it, you will just need the IP address for your Raspberry Pi, usually this is just the local IP Address. Something like 192.168.X.X is what it will look like. You can find your Raspberry Pi's IP address by typing "ifconfig" in the terminal. You will be asked for a username and password to connect. Default username: pi, default password: raspberry.
This video assumes, initially, you are using XRDP or you are connected with a mouse, keyboard and monitor to the Raspberry Pi.
First, to use GPIO, you will need to make sure you have the packages necessary on your Raspberry Pi. Via the Pi terminal, type:
sudo apt-get install python-rpi.gpio
Once you have that, you're ready to code with GPIO.
Now, open up a Python script from the desktop.
Our first program is going to act like a door with a password. The idea is that, if the LED light is "on," then the door is locked. In order to get the light to turn off and the "lock" to unlock, we need to enter a correct password.
import RPi.GPIO as gpio import time
First, we just import RPi.GPIO as gpio for some short-hand, then we import time so we can make the program sleep for a moment.
gpio.setmode(gpio.BCM) gpio.setup(18, gpio.OUT)
Here we are setting the mode to BCM, which is the naming convention for the GPIO pins. You can either address the pins by their actual physical pin number, or their "name" assigned to them. In order to be as careful as possible, it's best to explicitly check which you are doing.
while True: gpio.output(18, gpio.HIGH) passcode = raw_input("What is pi?: ")
while True is an infinite loop that will just always run, we are setting the output in to high, and then asking the user to input the password.
GPIO pins have "HIGH" or "LOW," which can be thought of as a 1 or a 0 value. On or off. They can also either be input or output. Input pins will "read" either a high or low value, and then output pins will actually push out a high or low signal.
if passcode == "Awesome": gpio.output(18, gpio.LOW) time.sleep(4)
We're assuming here the password is "Awesome." If that is what the user enters, then we set the output pin to low, which will turn off the LED light for 4 seconds.
else: gpio.output(18, gpio.HIGH) print("Wrong Password!")
If the password is not "Awesome," then the console will output that the password is wrong and continue the high signal.
The entire script is:
import RPi.GPIO as gpio import time gpio.setmode(gpio.BCM) gpio.setup(18, gpio.OUT) while True: gpio.output(18, gpio.HIGH) passcode = raw_input("What is pi?: ") if passcode == "Awesome": gpio.output(18, gpio.LOW) time.sleep(4) else: gpio.output(18, gpio.HIGH) print("Wrong Password!")
Now that we have the program, let's cover actually implementing it with the Raspberry Pi. Save the file to /home/pi/gpioexample.py
|
https://pythonprogramming.net/gpio-example-raspberry-pi/
|
CC-MAIN-2019-26
|
refinedweb
| 794
| 73.88
|
xlsx files produced in some environments are incompatible/invalid
I recently came across an issue where openpyxl on my dev machine was producing perfectly valid xlsx files, but the same code was producing incompatible xlsx files on my staging server.
I traced this down to my staging server having lxml installed while my dev machine did not. After installing lxml on my dev machine it started producing the same (seemingly) invalid xlsx files.
These xlsx files are completely rejected by Numbers. Libreoffice does open them. And according to a colleague Excel does open them but (sometimes) displays a warning. I don't think the testing code listed below produces warnings in Excel, but if necessary I could probably (in time) give more thorough testing code which does.
I diffed the xlsx packages produced with and without lxml, and from a cursory exploration it seems that the only difference is the way namespaces are handled, but I could easily be wrong about that.
Dev Env:
OS X 10.9.1, python 2.7.5, openpyxl 1.8.0, lxml 3.2.5
Staging Env:
Ubuntu 12.04.2, python 2.7.3, openpyxl 1.8.0, lxml 2.3.2
Testing Code:
Looks like a horribly outdated version of lxml on your staging server and you really ought to update it. Any reason you're not using a virtualenv on your staging server?
You can prevent openpyxl from using lxml by setting
LXML = FALSEin `openpyxl/init.py``
But, in your case, it's probably best either to remove or update lxml. I guess it might be possible to add a check for
lxml >= 3.xto the code, but really you should be managing dev and staging environments so that they are as close as possible.
I tried to be clear that the issue is also reproducible on my dev machine with the latest version of lxml installed. There are reasons for the super old lxml on staging, but since the issue also exists with lxml 3.2.5 I don't think this is relevant.
I tried doing this dynamically and it didn't work:
I assume because openpyxl imports all (or most) of its submodules automatically, which then read LXML before I can change it.
Are you suggesting that I update the source code of openpyxl? That's not a reasonable solution for me when it's much easier to just use xlsxwriter instead. It would be great to only use one library for xlsx processing, but using two is better than using an unsupported fork of one.
I have the same dev environment so I know the generated files are okay. The file
test-with-lxml.xlsxis fine (Excel 2010 on Mac OS 10.9.1)
On your staging server if you use a virtualenv without system packages then lxml will not be available. Otherwise, assuming you can install from source then you can set the environment variable OPENPYXL_LXML to False to prevent it being used.
Merge in changes on handling lxml. Resolves
#252
→ <<cset 524dcfdf2a04>>
1.8.2 has now been released. Can you let us know whether it fixes the problem? It should give a warning that the version of lxml in use is too old and not use it.
|
https://bitbucket.org/openpyxl/openpyxl/issues/252
|
CC-MAIN-2019-04
|
refinedweb
| 543
| 66.74
|
Nmap Development
mailing list archives
Hello devs,
I have two ideas for NSE, I will keep these brief for now but based on
the response I may flesh this ideas out further.
- NSE for Ncat
NSE is extremely useful for rapidly writing simple network programs,
currently this programmers are attached to the Nmap scanning engine
even if they do not benefit from a port scan. NSE for Ncat would allow
the same fine grained control but without all the overhead of being
reliant on the network scanner. I imagine this would be best
implemented by the addition of a new library which would be used by
both Ncat and Nmap. Nmap would load the library and then add any Nmap
dependent API(such as the Nmap namespace), and Ncat would do the same.
- Data structure standards for NSE output
Currently scripts return a string, while the string is excellent for
human consumption it isn't a very elegant solution. I propose using
tables to express output in a form that is palpable for both humans
and an XML parser. For example.
Strings:
output = "Port: 80\nServer: HTTP\nServer Status: Online"
->String as XML
<script id="test-script" output="Port: 80
Server: HTTP
Server
Status: Online
/>
Tables:
output = {
Port="80",
Server="HTTP"
Status="Online"
}
->Table as XML
<script id="test-script"><data name="Port">80</data><data
name="Server">HTTP</data><data name="Status">Online</data></script>
Not only is this method easier for computers to read, its also nicer
to look at (no ugly
) and can easily be converted to a string for
standard output.
As per above, please respond if you hold any strong opinion on these
two ideas, for or against them.
Cheers,
Michael Pattrick
_______________________________________________
Sent through the nmap-dev mailing list
Archived at
By Date
By Thread
|
http://seclists.org/nmap-dev/2009/q2/841
|
CC-MAIN-2014-41
|
refinedweb
| 301
| 52.02
|
We know that one can set attributes of a function like this:
def foo():
pass
foo.__setattr__("nameattr","myname")
def foo():
#self.__setattr__("nameattr","myname")
pass
You can just put the assignment inside the body of the function:
def foo(): foo.nameattr = value
Or:
def foo(): setattr(foo, "nameattr", value)
There is no need to explicitly call
__setattr__.
Note however that this will set the attribute everytime you call the function, moreover you must call the function for this to work:
>>> a = 1 >>> def foo(): ... global a ... foo.a = a ... >>> foo.a Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'function' object has no attribute 'a' >>> foo() >>> foo.a 1 >>> a = 2 >>> foo.a 1 >>> foo() >>> foo.a 2
As you can see the attribute is not set if you don't call the function before accessing it. Moreover at everycall the value could change.
If you want to just set the attribute once you could use a decorator.
It would be nice to be able to just use
partial with
setattr, but unfortunately
setattr uses positional-only arguments. But we can write our own wrapper:
from functools import partial def set_attribute(object, name, value): setattr(object, name, value) @partial(set_attribute, name="a", value=1) def foo(): pass print(foo.a) # -> 1
|
https://codedump.io/share/BF3OWVBrqBPX/1/how-to-set-attributes-of-a-function-when-defining-this-function
|
CC-MAIN-2017-39
|
refinedweb
| 216
| 64.81
|
Red Hat Bugzilla – Bug 86339
Update to glibc-2.3.2-4.80 breaks SSH
Last modified: 2016-11-24 09:49:16 EST
Description of problem:
After Upgrade to glibc-2.3.2-4.80 as per the RHSA-2003:089 - Security Advisory,
sshd will disconnect remote connections after providing the username.
No errors are logged in /var/log.
Version-Release number of selected component (if applicable):
glibc-2.3.2-4.80
How reproducible:
Upgrade to glibc-2.3.2-4.80 and attempt to ssh to the server from a remote client.
Steps to Reproduce:
1. Update/Update to glibc-2.3.2-4.80
2. SSH to remote server
Actual results:
After providing a valid username the connection is immediately closed.
If an invalid or nonexistant username is entered, the password is requested.
Expected results:
Password is requested, and upon correct authentication, connection is fully
established
Additional info:
You can fix this problem temporarily by entering the host name and IP address of
the remote client into /etc/hosts.
This seems to be very similar to the bug with MYSQL on RH8, Bug 77467.
This also affects connections to Sendmail, and any other service that does a
reverse DNS lookup?
Have you rebooted the server in between, or at least restarted all services
which use NSS lookup after they have been started (e.g. service sshd restart)
after the upgrade?
Yes, restarting the SSH service appears to allow the connection, and clears this
particular bug.
However, I used RHN to upgrade this server. It is my understanding that the
glibc upgrade would have been applied automatically, if I had not run up2date
manually?
If so, this would have prevented me from connecting to the server remotely via
SHH in order to restart the service and fix the problem.
Maybe glibc should be on the pkgSkipList of up2date? Or should the services
mentioned been restarted by up2date?
I had a an identical problem, but it was solved by doing 'service sshd restart'
Same with me - I had to physically walk to over a 100 machines in my dept and
restart sshd.. would have been nice to have been warned!
Tim makes a good point. Besides the suggestion for not installing
automatically, the errata page
() should mention which services
you need to restart or that you should reboot the system after installing this
update. Perhaps a separate bug should be filed against the errata page.
Associated bug filed against the errata page:
It should be possible to restart services via RHN (not just schedule a reboot). This applies even if the errata says what services to restart, since it may be inconvenient to do that semimanually for a big number of servers.
(Or maybe a pair of running shoes should be included in the RHN subscription? :-))
This appears to be a wide-reaching problem with symbol resolution in the new
glibc package and will break anything that e.g. hasn't already go the
libnss_dns.so loaded and tries to load it - it has the old glibc .so image, the
new libnss* images, and they conflict:
[pid 20911] open("/lib/libnss_dns.so.2", O_RDONLY) = 3
[pid 20911] read(3, "<snip>"..., 1024) = 1024
[pid 20911] fstat64(3, {st_mode=S_IFREG|0755, st_size=16700, ...}) = 0
[pid 20911] old_mmap(NULL, 12704, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) =
[pid 20911] mprotect(0x40359000, 416, PROT_NONE) = 0
[pid 20911] old_mmap(0x40359000, <snip>) = 0x40359000
[pid 20911] close(3) = 0
[pid 20911] munmap(0x40345000, 67073) = 0
[pid 20911] writev(2, [{"/usr/sbin/sshd", 14}, {": ", 2}, {"relocation error",
16}, {": ", 2}, {"/lib/libnss_dns.so.2", 20}, {": ", 2}, {"symbol
__libc_res_nquery, versio"..., 107}, {"", 0}, {"", 0}, {"\n", 1}], 10) = 164
* 14 bytes in buffer 0
| 00000 2f 75 73 72 2f 73 62 69 6e 2f 73 73 68 64 /usr/sbi n/sshd |
* 2 bytes in buffer 1
| 00000 3a 20 : |
* 16 bytes in buffer 2
| 00000 72 65 6c 6f 63 61 74 69 6f 6e 20 65 72 72 6f 72 relocati on error |
* 2 bytes in buffer 3
| 00000 3a 20 : |
* 20 bytes in buffer 4
| 00000 2f 6c 69 62 2f 6c 69 62 6e 73 73 5f 64 6e 73 2e /lib/lib nss_dns. |
| 00010 73 6f 2e 32 so.2 |
* 2 bytes in buffer 5
| 00000 3a 20 : |
* 107 bytes in buffer 6
| 00000 73 79 6d 62 6f 6c 20 5f 5f 6c 69 62 63 5f 72 65 symbol _ _libc_re |
| 00010 73 5f 6e 71 75 65 72 79 2c 20 76 65 72 73 69 6f s_nquery , versio |
| 00020 6e 20 47 4c 49 42 43 5f 50 52 49 56 41 54 45 20 n GLIBC_ PRIVATE |
| 00030 6e 6f 74 20 64 65 66 69 6e 65 64 20 69 6e 20 66 not defi ned in f |
| 00040 69 6c 65 20 6c 69 62 72 65 73 6f 6c 76 2e 73 6f ile libr esolv.so |
| 00050 2e 32 20 77 69 74 68 20 6c 69 6e 6b 20 74 69 6d .2 with link tim |
| 00060 65 20 72 65 66 65 72 65 6e 63 65 e refere nce |
Guys - do you even *test* these packages before you ship them?
I had similar problems with a PAM module we wrote here. Odd thing is, the disconnect behavior went away if we started nscd. It looks to us like somehow the gethostby* execution path gets hardwired to thinking nscd is available. I haven't tried mass reboots yet.
And rebooting fixes the problem.
For what it's worth, if you do the glibc upgrade without a reboot, the following
pam code snippet will fail (if nscd is not running). It would be nice if
checking for this could make it into the test suite somehow.
#include <sys/cdefs.h>
#include <stddef.h>
#include <syslog.h>
#include <netdb.h>
#define PAM_SM_AUTH
#include <security/pam_appl.h>
#include <security/pam_modules.h>
PAM_EXTERN int
pam_sm_authenticate(pam_handle_t *pamh, int flags,
int argc, const char *argv[])
{
struct hostent *hp;
if ((hp = gethostbyname("")) == NULL)
return (PAM_AUTH_ERR);
return (PAM_SUCCESS);
}
PAM_EXTERN int
pam_sm_setcred(pam_handle_t *pamh, int flags,
int argc, const char *argv[])
{
return (PAM_SUCCESS);
}
#ifdef PAM_STATIC
struct pam_module _pam_brokencrud_modstruct = {
"pam_brokencrud",
pam_sm_authenticate,
pam_sm_setcred,
NULL,
NULL,
NULL,
NULL,
};
#endif
I've added sshd condrestart to
I think sshd is special in that when sshd is not restarted and you don't have
physical access, you cannot restart the rest of services or reboot.
Problem with enlarging the list of services to restart is that it will never be
complete anyway, the only 100% way of finishing glibc upgrade is either
reboot, or telinit 1; telinit 5 (but neither of this can be done from glibc %post).
Otherwise some apps still have old copies of glibc and some new copies;
especially with security erratas that's something that should be avoided..
|
https://bugzilla.redhat.com/show_bug.cgi?id=86339
|
CC-MAIN-2017-17
|
refinedweb
| 1,134
| 70.02
|
Hi Maeda-san, Bjorn, Although the ACPI spec says that SCI is 'active-low, level' interrupt, there are many platforms that doesn't follow the rule (what I've seen are almost active-high, level). I think Maeda-san's case is just a wrong polarity. Usually those platforms would describe the polarity and trigger of SCI in 'interrupt source override' record in the ACPI MADT table. The polarity and trigger are programmed in iosapic when MADT parsing is done, so we don't want to force 'ACPI_ACTIVE_LOW, ACPI_LEVEL_SENSITIVE' when SCI is enabled. So maybe acpi_register_gsi() would take only one argument (u32 gsi) and the acpi_register_gsi() by itself will derive polarity and trigger from override table or iosapic_intr_info[]? From: MAEDA Naoaki <maeda.naoaki@jp.fujitsu.com> Subject: Re: [RFC] ACPI IRQ proposal Date: Fri, 26 Mar 2004 14:39:30 +0900 (JST) > Hi, Bjorn. > > I've tried your patch in tiger4, but it causes spurious acpi interrupts, > and finally the IRQ is disabled by note_interrupt(). > > I guess the difference causing this problem is your patch enables the acpi > interrupt on acpi_register_gsi() called by acpi_os_install_interrupt_handler(), > but original acpi_os_install_interrupt_handler() calls acpi_irq_to_vector(), > which does not enable the interrupt, instead. > > I am not sure the reason, but probably the enabling timing is too early > for the acpi interrupt. > > Didn't you hit this problem? > > Thanks, > Naoaki Maeda > > ------- Original code > #if defined(CONFIG_IA64) || defined(CONFIG_PCI_USE_VECTOR) > irq = acpi_irq_to_vector(irq); > if (irq < 0) { > printk(KERN_ERR PREFIX "SCI (ACPI interrupt %d) not registered\n", > acpi_fadt.sci_int); > return AE_OK; > } > #endif >; > } > acpi_irq_irq = irq; > -------- > > -------- Patched code > irq = acpi_register_gsi(gsi, ACPI_ACTIVE_LOW, ACPI_LEVEL_SENSITIVE); > if (irq < 0) { > printk(KERN_ERR PREFIX "SCI (ACPI interrupt %d) not registered\n", > gsi); > return AE_OK; > } > >; > } > -------- > > > From: Bjorn Helgaas <bjorn.helgaas@hp.com> > Subject: [RFC] ACPI IRQ proposal > Date: Tue, 23 Mar 2004 15:37:14 -0700 > > > I think the ACPI/platform interactions for IRQ setup are unnecessarily > > complex. Today we have: > > > > - boot-time parsing of all the _PRTs (platform subsys_initcall > > calls acpi_pci_irq_init(), which calls either mp_parse_prt() > > or iosapic_parse_prt() based on some #ifdefs). > > > > - pci_enable_device()-time IRQ enable (platform > > pcibios_enable_resources() calls acpi_pci_irq_enable(), which > > calls back to platform code, again based on some #ifdefs). > > > > By defining a new platform interface, we should be able to get rid of > > the boot-time _PRT parsing and do everything cleanly at > > pci_enable_device()-time: > > > > int /* Linux IRQ */ > > acpi_register_gsi(int gsi, > > int polarity, /* active high or low */ > > int trigger) /* edge or level */ > > > > This is responsible for whatever APIC or IOSAPIC programming the > > platform needs, as well as allocating and returning a Linux IRQ. > > > > By doing this, we get > > > > - possibility of hot-plugging a PCI root bridge (w/ _PRT) > > - removal of architecture #ifdefs from pci_irq.c and osl.c > > - removal of some Linux IRQ junk from acpi/pci_irq.c > > > > If there are still some broken drivers that don't call pci_enable_device(), > > we still have the option of putting a hook somewhere that just calls > > acpi_pci_irq_enable() for all PCI devices. > > > > Sample patch below only cleans up ia64; i386 and x86_64 looks a > > little more complicated. Any comments? > > - > Fri Mar 26 04:01:57 2004
This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:24 EST
|
http://www.gelato.unsw.edu.au/archives/linux-ia64/0403/9013.html
|
CC-MAIN-2020-24
|
refinedweb
| 521
| 51.58
|
How Do I detect an OS version?
In Win32 SDK, we have an API GetVersionEx that returns the information in
OSVERSIONINFO structure. And then we can look at the values of various members
of structures to decide what version of operating system we are running on.
To accomplish the same
task, .NET SDK provides a class named Environment. In this class there is a
static method named OSVersion that returns OperatingSystem object. This object
can be used to get the value of operating system version.
How Do
I Interpret OperatingSystem Object
The OperatingSystem
class has three properties that contain all the information that you will need
to get value of operating system version.
CSD: This property indicates Corrected Service Diskette number of the operating system or in other words this is a string representing the service pack installed for the operating system.
I would suggest you
read documentation to get in depth details about what these values stand for and
how .NET uses these values to load the right version of an assembly for any
application.
What All These Values Mean
You can combine the values returned by the above three values to get the exact
version of OS (Windows) running on the system. Since there are no details
available in .NET SDK, I assume the meaning of all the values remain the same as
Win32 SDK. Following is the table I used to extract the value of Operating
System.
Following a
small sample from the class that shows the use of Environment class in System
namespace. Private os As OperatingSystem
= Environment.OSVersion ' Get the version
information Private vs As Version
= os.Version Private Me.m_nMajorVer
= vs.Major Private Me.m_nMinorVersion
= vs.Minor Private Me.m_nRevision
= vs.Revision Private Me.m_nBuildNumber
= vs.Build ' Get the service pack
information Private Me.m_strServicePack
= os.CSD
View All
|
https://www.c-sharpcorner.com/UploadFile/kamran_shakil/find-an-operating-system-version/
|
CC-MAIN-2018-13
|
refinedweb
| 305
| 59.09
|
Yet Another Dataset Proposal
Contents
Informative Introduction
When working with RDF, it is often desirable to have a data structure that can comprise multiple RDF graphs. This is especially true when dealing with data on the web, where data may come from multiple sources with different levels of information quality, and it is important to keep track of what came from where. RDF datasets are a mechanism for achieving this.
IRIs in RDF graphs denote resources. In RDF datasets, IRIs can also have an additional associated RDF graph, called the state of the denoted resource.
RDF does not constrain what kind of resources can have state, or what exactly might be the state of any given resource. Given an IRI, there are no formal restrictions on the relationship that must hold between its denoted resource and the associated RDF graph.
Note: Although there is no formal restriction on the relationship between resources and state graphs, there are certainly good practices. For IRIs that dereference to a representation, if the representation can be parsed as RDF, it is considered good practice to treat the resulting RDF graph as the state of the resource. To promote interoperability, this interpretation should generally be followed when RDF datasets are used on the web.
Example: In the following example RDF dataset, the resources denoted by :g1 and :g2 are said to be valid in different years. Furthermore, both resources have associated state graphs. The graph for :g1 claims that Joe works for ACME, while the graph for :g2 claims that Joe works for Google.
{ :g1 :valid "2008"^^xsd:gYear. :g2 :valid "2009"^^xsd:gYear. } :g1 { :Joe :worksFor :ACME_Inc. } :g2 { :Joe :worksFor :Google_Inc. }
Abstract Syntax
An RDF dataset is a collection of RDF graphs and comprises:
- Exactly one default graph, being an RDF graph. The default graph does not have a name and may be empty.
- Zero or more state pairs. Each state pair consists of an IRI (called the graph IRI of the pair) and an RDF graph (called the named graph of the pair). There can only be one state pair for any given IRI within an RDF dataset. The named graph is said to be the state of the resource denoted by the graph name.
An RDF dataset is a pure mathematical structure, with no identity apart from its contents. Two RDF datasets with the same contents are in fact the same single RDF dataset, and an RDF dataset cannot change over time.
An RDF dataspace is a structure that can change over time, and its state at any given time is an RDF dataset. It can be thought of as a mutable RDF dataset.
Note: Not all implementations keep track of empty named graphs in RDF datasets and RDF dataspaces. Therefore, to maximize interoperability, users and applications should not ascribe significance to the distinction between the presence of a state pair with empty RDF graph and the absence of said state pair.
Semantics of RDF datasets: Overview
The semantics of RDF datasets are defined as an extension to the semantics of RDF graphs. DS-interpretations extend the concept of simple interpretations by assigns truth values not just to RDF graphs, but also to state pairs and RDF datasets. The semantics introduce a new property rdf:entails that holds between resources A and B if the state of A entails the state of B.
Some inferences: The most interesting inferences that can be drawn with this semantics are:
- Two datasets are inconsistent if they assign different states to the same graph IRI.
- For any graph G2 entailed by some state graph G1, we can infer a new state pair of the form <skolemIRI,G2>. (If blank nodes were allowed as graph names, then the state pair would associate a fresh blank node with G2. Since they are not allowed, we use a skolem IRI in its place.)
- If one graph in the dataset entails another, we can infer an rdf:entails statement between their associated resources (e.g., G1 rdf:entails G2).
Semantics of RDF datasets: Formal definition
Given an entailment regime E, a DS+E-interpretation is an E-interpretation extended with:
- a state relationship S that is a set of pairs <x,y> where x in IR and y an RDF graph and no x appears twice in the set.
A DS+E-interpretation of vocabulary (V union {rdf:entails}) must satisfy the following semantic conditions:
- If SP is a state pair <i,G> then I(SP) = true if <I(i),G> is in S, and false otherwise.
- If DS is an RDF dataset, then I(DS) =
- false if I(DG) is false for the default graph DG of DS
- false if I(SP) is false for any state pair SP in DS
- true otherwise.
- If <x,G1> is in S and G1 E-entails G2, then there exists an y such that <y,G2> is in S.
- <x,y> is in IEXT(I(rdf:entails)) if and only if <x,G1> is in S and <y,G2> is in S and G1 E-entails G2.
The first and second conditions assign truth values to state pairs and RDF datastes, respectively. The third condition ensures that for every graph G2 entailed by some state graph G1, a resource with state G2 does actually exist. That resource may not have a name, but we could refer to it via a blank node or via a skolem IRI. The fourth condition makes rdf:entails work.
Note: The semantics leaves the meaning of the named graphs themselves entirely isolated from the other contents of the RDF dataset; statements made in the default graph or in another named graph do not affect the interpretation of a named graph. Semantic extensions can impose additional conditions if desired.
Semantics of web datasets
Here we will capture the intuitive meaning of IRIs and dereferencing on the Web by defining additional semantic conditions on DS+E-interpretations.
A WDS+E-interpretation is a DS+E-interpretation that must satisfy the following additional semantic conditions:
- If x is a dereferenceable IRI that is not a skolem IRI, then <I(x),G> is in S if and only if x dereferences to a representation that can be parsed as an RDF graph G.
- E is itself a WDS+E-interpretation with the same state relationship.
The first condition requires that the state relationship is the dereference+parse relationship. We exclude skolem IRIs so that they can be used as “throw-away” identifiers for inferred graphs without requiring them to be dereferenceable.
The second condition is a way of forcing all dereference+parseable IRIs across default graph and all named graphs to have the same state, as all will be using the same state relationship. In practical terms this means that any rdf:entails triple that holds in the default graph will also hold in any of the named graphs.
@@ Problem! The formalism doesn't quite work here. The intention is that an IRI mentioned anywhere in the dataset—in the default graph, as a graph name, or in a named graph—have the same associated state (even though the formalism doesn't guarantee that they denote the same thing, which is incidental but perhaps a good thing). But the definition above is recursive and therefore doesn't work.
Examples
Example 1: The following two datasets are DS-inconsistent. S assigns each resource to only a single state graph. There can be no DS-interpretation whose S assigns I(:g1) to both given graphs.
:g1 { :x a :y. }
:g1 { :x a :y,:z. }
Example 2: The first dataset DS-entails the second. Let skolem: be a prefix that expands to a namespace of skolem IRIs.
:g1 { :x a :y,:z. }
skolem:g2 { :x a :z. }
Example 3: The first dataset DS-entails the second. Let skolem: be a prefix that expands to a namespace of skolem IRIs.
:g1 { :x a :y. :y rdfs:subClassOf :z. }
{ :g1 rdf:entails skolem:g2. } :g1 { :x a :y. :y rdfs:subClassOf :z. } skolem:g2 { :x a :z. }
|
https://www.w3.org/2011/rdf-wg/wiki/Yet_Another_Dataset_Proposal
|
CC-MAIN-2017-22
|
refinedweb
| 1,341
| 71.34
|
JavaScript Weekly
Archives
|
Search
|
Latest Issue
|
RSS
Search
Issues
» 18
Subscribe now »
ONE
e-mail each Friday. Easy to unsubscribe. No spam — your e-mail address is
safe.
Archive
|
Read this issue on the Web
JavaScript Weekly
Issue 18
March 18, 2011
It's issue 18 and it's March 18 (the 6th birthday of Ajax - did you know?). Thanks for being a part of the JavaScript Weekly club; now 4582 subscribers strong!
News
Is it AJAX's Birthday? Yes, It's 6 Years Old Today
—
On March 18, 2005, Jesse James Garrett wrote an article (linked at the bottom of this issue) called "Ajax: A New Approach to Web Applications" and kicked off the "Ajax" term. Happy 6th birthday, Ajax.
Dojo 1.6 Released: Object Store, HTML5 Data Attributes and More
—
Dojo is a popular JavaScript framework and toolkit that, it is argued, ranks very highly for its object oriented structure. This week's release of Dojo 1.6 follows from a substantial effort from the largest Dojo team ever.
jQuery Conference 2011 (SF Bay Area) Schedule Posted
—
The jQuery Conference 2011 is taking place in the Bay Area on April 16-17 and the speakers and schedule are now laid out. The early-bird tickets are sold out but there are still tickets to be had to join John Resig, Steve Souders, Paul Irish and other top JavaScript developers next month.
Opera Releases Web Page and JavaScript Debugger
—
Opera Software has extended its Opera Web browser with a DOM, CSS, network and JavaScript debugging tool called Dragonfly. Think Firefox's Firebug but for Opera.
Articles
Why JavaScript Doesn't Have Operators Yet?
—
Brendan Eich, the 'father of JS' and CTO of Mozilla, spends a few minutes talking about the future of JavaScript and its treatment of operators in the latest episode of his popular JavaScript podcast.
IE9 vs Chrome 10 vs Firefox 4 RC vs Opera 11.01 vs Safari 5 - JavaScript Benchmarks
—
ZDNet puts the latest versions of the major browsers under the spotlight and runs 4 sets of JavaScript benchmarks on them all. In short, Chrome wins and IE 9 64 bit is 'shockingly bad'.
A 'Hello World' Introduction to Dojo
—
Did you see the Dojo 1.6 release news above? If you're new to Dojo and want to see how it works, check out this 'Hello World' tutorial takes you through some of the bare basics.
Canvas From Scratch: Advanced Drawing
—
Rob Hawkes demonstrates some 'advanced' drawing techniques for Canvas elements using JavaScript.
Dictionary Lookups in JavaScript
—
JavaScript supremo John Resig looks at several ways of solving the same problem: looking up the existence of thousands of words in a dictionary as fast as possible.
JavaScript Trie Performance Analysis
—
Following on from the previous post, a commenter suggested to John Resig that he investigate 'trie' data structures. In this post, John shows how to use tries in JavaScript and what performance and memory benefits they yielded over other data structures.
Why the Nitro JavaScript Engine Isn't Available to Apps Outside Mobile Safari in iOS 4.3
—
UIWebViews on the iOS 4.3 platform don't have access to the full performance offered by the updated Nitro JavaScript Engine in Mobile Safari. John Gruber of Daring Fireball examines why.
Domain Specific Languages in CoffeeScript
—
One of the great features of the CoffeeScript language is the great expressiveness that allows easy creation of Domain Specific Languages (DSLs). In this post Amir Salihefendic explores this aspect of CoffeeScript, particularly in relation to some Ruby examples.
Plugin to Data Binding with jQuery
—
In a post for Microsoft's ScriptJunkie blog, Tim Kulp looks at how to 'bind' JSON-based data to templates using, first, plain-old JavaScript, before moving on to an efficient jQuery solution using jQuery Templates and DataBinder.
4 'this' Gotchas
—
Craig Buckler of SitePoint looks at four situations where you might get caught out by JavaScript's 'this' statement.
List Posts
33 jQuery, Mootools, and Prototype Lightbox Scripts
—
Alex Joy presents a well laid out list of 33 different 'lightbox' scripts (those modal dialogs that allow you to overlay images and/or HTML on the current page). There's a visual example of each too.
Top 15 Totally Fresh jQuery Plugins Of Early 2011
—
A totally random mish-mash of recently released jQuery plugins including carousels, accordions, a 3D gallery, and even a 'terminal emulator.'
Code and Libraries
NowJS: RPC and More in a Node.js Module
—
NowJS is a Node module that creates a magical 'now' namespace that's accessible by both server and client processes, making building real-time webapps even easier.
Jtalk: A JavaScript-Based Smalltalk for Web Devs
—
Jtalk is an implementation of the Smalltalk language that runs on top of the JavaScript runtime. It is designed to make client-side development faster and easier. Jtalk is written in itself, including the parser and compiler.
execjs: Running JavaScript Code from Ruby
—
execjs is a library by Sam Stephenson (creator of Prototype) that lets you run JavaScript code from Ruby scripts. It picks the best runtime available (from a generous selection) to evaluate your JavaScript.
Creating a Website Tour with jQuery
—
Mary Lou shares some code to put together an interactive, Web-based site 'tour' using jQuery. The demo is compelling.
Last but not least..
Ajax: A New Approach to Web Applications (2005)
—
It's the article that lit a fire under the collective asses of the Web development scene. Jesse James Garrett came up with the term Ajax and it's been blowing up ever
|
http://javascriptweekly.com/issues/18
|
CC-MAIN-2015-22
|
refinedweb
| 925
| 70.33
|
What’s the Score?
Our game is missing something vital…a way to know who is the best player…a way for one player to beat the other…a game has to have a winner! In this part we’ll add scoring to our game. Here’s how we’ll do it:
- Add goals
- Add a game manager script to keep track of the scores
- Display the current score on the screen.
Goals
Adding goals uses some of the techniques we’ve already covered, so we’re going to get a bit of practice using GameObjects, collisions, and a little scripting.
Create a Goal Prefab
- Create an empty GameObject and name it ‘GoalPrefab’.
- Add a BoxCollider2D component to GoalPrefab (remember, Add Component via the Inspector with the GameObject selected).
- Create a new C# script, and call it ‘GoalScript’. Leave this script empty for now.
- Add GoalSCript to GoalPrefab (remember, drag the script into the Inspector).
- Add a SpriteRenderer to GoalPrefab via the Inspector.
- Populate the SpriteRenderer with the same sprite we used for the paddles, but change the colour to differentiate the goal from the wall.
If you look closely in the Scene window you’ll see that the sprite is a different shape to the collider (the collider is the green square):
This is because we added the collider first (if you add the sprite first, the collider will automatically shape itself to the sprite).
To fix this:
- Click the cog in the upper-right corner of the collider component in Inspector.
- From the drop-down menu select Reset:
Resetting the collider sets it to match the sprite shape.
Finally, move the goal so it overlaps one of the walls and stretch its height (just change the transform Y scale to something around 2.2). Place it so it slightly over the edge of the wall (so the ball can hit the goal) like in the image below (my goal is green and on the left). Change the transform’s Y position to zero to ensure the goal is centred.
You will notice the goal is on top of the wall, covering it where they overlap. This is because of Unity’s drawing order layers. To make the goal draw under the wall, change the Order in Layer property on the Sprite Renderer to -1.
Despite its name, GoalPrefab is currently just a GameObject, so turn it into a prefab by dragging it into the Prefabs folder, then delete the original GameObject from the Hierarchy.
Now make two copies of GoalPrefab in the scene Hierarchy and place them both appropriately (they will default to the position of the original, so move one to the opposite side of the screen by reversing its transform’s X position like we did with the walls earlier, e.g. from -7.02 to 7.02). Rename the two goals to Player1Goal and Player2Goal. Create another empty GameObject called Goals and place both goals inside.
Game Manager
- Create an empty GameObject in the Hierarchy and name it GameManager.
- Create a new C# script in the Scripts folder and name it GameManagerScript.
- Add GameManagerScript to GameManager.
Edit GameManagerScript
Open GameManagerScript for editing. Start by adding these variables.
int playerOneScore, playerTwoScore;
Set them to start at zero by adding these lines to the Start() method:
playerOneScore = 0; playerTwoScore = 0;
Also add the following method:); }
For the non-programmers I’ll explain that code. We made this method public so it can be called from other scripts, and we gave it a parameter playerNumber, which we will use to tell this method who scored (i.e. player 1 or player 2).
(i.e. we are increasing the value by 1).
We will make our game a ‘best of 5’ (or ‘first to 3’) competition, so this is why we call a method called GameOver() when a player reaches a score of 3 (e.g. if (playerTwoScore ==3)).
We call GameOver() in the above method, so we need to create it (your script editor will probably mark those lines as errors at the moment). For now we’ll just restart the game, and we’ll add some more code to this later.
Firstly, add this variable so our script can communicate with the ball:
[SerializeField] BallScript gameBall;
Add the following method to GameManagerScript:
void GameOver(int winner) { // this is called when a player reaches 3 points // reset the scores playerOneScore = 0; playerTwoScore = 0; gameBall.Reset (); }
Open BallScript and add this Reset() method:
public void Reset() { // reset the ball position and restart the ball movement myBody.velocity = Vector2.zero; transform.position = new Vector2(0,0); Start(); // restart the ball }
This method halts the ball’s movement by setting its rigidbody’s velocity to Vector2.zero (meaning its velocity will be (0, 0) – no movement on either axis). Then the ball’s position is changed to (0, 0), which is the centre of the screen. Then finally, Start() is called, which sets the game off again.
We will need to add more here so the game doesn’t just suddenly restart, but for now we’ll leave it as it is.
Now we need to populate that gameBall variable in the GameManager script.
- Select GameManager in Hierarchy.
- Drag Ball from the Hierarchy over to the empty Game Ball field in the Game Manager Script.
Unity is clever enough to infer that we need a component of type BallScript, so it finds the BallScript in the Ball GameObject and adds it to the field. We now have Ball‘s instance of BallScript referenced in GameManagerScript.
GoalScript
Our goal script will be quite simple. It will detect when the ball comes into contact with the goal and then tell GameManagerScript that a goal has been scored. We also need to differentiate between the two different goals so we know who scored.
Open GoalScript and add the following variables:
[SerializeField] int attackingPlayer; // which player scores into this goal [SerializeField] GameManagerScript gameMan; // this will hold a reference to the game manager script
Next, add some behaviour to detect when the ball collides with the goal. This is very similar to the collision detection we did on the paddles:
void OnCollisionEnter2D(Collision2D other) { if(other.transform.name == "Ball") { gameMan.GoalScored(attackingPlayer); } }
When the ball collides with the goal, GoalScored() is called in GameManagerScript, and we pass which player scored by using attackingPlayer
as a parameter.
Reference GameManagerScript in the Goals
- Save GoalScript
- Select Player1Goal in the Hierarchy
- Drag GameManager from the Hierarchy into the Game Man slot in the Goal Script section of the Inspector.
- Repeat the above steps for Player2Goal.
Now, set the correct player values in the Attacking Player Inspector fields for each goal. Note that the goal behind player 1 needs the value 2 because player 2 will be scoring points in that goal (and vice versa).
Save the scene and the project, then playtest the game. Though we can’t yet see the score, when a player gets to three points the game will reset.
Recap
We did a lot of scripting in Part 7, and by now you should be getting used to attaching scripts to GameObjects and using public/serialized fields to add components and values to a script instance (like when we added Attacking Player values to the goals). We also got some practice at communicating between scripts by referencing a script and calling its public methods. We now have scoring system for our game!
Continue to Part 8 where we will work on our game’s user interface by adding a score display and a menu screen, all using Unity great GUI system.
16 thoughts on “Beginner’s Guide: Create a Pong Clone in Unity: Part 7”
Pingback: Beginner’s Guide: Create a Pong Clone in Unity: Part 6 « 6 | Unity for All
So i downloaded the scripts from the completed project and when i try to add the script it says it has to be fixed.
That will be because Unity had made some changes since this tutorial was written. Unity should be able to automatically fix everything. There are a couple of very minor changes to the way certain things are scripted, but none of the fundamentals have changed. I plan to update this tutorial series when the next major Unity update (5.4) is released.
Ok thanks for telling me. Please notify me when the new tutorial is out
Hi Damien,
I seem to be getting errors using your if statement for GoalScored so l can not process further. I have even cut and pasted it into the GameManager script but it has not worked. I am using Unity 5.5 1f1 personal. Unity is showing the following:
1. Assets/Assets/Scripts/GameManager.cs(16,1): error CS1525: Unexpected symbol `public’
2. Assets/Assets/Scripts/GameManager.cs(16,9): error CS1547: Keyword `void’ cannot be used in this context
3. Assets/Assets/Scripts/GameManager.cs(16,23): error CS1525: Unexpected symbol `(‘
4. Assets/Assets/Scripts/GameManager.cs(21,3): error CS1525: Unexpected symbol `else’
5. Assets/Assets/Scripts/GameManager.cs(49,1): error CS1525: Unexpected symbol `void’
For errors like that there is most likely something missing, like a bracket or semi-colon.
Double-check your script and make sure all brackets are correctly paired. You may have pasted over a bracket or semi-colon, or pasted in slightly the wrong place.
Find the ‘public’ on line 16 – there is probably something missing just before that – a closing bracket for the previous method probably. It’s also possible that a semi-colon is missing from the end of a line.
You could also download the finished project and check that part of the code.
If you’re still stuck, paste your whole GameManager script, and I’ll see if I can find the issue.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
// Use this for initialization
void Start () {
int playerOneScore, playerTwoScore;
playerOneScore = 0;
playerTwoScore = 0;);
}
[SerializeField]
BallScript gameBall;
void GameOver(int winner)
{
// this is called when a player reaches 3 points
// reset the scores
playerOneScore = 0;
playerTwoScore = 0;
gameBall.Reset ();
}
}
// Update is called once per frame
void Update () {
}
}
There is s close curly bracket ( ‘}’) missing at the end of the Start() method.
Place a closing curly bracket after playerTwoScore = 0;
Hi Damien,
Thank you so much for making this best tutorial ever , I followed your direction make my fist game,so far so good!
I have one problem that is on part 7
“Select GameManager in Hierarchy.
Drag Ball from the Hierarchy over to the empty Game Ball field in the Game Manager Script.”
I did not find “empty Game Ball field in the Game Manager Script”, so I stuck here , please help me.
lily
Do you have this:
[SerializeField]
BallScript gameBall;
In your GameManager script? If you don’t have the [SerializeField] part, the field will not be visible in the Inspector.
Another possibility is that you have that in your script but Unity is unable to compile the script due to an error elsewhere. Make sure there is no error in the Console window.
Hello, I’m having the same issue as lily. It doesn’t show an error anywhere so I was wondering how/if you were able to fix the issue?
I have a problem. The GoalSprite is not rendered somehow.
Make sure the goal sprite is not behind the wall.Check the sprite’s layer and order in layer properties.
|
http://unity.grogansoft.com/beginners-guide-create-a-pong-clone-in-unity-part-7/
|
CC-MAIN-2019-09
|
refinedweb
| 1,906
| 62.98
|
import "go.dedis.ch/kyber/util/random"
Package random provides facilities for generating random or pseudorandom cryptographic objects.
Bits chooses a uniform random BigInt with a given maximum BitLen. If 'exact' is true, choose a BigInt with _exactly_ that BitLen, not less
Bytes fills a slice with random bytes from rand.
Int chooses a uniform random big.Int less than a given modulus
New returns a new cipher.Stream that gets random data from the given readers. If no reader was provided, Go's crypto/rand package is used. Otherwise, for each source, 32 bytes are read. They are concatenated and then hashed, and the resulting hash is used as a seed to a PRNG. The resulting cipher.Stream can be used in multiple threads.
Package random imports 7 packages (graph) and is imported by 1 packages. Updated 2019-12-02. Refresh now. Tools for package owners.
|
https://godoc.org/go.dedis.ch/kyber/util/random
|
CC-MAIN-2020-40
|
refinedweb
| 147
| 60.92
|
Swish 1.0, our Swift networking library, is out! Swish came to life through working on many client projects and writing more or less the same networking stack over and over. Our goals with Swish are:
- Be able to test our networking layer.
- Keep the networking layer self contained.
- By default, decode JSON into domain objects via Argo.
- If we want to do something different than decoding JSON, it should be as painless as possible.
And so Swish was born!
Reasonable Default Behavior
Our 90% use case is that we get JSON from an endpoint, and we want to decode it
into a struct via Argo. Swish makes that easy. Let’s say you have an endpoint,
GET, that returns the following JSON:
{ "id": 1, "commentText": "Pretty good. Pret-ty pre-ty pre-ty good.", "username": "LarryDavid" }
We’ll model this with the following struct, and implement Argo’s
Decodable
protocol to tell it how to deal with JSON:
import Argo import Curry struct Comment: Decodable { let id: Int let text: String let username: String static func decode(json: JSON) -> Decoded<Comment> { return curry(Comment.init) <^> j <| "id" <*> j <| "commentText" <*> j <| "username" } }
(n.b. if you’re not familiar with the
Curry library, check this blog post
out)
We can model the request by defining a struct that implements Swish’s
Request
protocol:
struct CommentRequest: Request { typealias ResponseObject = Comment let id: Int func build() -> NSURLRequest { let url = NSURL(string: "\(id)")! return NSURLRequest(URL: url) } }
We can then use Swish’s default
APIClient to make the request:
let request = CommentRequest(id: 1) let dataTask = APIClient().performRequest(request) { (response: Result<Comment, SwishError>) in switch response { case let .Success(value): print("Here's the comment: \(value)") case let .Failure(error): print("Oh no, an error: \(error)") } }
And that’s it!
Customize via Protocols
Swish’s defaults make decoding via Argo seamless, but if you want to customize, provide a different implementation for any of the following protocols:
RequestPerformerallows you to define how the
NSURLRequestshould be carried out
Deserializerallows you to process the
NSDatafrom the response however you wish
Parserallows to you convert the result of your deserialization into a
Representation(e.g.
JSON, by default)
Clientallows you to define how the objects implementing the above protocols are linked together.
|
https://thoughtbot.com/blog/introducing-swish-1-0-protocol-based-networking-for-ios
|
CC-MAIN-2020-40
|
refinedweb
| 376
| 53.92
|
Abstract
An Atom document is very close to being an RDF document. This page aims to track the gap between the formats.
The intent is to see what would be required for an Atom document to be an RDF document consisting of elements taken from the OWL ontology such as AtomOWL . There is no interest in making the inverse true: namely that a graph consisting of OWL statements be mappable into any RDF document, and that that document be an Atom document.
Status
This is a first outline of some of the differences.
Rationale
If the gap between Atom and RDF is cheap enough to close, then specifying a solid extension mechanism will be very simply a requirement than any extensions to Atom also be RDF documents. This together with the Atom ontology, will help extension writers frame their work much more easily, and Atom consumers parse extensions in a generic way.
The Gap
Atom attributes are not in the atom namespace. It is deprecated in rdf for this to be the case.
Additions to the spec, stating that the atom syntax contains a hidden rdf:parseType="Resource" at various locations
changing the generator construct from having the form
atom:title is defined in 2 places with incompatible definitions
work on the OWL side needs to be done on understanding the TEXT construct
Solutions
There will be many different ways to close the gap. The onus will always be on there being the least amount of work on the Atom spec side.
Atom Attributes: [PaceAttributesNamespace]
Rejected Solutions
This is a space to keep track of proposed solutions that did not quite make it. It helps to have such a space as it can help people coming in to the discussion finding their way, or noticing some solution that may have been missed.
Atom Attributes:
Impacts
very minimal on the Atom format.
very high on the ability to extend Atom intelligently
|
http://www.intertwingly.net/wiki/pie/AtomAsRDF
|
crawl-001
|
refinedweb
| 320
| 58.52
|
BBC micro:bit
Bryn's Concentrated Clocks
Introduction
This game is based on code written with Bryn during one of our lessons. Bryn took an example program from the page on the matrix - the one which does a slideshow of the built-in images. He removed all of the images except the ones that were clock hands. He adjusted the speed of the animation and ended up with a line that was spinning round in circles. Having played the other concentration game, he realised that you could make another version based on stopping the rotating line at when it is in the 12 o'clock position.
The line will spin around when the game starts. It can spin happily for as long as you want. You need to stop it when it reaches the 12 position. If you are successful, you get a point and the game speeds up a little.
Programming
I reordered the clock images and built upon the code we wrote in class. Here is a basic version of the game that you can adapt to suit your purposes.
from microbit import * clocks = [ Image.CLOCK1,Image.CLOCK2,Image.CLOCK3, Image.CLOCK4,Image.CLOCK5,Image.CLOCK6, Image.CLOCK7,Image.CLOCK8,Image.CLOCK9, Image.CLOCK10,Image.CLOCK11,Image.CLOCK12] counter = 0 start = 200 paws = start score = 0 while True: display.show(clocks[counter]) # extra help on the last tick if counter==11: sleep(paws/10) if button_a.was_pressed(): sleep(500) if counter==11: display.show(Image.HAPPY) score += 1 paws = paws - 10 paws = max(10, paws) sleep(500) else: display.show(Image.SAD) display.scroll(str(score)) sleep(500) score = 0 paws = start counter += 1 if counter>11: counter = 0 sleep(paws)
As you read through the program, you should be able to see which numbers and calculations you can change to alter the pace of the game. The variable paws is the key one for this.
Challenges
- Start by getting the game play settings as you want them.
- Everyone seems to like using Play-Doh buttons for these games. Why should this one be any different?
- This game idea would also work by having the user have to wait for a number of cycles before stoppping the clock.
- Another variant of this game would be to have the user need to stop the clock in different positions. This could be a curious way of getting answers to questions in some sort of quiz-based affair.
|
http://multiwingspan.co.uk/micro.php?page=concentrate2
|
CC-MAIN-2017-22
|
refinedweb
| 407
| 73.27
|
Hi all,
I am a relatively inexperienced programmer, but I am really eager to do the hard yards and learn. To produce the code below, I have spent about 4 hours reading textbooks and searching the internet, so try not to laugh at it!
Thanks in advance for any advice you may offer! My problem is...Thanks in advance for any advice you may offer! My problem is...
I have a text file with the following text inside it
So what I want to do is:So what I want to do is:Code:image 0 281253 6.13325e+06 34.8823 0.009 -3.13852 0.0117609 -1.07777 1170 1189 1279 1278 ... ... (and then the next lot of information that is correlated with the next image) image 1 234940 6.13232e+06 ...etc
1. Search the code for the text "image"
2. Store the number after the text "image"
3. Store all of the following numbers, until the next mention of the word "image" OR until the end of the file.
So my attempt was to do this:
The output (which is not quite what I want) is:The output (which is not quite what I want) is:Code:#include <iostream> #include <conio.h> #include <fstream> using namespace std; int main() { int imageNumber = -1; ifstream inFile; string searchString = "image"; string lineOfText; inFile.open("C:\\datafile.txt"); for(;;){ getline(inFile, lineOfText); if (inFile.eof()) break; if (lineOfText.find(searchString, 0) != string::npos){ cout << "The program found the word: " << searchString << endl; inFile >> imageNumber; cout << "imageNumber read: " << imageNumber << "\n"; /* etc... I read in the other numbers using: inFile >> variableName; and then read in the 4 digit numbers into an array using a for loop (which works well) */ } } getch(); return 0; }
I want the imageNumber to read the number after the text "image", i.e. '0' in this case. The problem is because the lineOfText.find() has searched the whole line, and now the image stream pointer (correct me if I am wrongI want the imageNumber to read the number after the text "image", i.e. '0' in this case. The problem is because the lineOfText.find() has searched the whole line, and now the image stream pointer (correct me if I am wrongCode:The program found the word: image imageNumber read: 281253
) is pointing to the next line, so imageNumber just picks up the first integer on that line.) is pointing to the next line, so imageNumber just picks up the first integer on that line.
I never like coming to people for help with empty hands, so I think I either need to:
1. Use tokenisers - I read the forum help on this and vaguely understood it (it'll take me another 4 hours or so to work out how to integrate search with them though...)
2. Stop the pointer after matching the word "image" so I can read in the correct imageNumber variable. I have no idea how. Maybe seekg()? I read about that a few times.
Once again, I am only a beginner, so I would prefer you to help me with this code if possible rather than having to get my head around another concept.
Thanks so much for any suggestions (particularly code).
Regards, Geek10
|
https://cboard.cprogramming.com/cplusplus-programming/129634-ifstream-text-file-search-word-gather-block-data.html
|
CC-MAIN-2017-22
|
refinedweb
| 538
| 72.36
|
I have a working PHP app running in Bluemix that I want to extend to call a RESTful service (Insights for Twitter). Since PHP has no built-in way to call the service, I looked around and decided to use Guzzle.
I downloaded Guzzle 6.0.2 from its Git and imported the zip into my httdocs/vendor path and renamed the imported path GuzzleHttp I changed my buildpack to get PHP 5.5 and updated composer.json to the Autoload.psr4 property with:
"GuzzleHttp\\": "htdocs/vendor/"
I redeployed my app and it still worked.
Then I added the following code to my MainController.php: after some other uses:
use GuzzleHttp\Client;
and then later:
$client = new GuzzleHttp\Client([ // Base URI is used with relative requests 'base_uri' => 'https:myserviceURI.mybluemix.net', // You can set any number of default request options. 'timeout' => 2.0, ]); // Use guzzle to send a GET request to Watson Twitter Insights $guzzleresponse = $client->request('GET', '/api/v1/messages/search');
Now, when I redeploy the app I get:
FatalErrorException in HomeController.php line 100: Class 'App\Http\Controllers\GuzzleHttp\Client' not found
I don't know why it's looking in app\Http\Controllers\ but I tried copying the Guzzle src folder - which includes Client.php - there, renamed it GuzzleHttp and it still fails the same way.
I'm neither a PHP nor a Laravel expert. I inherited the code from an intern team so I don't quite know how all the pieces fit together.
I have some questions:
Did I really need to install Guzzle in my workspace or would it be picked up automatically from the buildpack?
Did I import the Guzzle code in the right way?
Why is it looking for the Guzzle Client in my Controllers path?
Is there a good PHP sample program that drives Insights for Twitter? I found one in Javascript but I need to run this server-side?
And of course, most importantly, what do I need to do to get this working?
Answers to any or all of these questions wold be greatly appreciated. John Knutson
Answer by John Knutson (31) | May 04, 2016 at 05:10 AM
I also raised this question on StackOverflow and it was answered overnight. Seems like I had a namespace issue - fixed now. More details here
Answer by NabazMaaruf (1) | Mar 13, 2017 at 02:46 PM
const BASE_URI = ''; $client = new Client(array_merge([ 'base_uri' => self::BASE_URI, 'timeout' => 30.0 ]), $options); $options = array_merge_recursive([ RequestOptions::AUTH => [ 'Conversation_USERNAME', 'CONVERSATION_PASSWORD', ], RequestOptions::HEADERS => [ 'Content-Type' => 'application/json' ] ]);
Answer by AppDividend (1) | Jun 17, 2018 at 02:04 PM
If you still have any issue in the Laravel Guzzle library then this guide Laravel Guzzle Http Client Example will be very helpful to you.
65 people are following this question.
|
https://developer.ibm.com/answers/questions/268091/how-to-get-guzzle-working-in-my-laravel-app-on-blu.html?sort=votes
|
CC-MAIN-2019-18
|
refinedweb
| 462
| 64.2
|
Bug #15596
Kernel.warn without arguments should do the same as Kernel.warn(nil)
Description
Kernel.warn without arguments does not print an empty line to $stderr.
This is inconsistent with
Kernel.puts and it feels weird, because it does not act like a regular Ruby method would (if it was written in Ruby instead of C, it would probably be defined like
def warn(msg = nil) and calling it with or without nil as argument would make no difference)
Expected behavior:¶
irb(main):001:0> warn nil => nil irb(main):002:0> warn => nil
Actual behavior:¶
irb(main):001:0> warn nil => nil irb(main):002:0> warn => nil
History
Updated by shevegen (Robert A. Heiler) 4 months ago
This is indeed a (to me) somewhat surprising behaviour; not that I guess
many have encountered it (and it probably is quite minor, which may
explain why that has not been reported before? Unless that was a more
recent change perhaps).
The current documentation is at:
If the behaviour is not a bug then I think it should be mentioned
in the documentation at the least briefly to explain why it behaves
that way.
If the behaviour is a bug, though, then I think I concur with Kimmo,
but I really do not know any specifics. It did seem strange though,
since I was not able to determine as to why warn nil would be
treated differently than warn without arguments.
Updated by nobu (Nobuyoshi Nakada) 4 months ago
It is a natural behavior.
This method prints multiple arguments to
STDERR, per line.
warn nil passes one argument and prints one line, whereas
warn passes no argument and prints zero line.
Updated by jeremyevans0 (Jeremy Evans) 4 days ago
- Status changed from Open to Rejected
As nobu stated, the current behavior is expected in regards to not printing a newline if no arguments are given, and the documentation is accurate for the current behavior. It states
converts each of the messages to strings, appends a newline character to the string if the string does not end in a newline, and calls Warning.warn with the string.. To me, that implies if there are no messages/arguments, it does not do anything.
It is true that
warn is different than
puts in how a zero argument call is handled.
warn it is similar to
p in this regard.
puts is specifically documented as adding a newline for no arguments (
If called without arguments, outputs a single newline), and
warn is not.
Also available in: Atom PDF
|
https://bugs.ruby-lang.org/issues/15596
|
CC-MAIN-2019-26
|
refinedweb
| 425
| 61.26
|
Back to: Java Tutorials For Beginners and Professionals
Polymorphism in Java with Examples
In this article, I am going to discuss Polymorphism in Java with Examples. Please read our previous where we discussed Wrapper Classes in Java with Examples. It is one of the primary pillars of the object-oriented programming concept. At the end of this article, you will understand the following pointers in detail as well as at the end we will discuss frequently asked interview questions related to Polymorphism, Method Overloading, and Method Overriding in Java.
- What is Polymorphism?
- Why we need Polymorphism?
- Types of Polymorphism in Java?
- What is Compile-Time Polymorphism?
- What is Runtime Polymorphism?
- Understanding Method Overloading and Overriding in Java.
What is Polymorphism in Java?
Polymorphism is a Greek word where poly means many or several and morph means faces/ behaviors or functionalities. So, in simple words, we can say that polymorphism is the ability of an entity to take several forms. In order to understand polymorphism better, please have a look at the following image:
As you can see in the above image, the vehicle is something that has several forms like a two-wheeler, three-wheeler, and four-wheeler, and so on. So this is one example of polymorphism.
According to the software standard, Polymorphism means one function with multiple functionalities or representations. In object-oriented programming, it refers to the ability of an object (or a reference to an object) to take different forms of objects. It allows a common data-gathering message to be sent to each class. Any Java object that can pass more than one IS-A test is considered to be polymorphic.
Polymorphism allows us to create consistent code. Polymorphism encourages called ‘extendibility’ which means an object or a class can have its uses extended. Polymorphism makes software applications a third-party independent applications.
Technically we can say that when a function shows different behaviors when we passed different types and number values, then it is called polymorphism. So behaving in different ways depending on the input received is known as polymorphism i.e. whenever the input changes, automatically the output or the behavior also changes.
The benefits of third-party independent application are as follows:
- In future enhancements migrating from one-third party to another third party is the easiest task.
- It reduces the development time of the application.
- It decreases maintenance support.
- It makes the application more dynamic.
Types of Polymorphism in Java:
Polymorphism is of two types in Java:
- Static polymorphism / compile-time polymorphism / Early binding
- Dynamic polymorphism / Run-time polymorphism / Late binding
The following images show the different types of polymorphisms in Java with their examples.
What is Compile-Time Polymorphism in Java?
It is also known as Static Polymorphism or Early Polymorphism. A polymorphism that is resolved during compile time is known as compile-time polymorphism. The compile-time Polymorphism feature is implemented with static binding. In Java, compile-time polymorphism is achieved through method overloading.
In the case of compile-time or static polymorphism, the object of the class recognizes which method to be executed for a given method call at the time of compilation and binds that method call with method definition.
In Java, this is happening in the case of method overloading because in the case of overloading each method will have a different signature and based on the method call we can easily recognize the method which matches the method signature.
Method Overloading in Java:
Defining a method multiple times with the same name in a single class with different parameter types then we can say that method is overloading. There are two ways to overload the method in java
- By changing the number of arguments
- By changing the data type
Example of Method Overloading in Java:
public class Overloading { public static void main (String[]args) { System.out.println (10); System.out.println (true); //System.out.println(10, true); //error System.out.println (); //leaves blank line System.out.println (10.89); } }
Output:
10
true
10.89
What is Runtime Polymorphism in Java?
It is also known as Dynamic Polymorphism or Late Polymorphism. A polymorphism that is resolved during run time is known as dynamic polymorphism. The Dynamic Polymorphism feature is implemented with dynamic binding. In Java, dynamic polymorphism is achieved through method overriding.
In the case of Runtime Polymorphism for a given method call, we can recognize which method has to be executed exactly at runtime but not in compilation time because in case of overriding we have multiple methods with the same signature.
So, which method to be given preference and executed that is identified at Runtime and binds the method call with its suitable method. It is also called dynamic polymorphism or late binding. Dynamic Polymorphism is achieved by using method overriding.
Method Overriding in Java:
Method Overriding is redefining the method from the superclass into the subclass by adding new functionality or code. In Java, using the overriding concept superclass provides the freedom to the subclass for writing their own code instead of binding on superclass behavior or code.
Usage of Method Overriding in Java:
Method overriding is used to provide the specific implementation of a method that is already provided by its superclass. Method overriding is used for runtime polymorphism.
Rules for Method Overriding in Java:
- The method name must be the same.
- Method parameter types must be the same.
- The method return type must be the same.
Example to Understand Method Overriding in Java:
class connection { void connect () { } } class oracleconnection extends connection { void connect () { System.out.println ("Connected to Oracle"); } } class mysqlconnection extends connection { void connect () { System.out.println ("Connected to MySQL"); } } class Overriding { public static void main (String args[]) { oracleconnection a1 = new oracleconnection (); mysqlconnection b1 = new mysqlconnection (); a1.connect (); b1.connect (); } }
Output:
Connected to Oracle
Connected to MySQL
Advantages of Polymorphism in Java:
- More flexible and reusable code.
- The single variable name can be used to store variables of multiple data types.
- Faster and efficient code at Runtime.
- Code that is protected from extension by other classes.
- More dynamic code at runtime.
Static and Dynamic Bindings in java:
If you have more than one method of the same name or two variables of the same name in the same class hierarchy it gets tricky to find out which one is used during runtime as a result of their reference in code. This problem is resolved using static and dynamic binding in Java.
Binding is a mechanism to link between a method call and method actual implementation. Its process is used to a link which method or variable to be called as a result of their reference in code.
Static Binding in Java:
When the type of the object is determined at the compiled time (by the compiler), it is known as static binding. The binding of all the static, private, and final methods is done at compile-time.
Why binding of static, final, and private methods is always static binding?
Because the compiler knows that all such methods cannot be overridden and will always be accessed by the object of a local class. Hence compiler doesn’t have any difficulty determining the local object of the class. Static binding is better performance-wise (no extra overhead is required).
Example to Understand Static Binding in Java:
public class StaticBinding { public static class superclass { static void print () { //print in superclass System.out.println ("Hi!"); } } public static class subclass extends superclass { static void print () { //print in subclass System.out.println ("Hello!"); } } public static void main (String[]args) { superclass A = new superclass (); superclass B = new subclass (); A.print (); B.print (); } }
Output:
Hi!
Hi!
Dynamic Binding in Java:
When the type of the object is determined at run time, it is known as dynamic binding. In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.
Example to Understand Dynamic Binding in Java:
public class Main { public static class superclass { void print () { //print in superclass System.out.println ("Hi!"); } } public static class subclass extends superclass { @Override void print () { //print in subclass System.out.println ("Hello!"); } } public static void main (String[]args) { superclass A = new superclass (); superclass B = new subclass (); A.print (); B.print (); } }
Output:
Hi!
Hello!
What is Method Overloading or Function Overloading in Java?
Method Overloading in Java is nothing but a process of creating multiple methods in a class with the same name but with a different signature. In Java, It is also possible to overload the methods in the derived classes as well. It means it allows us to create a method in the derived class with the same name as the method name defined in the base class.
In simple words, we can say that the Method Overloading in Java allows a class to have multiple methods with the same name but with a different signature.
When should we overload methods in Java?
If you want to execute the same logic but with different types of arguments i.e. different types of values, then you need to overload the methods. For example, if you want to add two integers, two floats, and two strings, then you need to define three methods with the same name.
What are the advantages of using method overloading in Java? Or what are the disadvantages if we define methods with a different name?
If we overload the methods, then the user of our application gets comfort feeling in using the method with the impression that he/she calling one method bypassing different types of values. The best example for us is the system-defined “println()” method. It is an overloaded method, not a single method taking different types of values.
When is a method considered as an overloaded method in Java?
If two methods have the same name then those methods are considered overloaded methods. Then the rule we need to, no Runtime Error. Methods can be overloaded in the same or in the super and subclasses because overloaded methods are different methods.
But we can’t override a method in the same class. It leads to Compile Time Error: “method is already defined” because overriding methods are the same methods with a different implementation.
What is Function Overriding in Java?
The process of re-implementing the superclass non-static method in the subclass with the same prototype (same signature defined in the superclass) is called Function Overriding or Method Overriding in Java. The implementation of the subclass overrides (i.e. replaces) the implementation of superclass methods.
The point that you need to keep in mind is the overriding method is always going to be executed from the current class object. The superclass method is called the overridden method and the sub-class method is called the overriding method.
When do we need to override a method in Java?
If the superclass method logic is not fulfilling the sub-class business requirements, then the subclass needs to override that method with the required business logic. Usually, in most real-time applications, the superclass methods are implemented with generic logic which is common for all the next level sub-classes.
When is a sub-class method treated as an overriding method?
If a method in the sub-class contains the same signature as the superclass non-private non-static method, then the subclass method is treated as the overriding method and the superclass method is treated as the overridden method.
Difference Between Method Overloading and Method Overriding in Java
Difference Between Static Polymorphism and Dynamic Polymorphism in Java:
Difference Between Static Binding and Dynamic Binding in Java:
In the next article, I am going to discuss Encapsulation in Java with Examples. Here, in this article, I try to explain Polymorphism in Java with Examples. I hope you enjoy this Polymorphism in Java with Examples article.
|
https://dotnettutorials.net/lesson/polymorphism-in-java/
|
CC-MAIN-2022-27
|
refinedweb
| 1,977
| 55.84
|
Originally published on m4x.io
I recently started adding more content to my blog and in the process I decided having a communication channel with my audience, if there's any, would be quite useful.
Disqus it's a "comment as a service" platform that give you all the tools you need to have this feature on your application in literally 5 mins.
Let's get it on
- Create a disqus account, if you don't have it yet.
- Add the component that is going to load the disqus comment box to your app.
// Comments.js import React, { useEffect } from 'react' const Comments = ({ fullUrl, id }) => { useEffect(() => { const DISQUS_SCRIPT = 'disq_script' const sd = document.getElementById(DISQUS_SCRIPT) if (!sd) { var disqus_config = function() { this.page.url = fullUrl this.page.identifier = id } const d = document const s = d.createElement('script') s.src = '' // REPLACE THIS LINE WITH YOUR DISQUS LINE s.id = DISQUS_SCRIPT s.async = true s.setAttribute('data-timestamp', +new Date()) d.body.appendChild(s) } else { window.DISQUS.reset({ reload: true, config: disqus_config, }) } }, []) return <div id="disqus_thread"></div> } export default Comments
- Use it in your app whenever you want to add comments:D
// Post.js import React from 'react' import Comments from './Comments' const Post = ({ url, id }) => ( <> <RestOfThePost /> <Comments fullUrl={url} id={id} /> </> ) export default Post
- Make sure you add the url of the page you are taking comments for and an id.
- Wait for the awesome comments from your followers.
Is that all I need?
Yes! Incredible, that's all that you need to use disqus. Make sure to add comments yourself to be sure you are sending the right url and id. Stay longer if you want the rest of the story...
Extra: Juice of the story
While doing some research on how to add this I encounter a couple of options that I could try on:
First,I tried adding the snippet of code that it's in the disqus wizzard.
I turned into a component with the famous
dangerouslySetInnerHTML and It looked like this
import React from 'react' const Comments = ({ fullUrl, id }) => { const html = ` <div id="disqus_thread"></div> <script> var disqus_config = function () { this.page.url = '${fullUrl}'; this.page.identifier = '${id}'; }; (function() { var d = document, s = d.createElement('script'); s.src = ''; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> ` return <div dangerouslySetInnerHTML={{ __html: html }} /> } export default Comments
But, this didn't work out of the box. Every time the client side routing was switching components it was behaving quite awful. Also, I was adding a new script everytime the component was mounting.
Yes, I know it was waaay to mvp. But it worked, 2 out 10 times :P
Second tried was using the npm module disqus-react that disqus provides but I was skeptical of how would this be much different from the web approach and if you look at the code...
// file: // ..lots of react code loadInstance() { const doc = window.document; if (window && window.DISQUS && doc.getElementById('dsq-embed-scr')) { window.DISQUS.reset({ reload: true, config: this.getDisqusConfig(this.props.config), }); } else { window.disqus_config = this.getDisqusConfig(this.props.config); window.disqus_shortname = this.props.shortname; insertScript(`{this.props.shortname}.disqus.com/embed.js`, 'dsq-embed-scr', doc.body); } } // ..lots of react code
...and if you look at the code, It isn't.
I didn't install the npm module and tried it out because at this point I have learnt enough about what I need to do to make it work without another black box in my proyect.
So, a couple of tries more and I ended up with this small, in house component that does exactly that. - useDisqus
In this story of adding a "simple" component. I hope you can relate with the thought process to decide what to do at any given time when picking a new library.
If you read this far, thank you and give me a sign ( like, comment, email, etc) that you want to keep reading about my day to day struggles.
I have a tendency of over analyzing simple stuff which sometimes are good for stories but not that much for your productivity.
PS: it took me more than 50 mins to add disqus and I hope you can do it in 5 mins. (10x factor)?
Discussion (0)
|
https://dev.to/neomaxzero/add-disqus-to-your-react-app-in-a-glance-p
|
CC-MAIN-2021-17
|
refinedweb
| 708
| 66.13
|
. Another component of this detection is adjusting the permissions of the device to be accessible to non-root users and groups. --attribute-walk --path=$(udevadm info --query=path --name= -
To get the path of a bare USB device which does not populate any subordinate device you have to use the full USB device path. Start monitor mode and then plug in the USB device to get it:
$ udevadm monitor
... KERNEL[26652.638931] add /devices/pci0000:00/0000:00:01.2/0000:02:00.0/0000:03:05.0/0000:05:00.0/usb1/1-3 (usb) KERNEL[26652.639153] add /devices/pci0000:00/0000:00:01.2/0000:02:00.0/0000:03:05.0/0000:05:00.0/usb1/1-3/1-3:1.0 (usb) ...
You can just choose the deepest path and
--attribute-walk will show all parent's attributes anyway:
$ udevadm info --attribute-walk --path=/devices/pci0000:00/0000:00:01.2/0000:02:00.0/0000:03:05.0/0000:05:00.0/usb1/1-3/1-3:1.0
Testing rules before loading
# udevadm test $(udevadm info --query=path --name. This is ill-advised for two reasons:
- systemd by default runs
systemd-udevd.servicewith a separate "mount namespace" (see namespaces(7)), which means that mounts will not be visible to the rest of the system.
- Even if you change the service parameters to fix this (commenting out the
PrivateMountsand
MountFlagslines), connectederrors.
Allowing regular users to use devices
When a kernel driver initializes a device, the default state of the device node is to be owned by
root:root, with permissions
600. [1] This makes devices inaccessible to regular users unless the driver changes the default, or a udev rule in userspace changes the permissions.
The
OWNER,
GROUP, and
MODE udev values can be used to provide access, though one encounters the issue of how to make a device usable to all users without an overly permissive mode. Ubuntu's approach is to create a
plugdev group that devices are added to, but this practice is not only discouraged by the systemd developers, [2] but considered a bug when shipped in udev rules on Arch (FS#35602).
The recommended approach is to use a
MODE of
660 to let the group use the device, and then attach a
TAG named
uaccess. This special tag makes udev apply a dynamic user ACL to the device node, which coordinates with systemd-logind(8) to make the device usable to logged-in users. For an example of a udev rule implementing this:
/etc/udev/rules.d/71-device-name.rules
SUBSYSTEMS=="usb", ATTRS{idVendor}=="vendor_id", ATTRS{idProduct}=="product_id", MODE="0660", TAG+="uaccess" up triggers of a USB device, like a mouse or a keyboard, so that it can be used to wake the system from sleep.", DRIVERS== --verbose --type=subsystems --action=remove --subsystem-match=usb --attr-match=.
1) The following udev rule executes a script that plays a notification sound and sends a desktop notification when screen brightness is changed according to power state on a laptop. Create the file:
/etc/udev/rules.d/99-backlight_notification.rules
#"
USERNAME_TO_RUN_SCRIPT_ASand
USERNAMEneed to be changed to that of the shortname for the user of the graphical session where the notification will be displayed;
-
#!/bin/sh -.,:
# grep -Fr GROUP /etc/udev/rules.d/ /usr/lib/udev/rules.d/ | sed 's:.*GROUP="\([-a-z_]\{1,\}\)".*:\1:' | sort -u >udev_groups # cut -d: -f1 /etc/gshadow /etc/group | sort -u "
X programs in RUN rules hang when no X server is present
When xrandr or another X-based program tries to connect to an X server, it falls back to a TCP connection on failure. However, due to
IPAddressDeny in the systemd-udev service configuration, this hangs. Eventually the program will be killed and event processing will resume.
If the rule is for a drm device and the hang causes event processing to complete once the X server has started, this can cause 3D acceleration to stop working with a
failed to authenticate magic error.
|
https://wiki.archlinux.org/title/Udev_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)
|
CC-MAIN-2022-40
|
refinedweb
| 670
| 52.8
|
NAME
vhold, vdrop, vdropl - acquire/release a hold on a vnode
SYNOPSIS
#include <sys/param.h> #include <sys/vnode.h> void vhold(struct vnode *vp); void vdrop(struct vnode *vp); void vdropl(struct vnode *vp);
DESCRIPTION
The vhold() function increments the v_holdcnt of the given vnode. If the vnode has already been added to the free list and is still referenced, it will be removed. The vdrop() and vdropl() functions decrement the v_holdcnt of the vnode. If the holdcount is less than or equal to zero prior to calling vdrop() or vdropl(), the system will panic. If the vnode is no longer referenced, it will be freed. The difference between vdrop() and vdropl() is that vdrop() locks the vnode interlock and then calls vdropl() while vdropl() expects the interlock to already be locked.
SEE ALSO
vbusy(9), vfree(9)
AUTHORS
This manual page was written by Chad David 〈davidc@acns.ab.ca〉.
|
http://manpages.ubuntu.com/manpages/intrepid/man9/vdropl.9freebsd.html
|
CC-MAIN-2015-22
|
refinedweb
| 152
| 72.76
|
Trouble using imported images from Photos
Hi,
I am currently teaching some young kids to code using Pythonista, our current project is Pac Man. As the kids are young I am having to take some shortcuts. For instance instead of building the background with tiles, I just want to load it from an image.
So I have saved some images from the internet and am attempting to load them into my Scene as a SpriteNode. I can import them into Pythonista without any issue, however when I try to use them in the code I get strange errors. Sometime it is ‘could not load image’, but other times it gives errors on future lines, such as if you forget a semi colon.
My image is in the same folder as the code, and I have tried lots of different images. One time one image worked, so I deleted it and tried again (need to ensure it works for kids) and it failed.
I am on iOS11 with the latest version of Pythonista. Has anybody ne experienced this issue or have an ideas?
‘’’
from scene import *
import sound
import random
import math
from joystick import Joystick
from player import Player
from tile import Tile
from direction import Direction
A = Action
class MyScene (Scene):
def setup(self):
self.background_color = '#000000' self.background = SpriteNode('IMG_0204.PNG') self.background.position = self.size.width / 2, self.size.height / 2 self.add_child(self.background)
‘’’.
i added a try catch block, wasn’t sure how to catch the error though. But strangely even trying to list the current dir is not working. I’m not much of a python programmer, am a Swift coder, but I realise now that the strange errors are actually due to it throwing an exception in the init method. My errors happen in other methods due to the rest of the init method not being run.
I did:
‘’’
class MyScene (Scene):
def setup(self):
self.background_color = '#000000' #print(os.listdir('.')) try: self.image = ui.Image('IMG_0204.PNG') except: print(os.listdir('.'))
‘’’
I am now thinking it may be something to do with directory length. This project is anpbout 5 sub folders deep.
Tried that too, same issue, thanks anyways.
Thanks for that, exception is ‘could not load texture’
Had to remove ui.image.named as I couldn’t convert it to a texture for SpriteNode
Exception doesn’t really help us much, this is a weird one.
‘’’
try:
self.background = SpriteNode('IMG_0202.PNG')
except Exception as e:
print(str(e))
‘’’
@iOSBrett
|
https://forum.omz-software.com/topic/5141/trouble-using-imported-images-from-photos
|
CC-MAIN-2022-27
|
refinedweb
| 419
| 73.98
|
Bug :.
For example, to create a new console application we only need to execute the following command
e:\test\new\dotnet new console
When this command is executed it will create two files, one with csproj extension and the second one with cs extension for you
new.csproj
program.cs
The contents of the program.cs file will be
using System; namespace new { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
If you compile this using the dotnet build command, the operation will fail and will get the following errors
Program.cs(3,11): error CS1001: Identifier expected [E:\test\new\new.csproj]
Program.cs(3,11): error CS1514: { expected [E:\test\new\new.csproj]
Program.cs(3,11): error CS0116: A namespace cannot directly contain members such as fields or methods [E:\test\new\new.csproj]
Program.cs(4,1): error CS1022: Type or namespace definition, or end-of-file expected [E:\test\new\new.csproj]
Build FAILED.
Issue
So why did this happen? If you go through the code that was generated by the templating engine closely, you can see that the namespace is called new. It is a C# keyword and cannot be used to define a namespace.
So you may now be thinking that why does the templating engine used that while generating the code. It's because we didn't specify a name for the project while creating it using the dotnet new command. So the templating engine took the name of the current directory for that and we ended up with a project file called new.csproj and used the same name for defining namespace too.
This issue has been reported to Microsoft and is still in Open State. You can track the progress of it in GitHub where the repository is hosted.
"dotnet new" can generate invalid code if directory name is not a valid C# namespace identifier
Workaround
So for the time being, you can get rid of this error by specifying a name for project while using the dotnet new command as shown below
dotnet new -n TestProj console
|
https://techrepository.in/bug-dotnet-cli-template-engine-produces-invalid-code-if-name-of-the-directory-is-a-valid-c-keyword
|
CC-MAIN-2018-39
|
refinedweb
| 351
| 54.93
|
So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?
PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The RFC for closures give a good example:
function replace_spaces ($text) { $replacement = function ($matches) { return str_replace ($matches[1], ' ', ' ').' '; }; return preg_replace_callback ('/( +) /', $replacement, $text); }
This lets you define the
replacement function locally inside
replace_spaces(), so that it's not:
1) Cluttering up the global namespace
2) Making people three years down the line wonder why there's a function defined globally that's only used inside one other function
It keeps things organized. Notice how the function itself has no name, it simply is defined and assigned as a reference to
$replacement.
But remember, you have to wait for PHP 5.3 :)
|
https://www.codesd.com/item/closures-in-php-and-hellip-what-exactly-are-they-and-when-would-you-need-to-use-them.html
|
CC-MAIN-2019-18
|
refinedweb
| 183
| 60.24
|
4. I/O Tutorial¶
Before getting into machine vision topics we’re going to talk about I/O pin control on your OpenMV Cam. It’s important you know how to toggle I/O pins, transmit and receive serial data, and put your OpenMV Cam to sleep so that you can create a system that’s able to “sense”, “plan”, and “act” in one package.
First, let’s take a look at your OpenMV Cam’s pinout below:
Depending on the model of your OpenMV Cam you have 9-10 general purpose I/O pins available which can be used for low-speed digital input and output. Note that we use STM32 processors which have 5V tolerant I/O pins so you can hookup your OpenMV Cam directly to an Arduino or other 5V device without worry. The I/O pins are quite beefy too and can source or sink up to 25 mA each.
Anyway, different I/O pins have different special functions. P0-P3, for example, are your OpenMV Cam’s SPI bus pins which you can use to control SPI devices. P4-P5 are your OpenMV Cam’s Asynchronous Serial or I2C bus bins to talk serial or I2C. P6 is your OpenMV Cam’s ADC/DAC pin for 0V to 3.3V input and output. And P7-P8 (or P7-P9) are your OpenMV Cam’s Auxiliary I/O pins.
4.1. The PYB Module¶
All microcontroller I/O functionality is available from the
pyb (Python
Board) module. You just need to
import pyb in your script to get access to
it. Once imported you’ll have access to the ADC, CAN, DAC, I2C, Pin, Servo, SPI,
and UART classes along with being able to control the board’s power consumption.
Note
The tutorial is not complete at all right now.
|
http://docs.openmv.io/openmvcam/tutorial/io_tutorial.html
|
CC-MAIN-2017-26
|
refinedweb
| 305
| 69.72
|
See also: IRC log
Present: Jonathan, Mike, Martin, David, Hugo, Eric, Michael
Regrets:
Chair: DavidF
Scribe: UNKNOWN
<hugo> Agenda:
<hugo> Reading from
... DONE: Marsh to send email to member ws-cg list to ask where motivation for OASIS coordination meeting
... ACTION: David to check about possibility of collocating a f2f with XML2003 [IN PROGRESS]
... XMLPWG is leaning towards the West Coast
... HH thinks that rooms are available between Sat and Fri
... DONE: Hugo to formulate a concrete proposal (for Plenary w/ OASIS at XML2003)
... DONE: Hugo to get a list of OASIS TCs interested
... see agenda item
... ACTION: ST to formally ask WSChor if they have any dependencies on Schema [IN PROGRESS]
... DONE: Philippe investigate WD listings on TR page
... see
... DONE: PH to copy XMLP WG on PASWA/WSDL proposal that was sent to WSD WG
... JM: we looked at different options for recording the media type information in a WSDL description
... ... we are going to circulate our proposal among other groups
... ... we may want to publish a Note as a result
... ... we are looking at a magic attribute
... MSM: the lightweight solution, that may be appropriate here, is to use an attribute in a new namespace, and define the semantics of this attribute
<ericm> ack
<hugo> EM: I would like to be included in the review of this
proposal, and we need to have MSM involved too
... HH: the proposal should be presented to the WSCG in order for us to ensure coordination
<davidF> agenda item 4. Tech Plenary scheduling
<hugo> -- XML CG
... I was working on the TP organization
<davidF> ... March 2004 Tech Plenary, I think
<hugo> We now have until 10 October
... (MSM speaking)
... Please send me feedback so that I can try to resolve conflicts
... [ MSM describing the process for resolving conflicts ]
... See:
... ACTION: WG Chairs to look at and to response to Michael
... ACTION 3 = WG Chairs to look at and to response to Michael by Tuesday 7 October
<davidF> - XML CG
<hugo> -- SWeb
<ericm> RDF Core to 2nd last call schedule -
<hugo> -- Choreography
... MC: F2F 2 weeks ago
... ... transitioning from reqs to language
... ... 2 languages proposed, people are working on working out differences and similarities
... ... republication of the requirements document early November (before moratorium)
... -- Architecture
... MikeC: F2F last week
... ... made progress on shape of the document
<davidF> [DavidF notes thatwe are rolling agenda item 5 into the reports, i.e. agenda item 3]
<hugo> ... LCWD targetted for very early 2004
... -- Description
... JM: F2F last week
... ... trying to making decisions on our largest proposals
... ... LCWD for Dec 2003 / Jan 2004
... -- XMLP
... DF: trying to nail down reqs for "attachments" work
... ... we have a draft for a WD to publish
... ... publication aimed for mid-Oct
... ... the LCWD for the spec will hopefully happen by EOY
<davidF> [the XMLP spec is currently called "SOAP MEssage Transmission Optimization Mechanism" or "MTOM"]
<hugo> HH: basically, the WSDL description of a service maps
in a blurry way to SOAP concepts
... JM: the SOAP 1.2 binding is the most underwork part of our spec
<davidF> JM: lack of work on SOAP binding by WSDL reflects interests of WG members
<hugo> HH: the WSAWG needs to work on this, and may have to
work with the WSDWG once they start working on the SOAP binding
... JM: the binding will soon be the next thing we need to focus on
<davidF> JM: WG is very close to closing issues on Part 1 at which time will work on PArt 2 (SOAP binding)
<hugo> DF: this is something that we have been talking about
for a little while
... ... maybe this reflect a lack of interest from the membership
<davidF> HH: maybe lack of interest is more a reflection of a lack of any good topics to discuss
<Marsh> Must go now - hosting another call...
<ericm> hmm... i think i make this point
... davidF, i'm going to have to wrap up for another meeting
... are we extending? or has the meeting adjounred?
<hugo> ... also at XML 2003, a town hall is being organized
... ... WS W3C people around should join in
... MikeC: how will it be organized?
... HH: not sure yet
<ericm> thanks all... got to run
<hugo> DF: this seems like the management asking us to do two
things: meeting with OASIS, and do a town hall
... HH: this is what we hear from the AC the most: that we need to coordinate
... EM: yes, and we usually have little guidance over how to proceed
... HH: I think that this will be useful feedback to the AC
... ... our WG haven't received much feedback from OASIS; I don't know if it's because their TCs have no comments or if the bar to raise comments is somehow too high and information is not passing through
... ... it would be good to know
|
http://www.w3.org/2002/ws/cg/3/09/30-minutes.html
|
CC-MAIN-2014-35
|
refinedweb
| 800
| 74.29
|
Writing software has become an art. I have always felt that programmers who write software that targets a "windowing" environment have one of two choices:
In my experience, I have found that if the software looks good or exciting or just generally appealing to the end user, the process of adoption of the software in the user's life becomes less painful. Developers who take pride in presenting a "beautiful" user interface to their technology that the user never sees can consider themselves artists in their own right.
In an effort to make my software more "beautiful", I've created the CKCSideBannerWnd class. The class brings to life the concept of banners, which can be used to give the user context as to what the purpose is of the current window that they are staring at.
CKCSideBannerWnd
Every time I use software, I always take notes of what I liked about the UI, what I didn't like, what was a good idea, what wasn't and, more importantly, why. One of the concepts that I've always enjoyed is that of a banner (like those found in InstallShield/Wise installation wizards, CPropertyEx derived wizards, etc).
CPropertyEx
Personally, I feel that those kinds of "well placed" banners give the software UI a more appealing, more professional look. So I took it upon myself to go and whip up a class that can pretty much do what the mentioned banners can do, but a little bit more (like attaching the banner to any edge of a window).
I also felt that the programmer should not have to worry about making allowances for the banner, and that it should be a quick exercise to attach a banner to any window. I have to admit, 2 of my own software packages have already been "upgraded" with the banner control
First off, to use the CKCSideBannerWnd class, you will need to include the following files in your project:
You will also need to copy the WndUtil.h file into the same directory as the KCSideBannerWnd.* files. Once you have the class at your disposal, using it is simple. To attach a banner to a dialog, add a member to your dialog class like this:
// YourDialog.h file
#include <span class="code-string">"KCSideBannerWnd.h"</span>
class CYourDialog : public Dialog
{
public:
CYourDialog();
// ...
// other declarations..
protected:
CKCSideBannerWnd m_banner;
};
Now add the following BOLDED code below to your OnInitDialog() function:
OnInitDialog()
BOOL CYourDialog::OnInitDialog()
{
CDialog::OnInitDialog();
// usual MFC wizard code...
// add the banner
m_banner.Attach(this);
}
If your dialog has the sizing borders, override the OnSize() function and add the BOLDED code below:
OnSize()
void CYourDialog::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
if ( m_banner.m_hWnd )
m_banner.UpdateSize();
}
CKCSideBannerWnd can be attached to any other window, as well. Simply follow the above mentioned steps for attaching the banner to views, etc.
The basic working of the control is as follows:
Attach()
The beauty of this technique is that the programmer does not specifically have to make space for the banner on any of his/her already defined dialogs or windows. Just a simple attach and the control will make room for itself.
This article would have been published a lot sooner had it not been for an interesting nuance that I ran into with Windows and its combobox handling. I had been testing this control on a number of different dialogs and everything was working great, until I used it on a dialog box which contained 2 combobox controls.
When the banner was attached, the combobox controls "lost" their ability to display selected text or text that had been entered by the user on the keyboard. In fact, it seemed as if the edit control of the combobox had just stopped working. (The listbox control worked just fine )
I posted to the forums, but no one seemed to be able to give me an answer as to why this was happening. So off I went on a bug(??) hunt to see what I was doing wrong to cause combobox controls to partially stop working.
What I found eventually was that when EnumChildWindows() is called, and it in turn calls the user supplier handler with each child HWND, one of the children that it found was in fact the edit control of the combobox. The problem came in with me moving the actual edit control, as well as the combobox control.
EnumChildWindows()
HWND
The solution to this problem was to add a check in the enumeration function which called GetParent() against the so-called child HWND and checked that the parent was in fact that parent as I knew it (the dialog or owning window). The edit control of the combobox control did in fact return the combobox's HWND as its parent and, since I was no longer moving both combobox and its contained edit control, everything worked great.
GetParent()
BOOL Attach(CWnd* pWnd, unsigned int uFlags =
KCSB_ATTACH_LEFT, unsigned int uiID = 0xFFF0)
Call this function to attach the banner to a parent window.
uFlags can be on of the following (Exclusive Flags):
uFlags
KCSB_ATTACH_LEFT
KCSB_ATTACH_TOP
KCSB_ATTACH_RIGHT
KCSB_ATTACH_BOTTOM
The uiID is the ID that will be used by the parent to refer to this control. It is defaulted to 0xFFF0.
uiID
void SetSize(int nSize)
Adjusts the size of the banner. This is relative in terms of adjusting either the height or the width of the banner and is dependent on where the banner is positioned. In other words, if the banner is on the the left or right, the width will be adjusted. If the banner is on the top or bottom, the height will be adjusted.
int GetSize()
Returns the current size of the banner.
void UpdateSize()
Call this when the size of the parent window has changed.
void SetPosFlag(unsigned int uFlags)
Call this to reposition the banner. The same flags apply as discussed in Attach().
unsigned int GetPosFlag()
Returns the current position flag.
void SetFillFlag(unsigned int uFlag)
Call this to set the fill type of the banner. Possible values are:
KCSB_FILL_FLAT
SetColBkg()
KCSB_FILL_GRADIENT
SetColBkg2()
KCSB_FILL_TEXTURE
SetTexture()
unsigned int GetFillFlag()
Returns the current fill flag.
void SetTitle(const char* lpszTitle)
Sets the title (main string) of the banner.
CString GetTitle()
Returns the current title of the banner.
void SetCaption(const char* lpszTitle)
Sets the caption (secondary string) of the banner.
CString GetCaption()
Returns the current caption of the banner.
void SetColBkg(COLORREF col)
Sets the primary background color. When a gradient fill is active, this will be the color that the gradient starts at.
COLORREF GetColBkg()
Returns the primary background color.
void SetColBkg2(COLORREF col)
Sets the secondary background color. When a gradient fill is active, this will be the color that the gradient will move towards. In flat fill mode, this color serves no purpose.
COLORREF GetColBkg2()
Returns the secondary background color.
void SetColEdge(COLORREF col)
Sets the color of the edge.
COLORREF GetColEdge()
Returns the color of the edge.
COLORREF SetColTxtTitle(COLORREF col)
Sets the color of the title text.
COLORREF GetColTxtTitle()
Returns the color of the title text.
COLORREF SetColTxtCaption(COLORREF col)
Sets the color of the caption text.
COLORREF SetColTxtCaption()
Returns the color of the caption text.
void SetEdgeOffset(CSize szOffset)
Sets the XY offset of the title text from the edge.
CSize GetEdgeOffset()
Returns the XY offset of the title text from the edge.
void SetCaptionOffset(CSize szOffset)
Sets the XY offset of the caption from the start of the title. In other words, if the edge offset is (5, 5) and the caption offset is also (5, 5), then the caption will be offset 5 pixels away from the title.
CSize GetCaptionOffset()
Returns the XY offset of the caption text relative to the title.
void SetTitleFont(CFont* pFont)
Sets the font used to draw the title text.
void GetTitleFont(LOGFONT* pFont)
Returns the font used to draw the title text in the LOGFONT structure passed into the function.
LOGFONT
void SetCaptionFont(CFont* pFont)
Sets the font used to draw the caption text.
void GetCaptionFont(LOGFONT* pFont)
Returns the font used to draw the caption text in the LOGFONT structure passed into the function.
bool SetIcon(HICON hIcon,
UINT uiIconPos = KCSB_ICON_RIGHT | KCSB_ICON_VCENTER,
bool bSelfDelete = true)
Sets the ICON that will be drawn in the banner. bSelfDelete indicates to the control whether you will be deleting the HICON resource (bSelfDelete = false) or whether the control can delete it when it's no longer needed (bSelfDelete = true).
bSelf
HICON
bSelfDelete = false
bSelfDelete = true
uiIconPos can be one or more of the following values:
uiIconPos
KCSB_ICON_LEFT
Draws the icon on the left of the banner. If the banner is attached to the left of the window, the icon will be drawn at the bottom. If the banner is attached to the right of the window, the icon will be drawn at the top.
Note: This flag cannot be combined with the KCSB_ICON_RIGHT flag.
KCSB_ICON_RIGHT
Draws the icon on the right of the banner. If the banner is attached to the left of the window, the icon will be drawn at the top. If the banner is attached to the right of the window, the icon will be drawn at the bottom.
Note: This flag cannot be combined with the KCSB_ICON_LEFT flag.
KCSB_ICON_TOP
Draws the icon at the top of the banner. If the banner is attached to the left of the window, the icon will be drawn on the left. If the banner is attached to the right of the window, the icon will be drawn on the right.
Note: This flag cannot be combined with the KCSB_ICON_VCENTER or KCSB_ICON_BOTTOM flags.
KCSB_ICON_VCENTER
KCSB_ICON_BOTTOM
Draws the icon vertically centered in the banner.
Note: This flag cannot be combined with the KCSB_ICON_TOP or KCSB_ICON_BOTTOM flags
Draws the icon at the bottom of the banner. If the banner is attached to the left of the window, the icon will be drawn on the right. If the banner is attached to the right of the window, the icon will be drawn on the left.
Note: This flag cannot be combined with the KCSB_ICON_VCENTER or KCSB_ICON_TOP flags
void SetIconPos(UINT uiIconPos)
Set the icon's position in the banner. Use the flags described in SetIcon().
SetIcon()
UINT GetIconPos()
Returns the icon positional flags (refer to SetIcon()).
void SetTexture(HBITMAP hBitmap, bool bSelfDelete = true)
Sets the bitmapped texture that will be used to draw the background when the control's fill flag is set to KCSB_FILL_TEXTURE (See SetFillFlag()). The bSelfDelete flag indicates whether you will delete the HBITMAP resource (bSelfDelete = false) or whether the control can delete it when it no longer needs it (bSelfDelete = true).
SetFillFlag()
HBITMAP
HBITMAP GetTexture()
Returns the HBITMAP of the texture that is used to draw the textured background.
Personally, I have never written a control that "makes space" for itself, and the concept has grasped my imagination somewhat. I have been contemplating the idea of developing a background app/service that monitors all HWND creations and attaches a banner to all windows of say, type DIALOG. This would merely be for purposes of fun and educational value... but still a cool idea, I think.
#pragma comment(lib, "MSIMG32.LIB")
GetColTxtTitle()
SetColTxtTitle()
GetColTxtCaption()
SetColTxtCaption().
|
http://www.codeproject.com/Articles/5269/CKCSideBannerWnd-An-MFC-Banner-Control-that-Can-Ad?fid=25061&df=90&mpp=50&sort=Position&spc=Relaxed&select=3609806&tid=669776
|
CC-MAIN-2015-18
|
refinedweb
| 1,866
| 62.27
|
I'm trying to get this to work... here is the pastebin if you'd rather look at it through that
Anyway, when using an iterator to call the Draw() method nothing actually draws. Pressing space in the example will draw them as Draw() is being called directly.
What am I doing wrong/how can I correct this?
Hehe don't ask why I used gnolam's avatar.
EDIT:
Here is the fix for this.. is there anyway to do this with the above example?
=-----===-----===-----=I like signatures that only the signer would understand. Inside jokes are always the best, because they exclude everyone else.
If Bitmap doesn't have a proper copy constructor, it won't be copied, and it won't be displayed. Maybe checking IsValid inside the Draw method will tell you something?
When you push the a, b, c, and d objects into the vector, you push the actual objects, so you actually make a copy of them. When this happens, OpenLayer has to send a copy of the Bitmap to the graphics card. I don't know if it handles this properly. One possible fix is to use a Bitmap* inside the class, and continue to use a vector of objects, but the pointer method is superior for most cases in terms of performance.
-- Tomasu: Every time you read this: hugging!
Ryan Patterson - <>
FYI: CGamesPlay was a major contributor to this being fixed :-D.
Another error that I'm having that CGamesPlay said was the right syntax and I thought so myself is this line:
...
vector < Avatars* > CurrentList, AvatarList;
// Avatar List gets filled so don't worry there is stuff in it
...
CurrentList.reserve(MAX_AVATARS_ON_SCREEN);
for(int i = 0; i < MAX_AVATARS_ON_SCREEN; i++)
CurrentList.push_back(AvatarList.at(rand() % AvatarList.size()));
*.at() should return a pointer and so it compiles correctly. The problem is that it stops things from being drawn and causes my CPU to be 100% and lags like crazy. I comment that line out and "bam" it's fixed. Is their a correct way to do this or is their a workaround like maybe setting a temp Avatar instance setting it equal to *.at(...) then pushing it to the back of CurrentList? I would rather have a one line simple thing.
What is the value of MAX_AVATARS_ON_SCREEN?
Like I said: that line of code is fine. Show the part where you draw, for instance.
MAX_AVATARS_ON_SCREEN is set to 15 for now.
This is how they're drawn:
bool Game::DrawAvatars()
{
vector< Avatar* >::iterator curAvatar;
for(curAvatar = CurrentList.begin(); curAvatar != CurrentList.end(); curAvatar++)
(*curAvatar)->Draw();
//Log::log("CurrentList.size() = %i", CurrentList.size());
return true;
}
This is the Avatar's Draw method:
bool Avatar::Draw(void)
{
this->m_Avatar.Blit(10, 10);
return true;
}
EDIT: I hate having difficult questions that no one knows the exact answer to or just ignore me
I wonder if you've found the answer yet?
Donno why its hanging there, likely a copy paste error or something.
CurrentList.reserve(MAX_AVATARS_ON_SCREEN);
for(int i = 0; i < MAX_AVATARS_ON_SCREEN; i++)
CurrentList.push_back(AvatarList.at(rand() % AvatarList.size()));
Should be:
#include <algorithm>
CurrentList.resize(AvatarList.size());
random_sample(AvatarList.begin(), AvatarList.end(), CurrentList.begin(), CurrentList.end());
Here is the fix for this.. is there anyway to do this with the above example?
Its not pretty:
How is my posting? - iPad POS
I wonder if you've found the answer yet?
Haha nope, well now that DD has posted I might have.
To DD (Or anyone else):
I'm reading about random_sample() from cppreference.com and it seems that it confuses me haha.AvatarList holds 1 copy of each avatar, now CurrentList is supposed to be holding the actual avatars you'll see and fight. When one dies a random avatar from AvatarList will be popped onto CurrentList. Now will random_sample() work for what I'm doing (just for the initialization though)? Does it randomly put them into CurrentList depending on CurrentList's size? The way it looks it seems like CurrentList needs to already be full .
random_sample(AvatarList.begin(), AvatarList.end(), CurrentList.begin() + dead_avatar_index, CurrentList.begin() + dead_avatar_index + 1);That will make it replace 1. I have no idea why you wouldn't just use your code.
I would use my code because it doesn't work. It may be logically correct but its causing things to not work, I mean I can rar it up again and show you how it doesn't work
Edit: I keep getting the error: random_sample().. first use of this function. And I've included algorithm >.< Rebuilt all... Baaaah.Eww totally had to include <algo.h> to get it to work I dunno why.
Edit: I keep getting the error: random_sample().. first use of this function. And I've included algorithm >.< Rebuilt all... Baaaah.Eww totally had to include <algo.h> to get it to work I dunno why.
Err, maybe std::random_sample or "using namespace std;" would help? These seem like errors you get when you forget about a namespace . This and the fact that <algorithm> probably only wraps <algo.h> in a namespace .
---------------------------[ ChristmasHack! | My games ] :::: One CSS to style them all, One Javascript to script them, / One HTML to bring them all and in the browser bind them / In the Land of Fantasy where Standards mean something.
When one dies a random avatar from AvatarList will be popped onto CurrentList.
[edit]Ah I see. Yes your code is better suited for this task. Just don't use reserve. Its generally useless unless you really know what you're doing. And even when you do, it pretty much will only apply to one compiler.
Err, maybe std::random_sample or "using namespace std;" would help?
Tried that and I am already using the standard namespace.
Just don't use reserve.
Then how do I set the size that CurrentList is going to be filled up to?
vec.resize(newsize);
Bah I never saw resize() on cppreference.com, I always overlook things. That's totally what I wanted to use in my other projects too not reserve(). Umm where can I get an update for all the standard libraries because no matter what I try I can't get random_sample() to work with <algorithm>.
What compiler are you using?
MinGW (the version that came with Dev-C++ beta 5 [4.9.9.2 or whatever])
Should support it just fine. Paste some code.
Paste some code.
#define MAX_AVATARS_ON_SCREEN 15
...
#include <algorithm>
...
CurrentList.resize(MAX_AVATARS_ON_SCREEN);
random_sample(AvatarList.begin(), AvatarList.end(), CurrentList.begin(), CurrentList.end());
When I use #include <algo.h>I get errors when trying to draw my CurrentList using (*iter)->Draw() My logfile is full of
 is not valid
for all of my Avatars in CurrentList. I changed CurrentList and AvatarList from vector < Avatar* > to vector < Avatar > and I got their names instead of that weird A but they were still not valid >.<. I'm thinking about trying this with an array instead of a vector. Or maybe try and STL::List (but lists and vectors are so similar I wouldn't see how that would effect things.
Could you show the code that wrote the "Â is not valid", as well as the full code for the Avatar class?
Avatar.hpp
Avatar.cpp
Ok to get the log file to produce this:
This is what I didGame.cpp area:
Add a copy constructor to your object:
Avatar::Avatar(const Avatar& other)
{
Log::error("Object not allowed to be copied");
}
Same log file. The object isn't being copied. Is that good or bad?
Good
Unfortunately, I'm at a loss. Start dumping your objects at very frequent intervals and see what causes them to screw up. Make sure they are loaded correctly.
Baaaaah, this is what always defers me away from programming sometimes. Everything always looks right, seems like it should work... BAM! RUN TIME ERRORS that are hard as hell to solve.
|
https://www.allegro.cc/forums/thread/589963
|
CC-MAIN-2018-17
|
refinedweb
| 1,314
| 76.82
|
C++ Annotated: Jan – Mar 2017
Today we are happy to share our next compilation of C++ news with you.
C++ Annotated: January – March 2017
In this edition:
C++ in 2017
The C++ ecosystem
This blog post about the C++ ecosystem in 2017 is worth a special mention. Written in January, it overviews nicely the main expectations and trends, and not just about the language. While C++17 is indeed the main topic for this year’s discussions (as well as the features that failed to be included and so postponed for the future), it is also about adopting new standards and libraries, and of course the community including user groups and conferences.
C++17
As C++17 is approved, pending national body comments, there are lots of resources now where you can find the final feature list, explanatory code samples, committee meeting live threads and committee meeting trip reports. This list by Bartlomiej Filipek is quite useful as it provides code samples for each feature, lists the key compilers (GCC, Clang, MSVC) explaining the versions where the feature is supported, and links to various additional articles. It’s very detailed and includes every small change.
News
Toggles in functions
A tricky problem with bool-typed toggles in functions is covered by this blog post. What at first glance looks like a readability issue, can actually grow into a bug especially inside some overloaded methods. The post discusses several solutions, including one proposed by the blog author.
Clang-tidy: easy start
Clang-tidy is the topic of regular blog posts, lightnings and even big conferences talks, like the one recent at C++ Russia 2017. Indeed, it’s a quick and easy way to get an analysis of your code base and even apply some fixes instantly.
If you’d like to try Clang-tidy, this blog post is a good place to start. Sharing a basic example where code modernization is needed and some cases with missing override attributes, it goes through the setup instruction step by step and teaches you to run a single check, apply a fix, and analyze the whole project (taking into account all the compile flags, etc.).
Continuous integration with C and C++
The challenges of CI for C and C++ are covered in this Conan blog post. It starts by explaining the C and C++ building processes, showing how the build systems can help with the incremental build. Then it goes on to binary management questions and incremental build complexity with regards to CI. The benefits of Conan Package Manager in this area are also mentioned, including re-build logic, profound dependency management, a way to specify build order of dependencies, and so on.
Inserting elements into STL container
In his blog, Fluent C++, Jonathan Boccara discusses the problem with inserting several elements into an STL container efficiently. This provides an interesting overview of std::back_inserter and std::copy. The main idea is that knowing the size of the data to be inserted can help a lot in your optimization tasks.
Refactoring principles
Arne Mertz is well-known for his Simplify C++ blog and especially his series of posts about code refactorings. This time he writes about the basic refactoring principles – sounds philosophical, but they’re very useful in practice. What are these principles? In a nutshell, go with small steps that you can compile, test and commit; select a direction from the very beginning and follow it, postponing not-related changes; and don’t be afraid to break code styles, duplicate code and do other things that you usually try to avoid, if that is really necessary as an intermediate step in your refactoring procedure.
Readable modern C++
At the end of February, Timur Doumler joined C++ Russia 2017 and the Saint-Petersburg C++ user group meetup to talk about readable code and especially readable modern C++. The talk highlighted the general principles, like naming conventions, the necessity of comments, and eliminating code redundancies. Timur also put forth his ideas on how to make C++ more readable with the latest standards (from C++11 to C++17). The meetup version of the talk was recorded and is available on YouTube (with slides). He also delivered this talk at the C++ London meetup group.
Concepts
This is no rocket science but a simple example of when Concepts could be beneficial. The article starts from a very simple arithmetic code sample, eliminating the compilation issues one by one. But then, it adds Concepts and gets all of them at once. Sounds good, doesn’t it? Concepts are not coming to C++17 (they still require more work and polishing in details), but that doesn’t mean you can’t start thinking about where it makes sense to adopt them in your code base.
To Catch a CLion
Catch is a cross-platform test framework for C++. It is known for its easy setup – only a single header is required, and no external dependencies are needed. Not to mention easy-to-use test cases, which are designed as self-registering functions or methods and can be divided into sections.
While this framework is not as popular as Google Test or Boost Test, it’s seeing more and more interest from the community. Phil Nash, the author of Catch, is now working at JetBrains as a developer advocate and has already influenced integration into two (out of three) C++ tools by the vendor, ReSharper C++ and CLion. This article in the CLion blog shares some useful tricks around its integration into CLion and the use of the framework itself.
The future of the C++ job market
If you feel like discussing the C++ job market and its future, go ahead and join this thread on reddit, but first invest 5 minutes into reading this article from Bartlomiej Filipek. Why? It offers a nice summary of the areas where C++ is currently applicable and lists the language’s advantages. It also gives advice for newcomers and summarizes the results of a Twitter poll on whether the C++ job market is stable, decreasing or growing.
emBO++
In case you are interested in embedded development, you’ll be glad to learn about a new conference dedicated to it, entitled emBO++ and driven by Odin Holmes. This year the talks covered Standardese (so called next-generation Doxygen), clang tooling for embedded systems, profiling and many more topics. Listen first hand to Odin at CppCast, a developer who is really keen on microcontrollers. The discussion covers his general impression, an overview of the audience, and of course technical specifics around embedded development.
Compiler Explorer goes Patreon
Compiler Explorer is a great online tool for seeing what your C++ code compiles down to when various compilers are used. Matt Godbolt, the author and maintainer, has now opened a Patreon page for the project, primarily to cover the hosting costs. It has also given him momentum to accelerate ongoing development, at least for now, so do check it out.
Releases
CLion
CLion 2017.1 was released at the end of March with nearly full support for C++14 (now only constexpr left), nested namespaces from C++17, precompiled headers support, disassembly view in debugger in case of GDB, support for the Catch test framework. There is also experimental support for the Microsoft Visual C++ compiler, so if you are not a fan of MinGW (MinGW-w64) or Cygwin, that’s something good for you to try out in CLion.
The CLion team also announced the preliminary roadmap for 2017.2, coming later this year. The plan is to focus on bug fixing, performance improvement and polishing of the existing functionality. Check it out in CLion’s blog.
ReSharper C++
ReSharper C++ 2017.1 brought support for Visual Studio 2017 and CMake projects, extended the list of supported postfix templates, and added some new options in formatting. It also came with lots of enhancements for inspections and code cleanup tasks. For more details see the ReSharper C++ site.
Visual Studio
Talking about Visual Studio 2017, we should mention improvements in its code analysis, including C++ Code Guidelines checkers. Example include marking objects as const unless you are writing to them, marking objects as const if passed to a function that doesn’t modify them, and using constexpr for values that can be computed at compile time (and same for functions).
Besides, Visual Studio 2017 supports several C++ compilers to serve various needs and use cases: MSVC, Clang, and GCC.
Qt Creator
Qt Creator 4.3 Beta was announced in late March. In terms of CMake support it now comes with CMake server, which is an alternative way to get project information (instead of parsing the generators output). It also supports different contexts for file parsing and experimental Clang-based rename refactoring.
That just about covers it for March. Talk to you later!
The C++ Team
3 Responses to C++ Annotated: Jan – Mar 2017
ai says:April 18, 2017
Very, very useful post!
Alessandro Stranieri says:April 21, 2017
Thanks for the post! Always very interesting.
Anastasia Kazakova says:April 21, 2017
Thanks for your support!
|
https://blog.jetbrains.com/clion/2017/04/cpp-annotated-january-march-2017/
|
CC-MAIN-2020-45
|
refinedweb
| 1,519
| 60.04
|
Directory Listing
For some experiments
arguments fixed.
remove Super LU from everywhere, we never supported it and never will directly.
remove pastix from everywhere. We never supported it and never will directly.
off-by-one errors.
type fixes in debug mode and savanna lib reference fix.
paso: allow saving to matrix market with >1 rank by collecting matrix on master.
addresses #366. Gauss-Seidel sweeps now only use the main block of the system matrix.
moved Distribution struct to escript and updated domains accordingly. We can now build the full escript suite without paso (-:.
fix a typo introduced in r6144. Buildbot reported success since then but was actually segfaulting!!
now refraining from adding all libraries to all targets. So we don't link unnecessary libraries, e.g. escript does not need parmetis etc...
last round of namespacing defines.
more namespacing of defines.
starting to 'namespace' our way too generic defines...
two fixes for long int build.
merging trilinos branch to trunk. We can now build with trilinos and use it instead of paso for single PDEs. There are some more things to be done...
Relicense all the things!
grr, another revert..
clear error code when restarting solver!
more special case issues (segfault due to empty rank).
squashed last instances of checkPtr.
Major rework of our exceptions. We now have specific AssertException NotImplementedError ValueError which translate to the corresponding python exception type. I have gone through a few places and replaced things but not everywhere.!!
Merged pasowrap into paso. Unfortunately, this required touching quite a few files. build_shared now defaults to true but will likely disappear altogether once esysUtils disappears.
removed obsolete comment.
fix for Bug #326
Commented use of makeZeroRowSums in Transport solver, see bug #326.
fixing UMFPACK numerical issues due to implicit METIS ordering not existin gin newer UMFPACK versions (>5.2)
pushing release to trunk
currently is now currecntly spelled
excetion for mpi and direct solver
Fixing institution name to comply with policy
Changes brought across from the debian preparation branch.
IS_NAN removed
Updating all the dates
release changes
Adding missing include which clang noticed.
updated UMFPACK def in places...
Some more long-index work.
More long-index work. Added scons option 'longindices'. Parts will not compile yet if set to true.
more work towards allowing non-int indices.
Work towards allowing non-int index type.
Merging ripley diagonal storage + CUDA support into trunk. Options file version has been incremented due to new options 'cuda' and 'nvccflags'.
Added ABS which was obviously missing in a function that is used to create balance vector in paso.
Separated generation of paso matrix pattern and coupler/DOF Map in Rectangle. This is in preparation for introducing non-Paso matrices. Brick still to do..
Continuing the compiler assistance package...
This commit is brought to you by the number 4934 and the tool "meld". Merge of partially complete split world code from branch.
trying to make centos happy.
whitespace only changes.
all of paso now lives in its own namespace.
don't report an error when there isn't one.....
paso: starting to polish
fixing mkl build.
cleansing
some mopping in paso
paso util sweep
More vacuuming.
paso::Options.
I fink I broke it - now I thixed it.
checkpointing paso::Preconditioner.
Fixing non-mpi build.
"Some" SystemMatrix clean up.....
removing unused MIS
fixing MKL compile.
Removed obsolete file, reverted verbosity of test and a bit more cleanup.
checkpointing some SparseMatrix cleanup.
Pattern shared ptrs
SystemMatrixPattern shptr
Coupler/Connector shared ptrs.
paso::SharedComponents now header-only and shared ptr managed.
paso::Distribution instances are now managed by a boost::shared_ptr, methods are all inline.
Removed some obsolete checkPtr's. More to come...
added missing const.
put SparseMatrix into paso namespace, accompanied by minor code cleanup.
code cleanup of paso::SparseMatrix_MatrixVector and variants. Mostly a no-op.
changing more awkward logic into more obvious (and correct, though i doubt a negative length ever happens) logic
I changed some files. Updated copyright notices, added GeoComp.
include cmath in all cases rather than math.h - the mathinf for intel on windows is still there (in part because we have no way to test if it is still relevant)
use enums
Steube!!!!!
Remove bool_t Part of random.
Removing spurious usage of C compiler: -Changed all scons tests to use C++ compiler -Renamed paso profiling files (unused) -Updated most options files (removal of options and updated comments)
Hopefully addresses mantis721
Finley changes that were held back while in release mode - moved more stuff into finley namespace.
More valgrind suppressions and memory leak fixes identified in various places.
fix problems revealed on freebsd
Reapply some of the spelling fixes that got lost....
Bringing the changes from doubleplusgood branch. Can't merge directly because svn doesn't transfer changes to renamed files (mutter grumble).
Assorted spelling fixes.
Corrected some spelling.
Removed some incorrect ACcESS copyright attributions [2010 or later] since ACcESS did not exist at that point. Also added 2013 to a couple of files which I missed.
Round 1 of copyright fixes
A bit of doco cleanup.
There is now a coherent implementation of gravity and magnetic forward model including an update of the user's guide.
More edits + removing pyvisi from trunk
First pass of updating copyright notices
Merged symbolic branch into trunk. Curious what daniel and spartacus have to say...
darcy solver removes hydrostatic pressure from problem now
offset removed: not clear why this was there)
LINEAR_CRANK_NICOLSON solver added
Quick fix for potential invalid memory access in paso.
Fixed OpenMP bug in paso local AMG.
better error reporting from UMFPACK
ode solver added
Assorted spelling/comment fixes in paso.
Prepend our libraries instead of appending. This should fix HYPRE link issue on epic.
New config option build_shared (which replaces share_paso & share_esysUtils). Also enabled building escriptreader library on Windows which should now work in both shared and static mode.
Added missing declspecs in paso. Thanks Terry.
This fixes the bug 616. Problem was that the Coupler used the pattern of original rather than unrolled pattern.
Typo fixed.
Silence some warnings unused var warnings under gcc. gcc-4.6 fixes (mostly initialized-but-unused-var warnings)
Fixed a few warnings emitted by gcc-4.6.
some compile fixes
Ops: AMG MPI chould not be called yet.
some work on AMG MPI
Patch from Terry to fix compilation on Windows with MKL enabled.
more on AMG under MPI
segfault fixed
some compilation fixes
compilation fixes
more compilation fixing
compile problem in AMG fixed.
and more work toward AMG MPI
more work towards MPI AMG!
memory leak in UMFPACK interface fixed
semi-colon is missing
some fixes for MKL lapack
some small fixes
AMG support now block size > 3 (requires clapack or MKL). additional diagnostics for AMG
wrong pointer handed
seg fault fixed.
some clarification on lumping
matrix balance introduced in paso
a more flexiblae version of safeDiv
exposure of AMG options.
some openmp fizes.
This should fix building paso without OpenMP.
bug in sparse matrixmatrix fixed.
output removed/leaned up
last step for a clean up version of the AMG
more clean up work on the AMG
some fixes
complaint from valgrind about an uninitialized value fixed (no impact on result)
bug in initialization step fixed.
old AMLI code collected in a single file. It does not compile and should be merged with RecILU
AMG reengineered, BUG is Smoother fixed.
Removing dead files
Merging dudley and scons updates from branches
Fixed a declaration/definition mismatch.
missing files
more clean up in AMG
some fixes for the case that no direc solver is available.
bug fixed in RILU and test modified.
AMG is using now a simpler interface to the Smoothers.
GS and Jacobi are now used through the same interface.
a more robust version of MINRES (really?)
more code cleaning
missing file
first iteration on Paso code clean up
some diagnostics for time step backtracing added
bug fixed in the Gauss Seidel
bug in ILU0 fixed.
fix to the GaussSeidel.
Put back
Problem with latest MKL should be fixed now. The problem was solving unrolled block matrix with MKL.
Should be faster with openmp. Some ROW-COL conversion.
fix for overflow
some fix for omp
typo fixed.
MPI problem fixed.
reactive solver added.
Gauss_Seidel preconditioner is now SPD.
More openMP corrections
Some openMP corrections
Some optimization on GAUSS_SEIDEL sweeps.
Sweeps bug is fixed and some more comments added about how sweeps computed
C-level lumping switched on
FCT solver rewritten
Fix out of date comment
Fixing non-ansi compliant code
Added MPI aware MIS
some print statements removed.
test for positivity of initial solution in transport solver has been switched on again
printfs removed.
more changes on the cookbook.
Fix for mantis #480 when parmetis is off.
a work around for gcc 4.4 added.
minor compiliation problem under MKL is fixed.
minor adjustments
minor openmp fix
minor
Splitting can be read from file. This is useful for testing..
Paso Testing tools now can select coarseing.The builld_PasoTests target is also added to scons.
Standard coarsening is added to options list.
default coarseneing is Ruge-Stueben.
Post and pre smoothing parameters are added for AMLI. Little bit reengineering according to Axelson's original AMLI paper..
More performance tunning. Sparsity check is added. If Coarse level matrix is denser than 1% then stop.
More openmp calls are added,escpecialy in arg_max method.
First steps toward efficiency. Coarsening process is improved. Some profiling tools are added.
Some openMP calls are removed.
Macro elements are implemented now. VTK writer for macro elements still needs testing.
minor
Some openMP codes in AMG systems are removed for testing.
some clarity in the notations REMOVED changes IN_SET)
AMG on systems not supported yet exeption is added
stopping criteria is slightly changed.
inplace bugs are fixed
minor comments changed
memory leack fixed
Pattern_free for Aggregiation coarsening is added.
bug with MKL call fixed.
openmp change
a problem with the sparse matrix unrolling fixed.
AMG throws an error now if block size not 1
Updating copyright notices
the line added in RS for symetricity brings factorization failure in heatedblock example
endof line added.
tests for examples added. utest is not working yet.
adjusting to new Paso_Options.
void *solver; is added to Paso_SpaseMatrix struct. Paso_MKL will need this.
Paso_MKL1 supports Paso_SparseMatrix type with offset1
numarray removed from docu; Locator revised.
paso returns now some diagnostics. SCSL has been removed..
Remove the "const from the alpha argument of Paso_SystemMatrix_MatrixVector_CSR_OFFSET0() in order to match it's declaration. This is C, and the double is passed by value, so alpha is by nature const. This is C code, not C++. The const keyword has no place in C..
|
https://svn.geocomp.uq.edu.au/escript/branches/clazy/paso/?view=log&pathrev=6513
|
CC-MAIN-2019-04
|
refinedweb
| 1,765
| 61.53
|
XML can also be used with datasets. The DataSet class, described in Chapter 18, has methods for both reading and writing XML. In this section, you’ll learn how to place XML data in a dataset and how to write data from a dataset to an XML file.
To read data into a dataset, you use the ReadXml method of the DataSet class. This method can work with both XML and schema information. Consider the following XML file, which is like the one that was created using the Videos form presented earlier in this chapter, in the section “Sample Application Using XmlTextWriter”:
<?xml version="1.0" encoding="utf-8" ?> <!--Video Library--> <!--This is a file containing a number of videos.--> <VideoLibrary> <Video> <Title>Gone with the Wind</Title> <Length Measurement="minutes">111</Length> <star>Clark Gable</star> <rating>PG</rating> </Video> <Video> <Title>The Matrix</Title> <Length Measurement="minutes">123</Length> <star>Keanu Reeves</star> <rating>R</rating> </Video> <Video> <Title>Vanilla Sky</Title> <Length Measurement="minutes">109</Length> <star>Tom Cruise</star> <rating>R</rating> </Video> <Video> <Title>Lord of the Rings</Title> <Length Measurement="minutes">168</Length> <star>Frodo</star> <rating>PG-13</rating> </Video> <Video> <Title>Winnie the Pooh</Title> <Length Measurement="minutes">93</Length> <star>Christopher Robin</star> <rating>G</rating> </Video> </VideoLibrary>
The listing for XMLWrite was hard-coded to store an XML file such as the preceding one at C:\Videos.xml. To read this file into a dataset, you should first instantiate a DataSet object, as shown here:
DataSet myDataSet = new DataSet();
After the object has been instantiated, you use the ReadXml method to load the XML data into the dataset, as follows:
myDataSet.ReadXml(@"C:\Videos.xml");
Once this command has been executed, the XML file is loaded into the dataset. You can then manipulate the data just as you can other data stored in a dataset. Refer to Chapter 18 for more information about working with datasets.
The following listing presents a simple form that contains a data grid that displays the primary data in the Videos.xml file:
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace ReadDataSet { /// <summary> /// Summary description for Form1 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.DataGrid dataGrid1; /// <summary> /// Required designer variable /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // TODO: Add constructor code after InitializeComponent call. // Create the DataSet object. DataSet myDataSet = new DataSet(); // Load XML data. myDataSet.ReadXml(@"C:\Videos.xml"); // Bind the dataset to the data grid. dataGrid1.DataSource = myDataSet; dataGrid1.SetDataBinding(myDataSet, "Video" ); } /// .dataGrid1 = new System.Windows.Forms.DataGrid(); ((System.ComponentModel.ISupportInitialize) (this.dataGrid1)).BeginInit(); this.SuspendLayout(); // // dataGrid1 // this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(16, 16); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.Size = new System.Drawing.Size(496, 232); this.dataGrid1.TabIndex = 0; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(528, 262); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.dataGrid1}); this.Name = "Form1"; this.Text = "Read Data Set"; ((System.ComponentModel.ISupportInitialize) (this.dataGrid1)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// Main entry point for the application /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } } }
As you can see, the Videos.xml file is loaded into myDataSet using the ReadXml method. The next two lines of the listing connect the dataset to the data grid and specify which data will be displayed, as follows:
dataGrid1.DataSource = myDataSet; dataGrid1.SetDataBinding(myDataSet, "Video");
In this case, the video information is displayed. The first line sets the data source for the data grid to the dataset you loaded with the XML data. The second line binds the Video data to the control. This binding will cause the Video data to be displayed as a table.
You can also display the video length information if you change the preceding data binding line to this:
dataGrid1.SetDataBinding(myDataSet, "Length" );
When the Videos.xml file was loaded, it was automatically broken into relational tables for you. You’ll need to write the necessary code if you want to rejoin these tables when displaying the information.
Once you have data in a dataset, you can write it to an XML file by calling the WriteXml method. The WriteXml method of the dataset will take care of all the work for you. The following line of code will create a file named NewXml.xml from myDataSet in the root directory of the C drive:
myDataSet.WriteXml(@"C:\NewXml.xml");
You can also specify whether a schema should be included with the file. This is done by including an XmlWriteMode value as a second parameter to the WriteXml method call, as shown here:
myDataSet.WriteXml(@"C:\Filename", writeMode)
The writeMode parameter can be one of the following values:
XmlWriteMode.DiffGram Writes the XML file as a DiffGram, which is a format used to identify current and original version of data elements.
XmlWriteMode.IgnoreSchema Writes just the XML data. If the file contains no data, nothing is written.
XmlWriteMode.WriteSchema Writes the XML data and the schema.
|
http://etutorials.org/Programming/visual-c-sharp/Part+IV+Data+Access+and+XML/Chapter+19+XML/Using+XML+with+Datasets/
|
CC-MAIN-2017-22
|
refinedweb
| 868
| 51.65
|
Conceptually, shell:jirb *is* a compound task. I read that as "in the shell
namespace, execute the jirb task". It isn't logically parametrized at all,
it just happens to be dynamically created. The clincher for me is the fact
that the shell:* namespace is finite and well-defined, whereas test
(which *should
be* logically parametrized) has an unfixed domain.
Daniel
On Mon, Jan 5, 2009 at 5:18 PM, Assaf Arkin <arkin@intalio.com> wrote:
> On Mon, Jan 5, 2009 at 3:00 PM, Alex Boisvert <boisvert@intalio.com>
> wrote:
> >.
>
> buildr test:<not task name> was written in the days of Rake 0.7.3,
> it's a hack, painful to maintain and extend. I've been longed
> convinced its days are over, just didn't get around to do a better
> implementation.
>
> Everywhere else, foo:bar means compound task name, it identifies the
> task being executed. Not so with test, where the last part is an
> argument telling the test task what to do, but expressed as a task
> name.
>
> Not only is an argument conceptually better, the code to implement and
> test it is much simpler, and you can support multiple arguments. Say
> we wanted to give test two arguments, the class name and test name.
>
> If you have shell.using(:jirb) in the project definition and
> shell[jirb] on the command line, that looks consistent to me. One is
> setting default value, the other affecting it by argument.
>
> Assaf
>
> >
> > alex
> >
>
|
http://mail-archives.apache.org/mod_mbox/buildr-users/200901.mbox/%3C5c99d0330901051530j6d4828e8m1fbd34262b6a3594@mail.gmail.com%3E
|
CC-MAIN-2018-13
|
refinedweb
| 244
| 74.08
|
crosvm: aarch64 guest support - removes old ARMv7a (32-bit) bindings as we're only supporting aarch64 guests right now - switches both ARMv7 and aarch64 builds to use aarch64 kvm bindings - adds support for ARMv8 Linux guest with dynamic flattened-device-tree CQ-DEPEND=990894 BUG=chromium:797868 TEST=./build_test passes on all architectures TEST=crosvm runs on caroline TEST=crosvm runs on kevin built with USE="kvm_host" Change-Id: I7fc4fc4017ed87fd23a1bc50e3ebb05377040006 Reviewed-on: Commit-Ready: Sonny Rao <sonnyrao@chromium.org> Tested-by: Sonny Rao <sonnyrao@chromium.org> Reviewed-by: Zach Reizner <zachr@chromium.org>.)
-u)
namespaceing
New code should be run with
rustfmt, but not all currently checked in code has already been autoformatted. If running
rustfmt causes a lot of churn for a file, do not check in lines unrelated to your:
byteorder- A very small library used for endian swaps.
gcc- requires rustc v1.20 or later.
Source code is organized into crates, each with their own unit tests. These crates are:
crosvm- The top-level binary front-end for using crosvm.
devices- Virtual devices exposed to the guest OS.
io_jail- Creates jailed process using
libminijail. architecturs, the seccomp policies are split by architecture.
|
https://chromium.googlesource.com/chromiumos/platform/crosvm/+/2ffa0cbe5bb41beea81fd2d14a7f781747bb955e
|
CC-MAIN-2018-34
|
refinedweb
| 195
| 58.28
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.